text
stringlengths 27
775k
|
---|
package amino.run.policy.dht;
import java.io.Serializable;
public class DHTKey implements Comparable, Serializable {
String identifier;
byte[] key;
public DHTKey(byte[] key) {
this.key = key;
}
public DHTKey(String identifier) {
this.identifier = identifier;
this.key = DHTHash.hash(identifier);
}
public boolean isBetween(DHTKey fromKey, DHTKey toKey) {
if (fromKey.compareTo(toKey) < 0) {
if (this.compareTo(fromKey) > 0 && this.compareTo(toKey) < 0) {
return true;
}
} else if (fromKey.compareTo(toKey) > 0) {
if (this.compareTo(toKey) < 0 || this.compareTo(fromKey) > 0) {
return true;
}
}
return false;
}
public DHTKey createStartKey(int index) {
byte[] newKey = new byte[key.length];
System.arraycopy(key, 0, newKey, 0, key.length);
int carry = 0;
for (int i = (DHTHash.KEY_LENGTH - 1) / 8; i >= 0; i--) {
int value = key[i] & 0xff;
value += (1 << (index % 8)) + carry;
newKey[i] = (byte) value;
if (value <= 0xff) {
break;
}
carry = (value >> 8) & 0xff;
}
return new DHTKey(newKey);
}
@Override
public boolean equals(Object obj) {
DHTKey another = (DHTKey) obj;
if (obj == null) return false;
return another.getIdentifier().equals(identifier);
}
@Override
public int hashCode() {
return identifier.hashCode();
}
@Override
public int compareTo(Object obj) {
DHTKey targetKey = (DHTKey) obj;
for (int i = 0; i < key.length; i++) {
int loperand = (this.key[i] & 0xff);
int roperand = (targetKey.getKey()[i] & 0xff);
if (loperand != roperand) {
return (loperand - roperand);
}
}
return 0;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (key.length > 4) {
for (int i = 0; i < key.length; i++) {
sb.append(Integer.toString(((int) key[i]) & 0xff) + ".");
}
} else {
long n = 0;
for (int i = key.length - 1, j = 0; i >= 0; i--, j++) {
n |= ((key[i] << (8 * j)) & (0xffL << (8 * j)));
}
sb.append(Long.toString(n));
}
return sb.substring(0, sb.length() - 1).toString();
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public byte[] getKey() {
return key;
}
public void setKey(byte[] key) {
this.key = key;
}
}
|
const { Op } = require("sequelize");
const { Task, Class, Score } = require("../models");
const { initRedis } = require("../helpers/redis");
const redis = initRedis();
// const Redis = require("ioredis");
// const redis = new Redis(process.env.REDIS_URL);
const { searchSongs, getSongDetailById, convertLyricsToQuestion, getListeningScore } = require("../helpers/getSongs");
class TaskController {
static async create(req, res, next) {
try {
const { name, description, question, soundUrl, classId } = req.body;
const input = { name, description, question, soundUrl, classId };
const result = await Task.create(input);
res.status(201).json({ result });
} catch (err) {
next(err);
}
}
static async get(req, res, next) {
try {
const { classId } = req.query;
let opt = { where: {} };
if (classId) {
opt.where.classId = classId;
}
const tasks = await Task.findAll(opt);
res.status(200).json(tasks);
} catch (err) {
next(err);
}
}
static async getTaskByClass(req, res, next) {
try {
const { classId } = req.params;
const studentId = req.user.id;
if (!Number(classId)) throw { name: "InvalidMaterialId" };
const classData = await Class.findByPk(classId);
if (!classData) throw { name: "ClassNotFound", id: classId };
const tasks = await Task.findAll({
where: {
classId,
},
});
let temp = [];
for (const key in tasks) {
temp.push(tasks[key]["id"]);
}
const score = await Score.findAll({
where: {
studentId,
taskId: temp,
},
});
const result = { tasks, score };
res.status(200).json(result);
} catch (err) {
next(err);
}
}
static async getById(req, res, next) {
const id = req.params.id;
try {
const task = await Task.findByPk(id);
if (!task) {
throw { name: "TaskNotFound", id };
}
if (task.soundUrl) {
task.question = JSON.parse(task.question);
}
res.status(200).json(task);
} catch (err) {
console.log("xderror", err);
next(err);
}
}
static async delete(req, res, next) {
const id = req.params.id;
try {
// const task = await Task.findByPk(id);
await Task.destroy({ where: { id } });
res.status(200).json({ message: `Deleted task with ID ${id}` });
} catch (err) {
next(err);
}
}
static async update(req, res, next) {
try {
const id = req.params.id;
const { name, description, question, soundUrl, classId } = req.body;
const input = { name, description, question, soundUrl, classId };
const result = await Task.update(input, {
where: { id },
returning: true,
});
res.status(200).json({ result: result[1][0], message: `Task with ID ${id} Updated` });
} catch (err) {
next(err);
}
}
static async searchSong(req, res, next) {
try {
const { artist, title } = req.query;
const songs = await searchSongs(artist, title);
res.status(200).json(songs);
} catch (err) {
next(err);
}
}
static async getSongDetails(req, res, next) {
try {
const { songId } = req.params;
const checkCache = await redis.get(songId);
// console.log(checkCache, "<<<");
if (checkCache) {
const cachedSong = JSON.parse(checkCache);
if (cachedSong.id == songId) {
res.status(200).json(cachedSong);
return;
}
}
const songDetail = await getSongDetailById(songId);
redis.set(songId, JSON.stringify(songDetail));
res.status(200).json(songDetail);
} catch (err) {
next(err);
}
}
static async getQuestion(req, res, next) {
try {
const { id, song, index, classId } = req.body;
// console.log(req.body, "<<< BODY");
const checkCache = await redis.get(id);
if (checkCache) {
// console.log("GOT CACHE");
const cachedSong = JSON.parse(checkCache);
if (cachedSong.id == id) {
const question = convertLyricsToQuestion(cachedSong, index);
const payload = {
name: song.title,
description: "listening",
classId,
soundUrl: song.media[0].url,
question: JSON.stringify({ index, id, song, question }),
};
const result = await Task.create(payload);
res.status(200).json({ result });
}
} else {
// console.log("NOT GOT CACHE");
const question = convertLyricsToQuestion(song, index);
const payload = {
name: song.title,
description: "listening",
classId,
soundUrl: song.media[0].url,
question: JSON.stringify({ index, id, song, question }),
};
const result = await Task.create(payload);
res.status(200).json({ result });
}
} catch (err) {
next(err);
}
}
static async getListeningScore(req, res, next) {
// Still uses Redis to transport the 'song' atm
try {
const { answer, index, id, song } = req.body;
const checkCache = await redis.get(id);
if (checkCache) {
const cachedSong = JSON.parse(checkCache);
if (cachedSong.id == id) {
const { splitLyrics } = cachedSong; //JSON.parse(cachedSong);
const score = getListeningScore(splitLyrics, answer, index);
res.status(200).json({ score });
}
} else {
const { splitLyrics } = song;
const score = getListeningScore(splitLyrics, answer, index);
res.status(200).json({ score });
}
} catch (err) {
next(err);
}
}
}
module.exports = TaskController;
|
<?php
declare(strict_types=1);
/**
* @copyright: 2019 Matt Kynaston
* @license : MIT
*/
namespace Kynx\Saiku\Client\Resource;
use GuzzleHttp\Exception\GuzzleException;
use Kynx\Saiku\Client\Entity\Datasource;
use Kynx\Saiku\Client\Exception\BadResponseException;
use Kynx\Saiku\Client\Exception\EntityException;
use Kynx\Saiku\Client\Exception\SaikuException;
use function array_map;
final class DatasourceResource extends AbstractResource implements DatasourceResourceInterface
{
public const PATH = 'rest/saiku/admin/datasources/';
/**
* {@inheritdoc}
*/
public function getAll() : array
{
try {
$response = $this->session->request('GET', self::PATH);
} catch (GuzzleException $e) {
throw new SaikuException($e->getMessage(), $e->getCode(), $e);
}
if ($response->getStatusCode() === 200) {
return array_map(function (array $item) {
return new Datasource($item);
}, $this->decodeResponse($response));
}
throw new BadResponseException("Couldn't get datasources", $response);
}
/**
* {@inheritdoc}
*/
public function create(Datasource $datasource) : Datasource
{
$this->validate($datasource);
$options = [
'json' => $datasource->toArray(),
];
try {
$response = $this->session->request('POST', self::PATH, $options);
} catch (GuzzleException $e) {
throw new SaikuException($e->getMessage(), $e->getCode(), $e);
}
if ($response->getStatusCode() === 200) {
return new Datasource((string) $response->getBody());
}
throw new BadResponseException("Couldn't create / update datasource", $response);
}
/**
* {@inheritdoc}
*/
public function update(Datasource $datasource) : Datasource
{
$this->validate($datasource);
if (! $datasource->getId()) {
throw new EntityException('Datasource must have an id');
}
$options = [
'json' => $datasource->toArray(),
];
try {
$response = $this->session->request('PUT', self::PATH . $datasource->getId(), $options);
} catch (GuzzleException $e) {
throw new SaikuException($e->getMessage(), $e->getCode(), $e);
}
if ($response->getStatusCode() === 200) {
return new Datasource((string) $response->getBody());
}
throw new BadResponseException("Couldn't create / update datasource", $response);
}
/**
* {@inheritdoc}
*/
public function delete(Datasource $datasource) : void
{
if (! $datasource->getId()) {
throw new EntityException('Datasource must have an id');
}
try {
$this->session->request('DELETE', self::PATH . $datasource->getId());
} catch (GuzzleException $e) {
throw new SaikuException($e->getMessage(), $e->getCode(), $e);
}
}
private function validate(Datasource $datasource)
{
if (! ($datasource->getAdvanced() || $datasource->getConnectionType())) {
throw new EntityException('Datasource must contain a connection type or be advanced');
}
}
}
|
using System;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using CarDealership.HealthChecks.Tags;
using HealthChecks.UI.Client;
using HealthchecksDemo.HealthChecks.Responses;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace HealthchecksDemo.HealthChecks.Middlewares
{
public static class CustomMiddlewareExtensions
{
public static IApplicationBuilder UseServiceHealthChecks(this IApplicationBuilder builder)
{
builder.UseHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = (check) => check.Tags.Contains(nameof(HealthChecksTags.Ready)),
ResponseWriter = _responseWriter
});
builder.UseHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter = _responseWriter
});
builder.UseHealthChecks("/health-ui", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
return builder;
}
#region Response writer Func
private static readonly Func<HttpContext, HealthReport, Task> _responseWriter = async (context, report) =>
{
context.Response.ContentType = "application/json";
var response = new HealthCheckReponse
{
Status = report.Status.ToString(),
HealthCheckDuration = report.TotalDuration,
HealthChecks = report.Entries.Select(x => new IndividualHealthCheckResponse
{
Component = x.Key,
Status = x.Value.Status.ToString(),
Description = x.Value.Description,
Exception = x.Value.Exception
})
};
await context.Response.WriteAsync(JsonSerializer.Serialize(response)).ConfigureAwait(false);
};
#endregion Response writer Func
}
} |
using System.Collections.Generic;
using Entitas;
public sealed class RemoveViewSystem:ISetPool,IReactiveSystem,IEnsureComponents
{
public TriggerOnEvent trigger { get { return CoreMatcher.Asset.OnEntityRemoved(); } }
public IMatcher ensureComponents { get {return CoreMatcher.View; } }
Pool pool;
public void SetPool(Pool pool)
{
pool.GetGroup(CoreMatcher.View).OnEntityRemoved += (group, entity, index, component) =>
{
var viewComponent = component as ViewComponent;
UnityEngine.Object.Destroy(viewComponent.gameObject);
};
}
public void Execute(List<Entity> entities)
{
foreach (var e in entities)
{
e.RemoveView();
}
}
}
|
package payload.response.common
import enums.*
import kotlinx.serialization.Serializable
@Serializable
data class Achievement private constructor(
val name: String,
val icon: ResourceLocation,
val description: String,
val exposed: Boolean,
val type: AchievementType
) |
import express from 'express';
import ReposController from '../../../../controllers/reposController';
import { RouterWrapper } from '../../../../utils/routes/router';
import { Config } from '../../../../config';
import createOctokit from '../../../../utils/createOctokit';
export default class ReposRouter implements RouterWrapper {
private controller: ReposController;
constructor (config: Config) {
this.controller = new ReposController(config, createOctokit(config));
}
init (): express.Router {
return express.Router()
.get('/slugs', this.controller.getSlugs.bind(this.controller));
}
}
|
import { CodeMod, ModResult, NoOp } from '../../../../codeMods/types';
import { Err } from '../../../../helpers/result';
const CodeMod: CodeMod<string> = {
run: () => {
return Err<ModResult, NoOp>({ logs: [] });
},
version: '1.0.0',
name: 'CodeMod',
};
export default CodeMod;
|
### 贪心
- 本质为每次操作都达到局部最优,当问题有唯一最优解的时候,最终达到全局最优。
*值得说明的是,"贪心"并不是"贪得无厌",它只是指每次操作所能达到的最优极限*
> 例如:需要挪动200kg的重物,但是工具每次只能挪动100kg,最简单的方式就是直接把200kg直接挪过去,但受限于工具的极限,只能100kg 100kg挪动,所以,这个每次把100kg打满的动作,就是贪心
一般来说,当题目问题中存在最多最少等字眼,考虑是否可以采用贪心或者动态规划求解。
较为常见的三类问题
1. 典型的贪心问题
较简单,没啥技巧,做就完事了
- [AssignCookies](./AssignCookies.py)
- [CanPlaceFlowers](./CanPlaceFlowers.py)
- [BestTimeToBuyAndSellStock2](./BestTimeToBuyAndSellStock2.py)
- [NonDecreasingArray](./NonDecreasingArray.py)
2. 多维度优化问题
这类问题一般有两个或更多的因素需要考虑,我们可以考虑对多个维度one by one地去解决
>(ps:我甚至觉得每次只解决一个维度也算贪心,也符合 局部最优->全局最优)
*在解决过程中可能需要多次使用贪心,或者贪心配合其他不同思路去解决不同维度的问题*
- [Candy](./Candy.py)
- [QueueReconstructionByHeight](./QueueReconstructionByHeight.py)
3. 区间问题
一般包括 区间合并 / 区间去重 / 区间调度等 均可以贪心算法去实现
* 该类问题一般不会直接直白地告诉是区间问题,需要先将其抽象为区间。套路一般为先排序后贪心
- [NonOverlappingIntervals](./NonOverlappingIntervals.py)
- [MinimumNumberOfArrowsToBurstBalloons](./MinimumNumberOfArrowsToBurstBalloons.py)
- [PartitionLabels](./PartitionLabels.py) |
#!/bin/sh
VERSION="0.0.2" # Time-stamp: <2021-11-21T18:03:50Z>
DATE=`date +%Y%m%d`
set `seq -w 1 99`
set -x
set -e
python plot_logs.py normal fana -p AccDeath -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal fana -p AccAbortion -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal fana -p AccTemple -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal fana fanampr fanamprmprs -p Education -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal fana fanampr fanamprmprs -p AccDeath -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal fana fanampr fanamprmprs -p Population -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal fana fanampr fanamprmprs -p AccAbortion -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal fana fanampr fanamprmprs -p Power -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarmpopmamb mwarmpop -p AccDeath -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarmpopmamb mwarmpop -p AccDeathRate -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarmpopmamb mwarmpop -p AccAbortion -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarmpopmamb mwarmpop -p AccBreakup -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarmpopmamb mwarmpop -p Welfare -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarmpopmamb mwarmpop -p Budget -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarmpopmamb mwarmpop -p Power -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarmpopmamb mwarmpop -p Injured -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarfpr -p AccDeath -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarfpr -p AccAbortion -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarfpr -p Education -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal mwar mwarfpr -p Power -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal ledu ltom ledultom -p AccKarma -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal ledu ltom ledultom -p NewKarma -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal ledu ltom ledultom -p Education -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal lpe -p AccDeath -o fig-${DATE}_$1.png
shift 1
python plot_logs.py lpe ltomlpe ledultomlpe -p AccDeath -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal ledu ltomlpe ledultomlpe -p AccKarma -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal lsth ltom ltomlsth -p Population -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal lsth ltom ltomlsth -p AccDeath -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal lsth ltom ltomlsth -p AccKarma -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal lsth ltom ltomlsth -p NewKarma2 -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal lsth ltom ltomlsth -p Hating -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal lsth ltom ltomlsth -p VirtualHating -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal lsth ltom ltomlsth -p AccVKarma -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal worst1 worst2 -p AccDeath -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal worst1 worst2 -p AccAbortion -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal worst1 worst2 -p AccKarma -o fig-${DATE}_$1.png
shift 1
python plot_logs.py normal worst1 worst2 -p Education -o fig-${DATE}_$1.png
shift 1
|
package com.couchbase.demo.config;
import com.couchbase.client.java.Cluster;
import com.couchbase.demo.tasks.Task;
import com.couchbase.demo.tasks.TaskRepository;
import com.couchbase.demo.testha.SimulatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SimulatorConfig {
@Bean
@Autowired
public SimulatorService<Task> simulatorService(TaskRepository repository) {
return new SimulatorService<Task>(repository);
}
}
|
import arrow
import pdb
import json
from copy import deepcopy
import os
from scrabble import Scrabble
from data_model import *
from common import *
import random
args =argparser.parse_args()
t0 = arrow.get()
#target_building = 'ap_m'
#source_buildings = ['ap_m']
#source_buildings = ['ebu3b', 'ap_m']
#source_sample_num_list = [200, 10]
#source_sample_num_list = [200, 10]
res_obj = get_result_obj(args)
source_buildings = args.source_building_list
target_building = args.target_building
source_sample_num_list = args.sample_num_list
building_sentence_dict, target_srcids, building_label_dict,\
building_tagsets_dict, known_tags_dict = load_data(target_building,
source_buildings)
tot_label_dict = {}
for building, tagsets_dict in building_tagsets_dict.items():
tot_label_dict.update(tagsets_dict )
t1 = arrow.get()
print(t1-t0)
config = {
'use_known_tags': args.use_known_tags,
'n_jobs': args.n_jobs,
'tagset_classifier_type': args.tagset_classifier_type,
'use_brick_flag': args.use_brick_flag,
}
learning_srcid_file = 'metadata/test'
for building, source_sample_num in zip(source_buildings,
source_sample_num_list):
learning_srcid_file += '_{0}_{1}'.format(building, source_sample_num)
learning_srcid_file += '_srcids.json'
if os.path.isfile(learning_srcid_file):
with open(learning_srcid_file, 'r') as fp:
predefined_learning_srcids = json.load(fp)
else:
predefined_learning_srcids = []
for building, source_sample_num in zip(source_buildings,
source_sample_num_list):
predefined_learning_srcids += select_random_samples(building,
building_tagsets_dict[building].keys(),
source_sample_num,
True)
with open(learning_srcid_file, 'w') as fp:
json.dump(predefined_learning_srcids, fp)
scrabble = Scrabble(target_building,
target_srcids,
building_label_dict,
building_sentence_dict,
building_tagsets_dict,
source_buildings,
source_sample_num_list,
known_tags_dict,
config=config,
learning_srcids=predefined_learning_srcids
)
scrabble.update_model([])
history = []
for i in range(0, 20):
t2 = arrow.get()
new_srcids = scrabble.select_informative_samples(10)
scrabble.update_model(new_srcids)
pred = scrabble.predict(target_srcids + scrabble.learning_srcids)
pred_tags = scrabble.predict_tags(target_srcids)
tot_acc, tot_point_acc, learning_acc, learning_point_acc = \
calc_acc(tot_label_dict, pred, target_srcids, scrabble.learning_srcids)
print_status(scrabble, tot_acc, tot_point_acc,
learning_acc, learning_point_acc)
hist = {
'pred': pred,
'pred_tags': pred_tags,
'learning_srcids': len(list(set(scrabble.learning_srcids)))
}
t3 = arrow.get()
res_obj.history.append(hist)
res_obj.save()
print('{0}th took {1}'.format(i, t3 - t2))
|
require 'test_helper'
require 'benchmark'
class PrinterTest < Minitest::Test
def test_typing_outputs_as_is
text = "sending data..."
interval = 0.1
assert_output(stdout = text) { Tryhttp::Printer.typing(text, interval) }
end
def test_typing_outputs_with_given_interval
text = "sending data..."
interval = 0.1
result = Benchmark.realtime do
assert_output(stdout = text) { Tryhttp::Printer.typing(text, interval) }
end
assert result > text.size * interval / 1000
end
def test_carriage_return
skip("unable to test carriage return nicely")
expected = "expected text"
assert_output(stdout = expected) do
print "this is a text"
Tryhttp::Printer.cr()
print expected
end
end
end
|
package zella.lanternascreens.controller;
import zella.lanternascreens.view.View;
public abstract class BaseController<T extends View> {
protected T view;
public void setView(T view){
this.view = view;
}
}
|
#include "DXShader.h"
#include "BF/IO/FileLoader.h"
#include "BF/Engine.h"
#include "DXError.h"
namespace BF
{
namespace Platform
{
namespace API
{
namespace DirectX
{
using namespace std;
using namespace BF::IO;
DXShader::DXShader() :
VS(nullptr), PS(nullptr), VSData(nullptr), PSData(nullptr), VSsize(0), PSsize(0)
{
}
DXShader::~DXShader()
{
}
void DXShader::Load(const string& vertexShaderFilePath, const string& pixelShaderFilePath)
{
VSData = FileLoader::LoadBinaryFile(vertexShaderFilePath, &VSsize);
PSData = FileLoader::LoadBinaryFile(pixelShaderFilePath, &PSsize);
DXCall(Engine::GetContext().GetDXContext().GetDevice()->CreateVertexShader(VSData, VSsize, 0, &VS));
DXCall(Engine::GetContext().GetDXContext().GetDevice()->CreatePixelShader(PSData, PSsize, 0, &PS));
}
void DXShader::Bind() const
{
Engine::GetContext().GetDXContext().GetContext()->VSSetShader(VS, 0, 0);
Engine::GetContext().GetDXContext().GetContext()->PSSetShader(PS, 0, 0);
}
void DXShader::CleanUp() const
{
VS->Release();
PS->Release();
}
}
}
}
} |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Ticket extends Model
{
use HasFactory;
protected $table = 'ticket';
protected $fillable = [
'user_name',
'from',
'to',
'number_phone',
'departure_date',
'return_date',
'category',
'amount_adults',
'amount_children_less_12',
'amount_children_less_2'
];
}
|
import Test.HUnit (Test(TestCase))
import Input (echo)
import HUnitJudge (isEqual, runJSON)
echo' = echo :: [Int] -> [Int]
empty = []
main = runJSON
[ TestCase (isEqual "echo [1,2,3]" [1,2,3] (echo' [1,2,3]))
, TestCase (isEqual "echo []" empty (echo' empty))
, TestCase (isEqual "echo [1]" [1] (echo' [1]))
, TestCase (isEqual "echo [1,1]" [1,1] (echo' [1,1]))
]
|
namespace CommandApi.Internal.Requests
{
using System;
using Newtonsoft.Json;
/// <summary>
/// Represents the data sent in response to receiving a valid command.
/// </summary>
internal class CommandResponse
{
/// <summary>
/// Initializes a new instance of the <see cref="CommandResponse"/> class.
/// </summary>
/// <param name="command">The name of the command.</param>
/// <param name="correlationId">The associated correlation identifier.</param>
/// <param name="executed">Whether or not the command was executed.</param>
public CommandResponse(
string command,
string correlationId,
bool executed)
{
if (string.IsNullOrWhiteSpace(command))
{
throw new ArgumentNullException(nameof(command));
}
if (string.IsNullOrWhiteSpace(correlationId))
{
throw new ArgumentNullException(nameof(correlationId));
}
this.Command = command;
this.CorrelationId = correlationId;
this.Executed = executed;
}
/// <summary>
/// Gets the name of the command that was received.
/// </summary>
[JsonProperty("command")]
public string Command { get; }
/// <summary>
/// Gets the associated correlation identifier.
/// </summary>
[JsonProperty("correlationId")]
public string CorrelationId { get; }
/// <summary>
/// Gets a value indicating whether or not the command was executed or
/// just validated.
/// </summary>
[JsonProperty("executed")]
public bool Executed { get; }
}
}
|
class CreateSpreeNavisionItems < ActiveRecord::Migration[5.1]
def change
create_table :spree_navision_items do |t|
t.string :key
t.string :rec_id
t.string :no
t.string :description
t.string :description_2
t.string :long_text
t.string :base_unit_of_measure
t.string :item_category_code
t.string :product_group_code
t.string :group_of_goods_code
t.string :vat_bus_posting_gr_price
t.string :vat_prod_posting_group
t.boolean :blocked
t.string :eol
t.string :manufacturer_item_no_1
t.string :manufacturer_item_no_2
t.string :manufacturer_code
t.decimal :net_weight
t.decimal :gross_weight
t.boolean :webshop_release
t.timestamps
end
add_index :spree_navision_items, :key, unique: true
end
end
|
class HomeController < ApplicationController
DOGS = ['1-normal', '10-newspaper', '47-celebrate', '48-box', '52-basketball', '56-rocket']
WORDS = [
'Hi!<br/>Sure it\'s nice to see you!',
'Yay!<br/>I knew you\'d come!',
'I was expecting you!',
'Yay!<br/>You made it!',
'Let\'s play!'
]
def index
drnd = rand(DOGS.length)
wrnd = rand(WORDS.length)
@dog = "#{DOGS[drnd]}.png"
@word = WORDS[wrnd]
end
end |
package Structural_Patterns.Decorator;
public class MainDecorator {
public static void main(String[] args) {
IReal real = new Real();
IReal decoCheck = new DecoratorCheckSyntax(real);
IReal decoLog = new DecoratorLogging(decoCheck);
for (String query : new String[]{"15", "-15", "foo15", "", null}) {
System.out.printf("Evaluation of \"%s\" is %d.\n", query, decoLog.compute(query));
}
}
}
|
package com.rac021.jaxy.api.crypto ;
import java.util.Arrays ;
import java.util.Base64 ;
import java.util.Objects ;
import javax.crypto.Cipher ;
import java.util.logging.Level ;
import java.util.logging.Logger ;
import java.security.SecureRandom ;
import javax.crypto.spec.SecretKeySpec ;
import javax.crypto.BadPaddingException ;
import javax.crypto.spec.IvParameterSpec ;
import java.security.NoSuchAlgorithmException ;
import javax.crypto.IllegalBlockSizeException ;
import static com.rac021.jaxy.api.logger.LoggerFactory.getLogger ;
/**
*
* @author ryahiaoui
*/
public abstract class EncDecRyptor implements ICryptor {
protected Cipher cipher ;
protected IvParameterSpec ivSpec ;
protected byte[] ivBytes ;
protected SecretKeySpec secretKeySpec ;
protected _Operation OPERATION ;
protected byte[] KEY ;
protected int SIZE_BYTE_KEY ;
protected _CIPHER_MODE CIPHER_TYPE ;
protected _CIPHER_SIZE CIPHER_SIZE ;
public enum _Operation { Encrypt, Decrypt }
public enum _CIPHER_MODE { CBC, ECB }
public enum _CIPHER_NAME { AES, DES }
public enum _CipherOperation { dofinal , update }
public enum _CIPHER_SIZE { _64, _96 , _128 , _192 , _256 }
private static final Logger LOGGER = getLogger() ;
protected static byte[] randomInitIV( int size ) {
byte[] ivBytes = new byte[size] ;
SecureRandom random = new SecureRandom() ;
random.nextBytes(ivBytes) ;
return ivBytes ;
}
public byte[] getKeyFromPasswordUsingSha256( String password ) throws Exception {
Objects.requireNonNull(password) ;
return toSHA256 ( password , SIZE_BYTE_KEY ) ;
}
protected byte[] decrypt( String encryptedMessage ,
_CipherOperation cipherOperation ) throws Exception {
try {
int indexOfPoint = encryptedMessage.indexOf(".") ;
byte[] l_ivBytes = null ;
byte[] encry = null ;
if( indexOfPoint != -1 ) {
l_ivBytes = Base64.getDecoder().decode( encryptedMessage.substring(0, indexOfPoint) ) ;
encry = Base64.getDecoder().decode( encryptedMessage.substring(indexOfPoint + 1 ) ) ;
this.ivSpec = new IvParameterSpec(l_ivBytes) ;
}
else {
encry = Base64.getDecoder().decode( encryptedMessage ) ;
}
setOperationMode( OPERATION ) ;
return cipherOperation == _CipherOperation.dofinal ?
cipher.doFinal( encry ) :
cipher.update ( encry ) ;
} catch ( BadPaddingException | IllegalBlockSizeException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex) ;
return null ;
}
}
public static byte[]toSHA256( String password, int size ) throws NoSuchAlgorithmException {
return Arrays.copyOfRange( Digestor.toSHA256(password), 0 , size ) ;
}
public static byte[]toSHA1( String password, int size ) throws NoSuchAlgorithmException {
return Arrays.copyOfRange( Digestor.toSHA1(password), 0 , size ) ;
}
public static byte[]toMD5( String password, int size ) throws NoSuchAlgorithmException {
return Arrays.copyOfRange( Digestor.toMD5(password), 0 , size ) ;
}
@Override
public abstract void setOperationMode( _Operation op ) ;
}
|
#!/bin/bash
green='\033[1;32m'
end='\033[1;m'
info='\033[1;33m[!]\033[1;m'
que='\033[1;34m[?]\033[1;m'
bad='\033[1;31m[-]\033[1;m'
good='\033[1;32m[+]\033[1;m'
run='\033[1;97m[~]\033[1;m'
printf """$green ___ _
/ _ \(_)__ ____ ___ __
/ // / / _ \`/ _ \`/ // /
/____/_/\_, /\_, /\_, /
/___//___//___/
$end"""
if [ -z "$1" ]; then
printf "Usage: ./apk.sh <path to apk file>\n"
return 1
fi
apk=$1
dir=$( pwd )
name=$(echo "$apk" | sed -E "s|[^a-zA-Z0-9]+|-|")
decom="$dir/$name"
links="$dir/$name.txt"
touch $links
if type "apktool" > /dev/null; then
:
else
printf "$bad Diggy requires 'apktool' to be installed."
return 1
fi
extract() {
k=$(apktool d $apk -o $decom -fq)
}
regxy() {
matches=$(grep -EroI "[\"'\`](https?://|/)[\w\.-/]+[\"'\`]")
for final in $matches; do
final=${final//$"\""/}
final=${final//$"'"/}
if [ $(echo "$final" | grep "http://schemas.android.com") ]
then
:
else
echo "$final" >> "$links"
fi
done
awk '!x[$1]++' $links
}
printf $"$run Decompiling the apk\n"
extract
printf $"$run Extracting endpoints\n"
regxy
printf $"$info Endpoints saved in: $links\n" |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.slice;
import static android.app.slice.SliceItem.FORMAT_ACTION;
import static android.app.slice.SliceItem.FORMAT_IMAGE;
import static android.app.slice.SliceItem.FORMAT_INT;
import static android.app.slice.SliceItem.FORMAT_LONG;
import static android.app.slice.SliceItem.FORMAT_REMOTE_INPUT;
import static android.app.slice.SliceItem.FORMAT_SLICE;
import static android.app.slice.SliceItem.FORMAT_TEXT;
import static androidx.slice.Slice.addHints;
import android.app.PendingIntent;
import android.app.RemoteInput;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import androidx.annotation.StringDef;
import androidx.core.graphics.drawable.IconCompat;
import androidx.core.util.Consumer;
import androidx.core.util.Pair;
import java.util.Arrays;
import java.util.List;
/**
* A SliceItem is a single unit in the tree structure of a {@link Slice}.
* <p>
* A SliceItem a piece of content and some hints about what that content
* means or how it should be displayed. The types of content can be:
* <li>{@link android.app.slice.SliceItem#FORMAT_SLICE}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_TEXT}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_IMAGE}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_ACTION}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_INT}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_LONG}</li>
* <p>
* The hints that a {@link SliceItem} are a set of strings which annotate
* the content. The hints that are guaranteed to be understood by the system
* are defined on {@link Slice}.
*/
public class SliceItem {
private static final String HINTS = "hints";
private static final String FORMAT = "format";
private static final String SUBTYPE = "subtype";
private static final String OBJ = "obj";
private static final String OBJ_2 = "obj_2";
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
@StringDef({FORMAT_SLICE, FORMAT_TEXT, FORMAT_IMAGE, FORMAT_ACTION, FORMAT_INT,
FORMAT_LONG, FORMAT_REMOTE_INPUT, FORMAT_LONG})
public @interface SliceType {
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
protected @Slice.SliceHint String[] mHints;
private final String mFormat;
private final String mSubType;
private final Object mObj;
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public SliceItem(Object obj, @SliceType String format, String subType,
@Slice.SliceHint String[] hints) {
mHints = hints;
mFormat = format;
mSubType = subType;
mObj = obj;
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public SliceItem(Object obj, @SliceType String format, String subType,
@Slice.SliceHint List<String> hints) {
this (obj, format, subType, hints.toArray(new String[hints.size()]));
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public SliceItem(PendingIntent intent, Slice slice, String format, String subType,
@Slice.SliceHint String[] hints) {
this(new Pair<Object, Slice>(intent, slice), format, subType, hints);
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public SliceItem(Consumer<Uri> action, Slice slice, String format, String subType,
@Slice.SliceHint String[] hints) {
this(new Pair<Object, Slice>(action, slice), format, subType, hints);
}
/**
* Gets all hints associated with this SliceItem.
*
* @return Array of hints.
*/
public @NonNull @Slice.SliceHint List<String> getHints() {
return Arrays.asList(mHints);
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public void addHint(@Slice.SliceHint String hint) {
mHints = ArrayUtils.appendElement(String.class, mHints, hint);
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public void removeHint(String hint) {
ArrayUtils.removeElement(String.class, mHints, hint);
}
/**
* Get the format of this SliceItem.
* <p>
* The format will be one of the following types supported by the platform:
* <li>{@link android.app.slice.SliceItem#FORMAT_SLICE}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_TEXT}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_IMAGE}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_ACTION}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_INT}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_LONG}</li>
* <li>{@link android.app.slice.SliceItem#FORMAT_REMOTE_INPUT}</li>
* @see #getSubType() ()
*/
public @SliceType String getFormat() {
return mFormat;
}
/**
* Get the sub-type of this SliceItem.
* <p>
* Subtypes provide additional information about the type of this information beyond basic
* interpretations inferred by {@link #getFormat()}. For example a slice may contain
* many {@link android.app.slice.SliceItem#FORMAT_TEXT} items, but only some of them may be
* {@link android.app.slice.Slice#SUBTYPE_MESSAGE}.
* @see #getFormat()
*/
public String getSubType() {
return mSubType;
}
/**
* @return The text held by this {@link android.app.slice.SliceItem#FORMAT_TEXT} SliceItem
*/
public CharSequence getText() {
return (CharSequence) mObj;
}
/**
* @return The icon held by this {@link android.app.slice.SliceItem#FORMAT_IMAGE} SliceItem
*/
public IconCompat getIcon() {
return (IconCompat) mObj;
}
/**
* @return The pending intent held by this {@link android.app.slice.SliceItem#FORMAT_ACTION}
* SliceItem
*/
public PendingIntent getAction() {
return (PendingIntent) ((Pair<Object, Slice>) mObj).first;
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY_GROUP)
public void fireAction(Context context, Intent i) throws PendingIntent.CanceledException {
Object action = ((Pair<Object, Slice>) mObj).first;
if (action instanceof PendingIntent) {
((PendingIntent) action).send(context, 0, i, null, null);
} else {
((Consumer<Uri>) action).accept(getSlice().getUri());
}
}
/**
* @return The remote input held by this {@link android.app.slice.SliceItem#FORMAT_REMOTE_INPUT}
* SliceItem
* @hide
*/
@RequiresApi(20)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public RemoteInput getRemoteInput() {
return (RemoteInput) mObj;
}
/**
* @return The color held by this {@link android.app.slice.SliceItem#FORMAT_INT} SliceItem
*/
public int getInt() {
return (Integer) mObj;
}
/**
* @return The slice held by this {@link android.app.slice.SliceItem#FORMAT_ACTION} or
* {@link android.app.slice.SliceItem#FORMAT_SLICE} SliceItem
*/
public Slice getSlice() {
if (FORMAT_ACTION.equals(getFormat())) {
return ((Pair<Object, Slice>) mObj).second;
}
return (Slice) mObj;
}
/**
* @return The long held by this {@link android.app.slice.SliceItem#FORMAT_LONG}
* SliceItem
*/
public long getLong() {
return (Long) mObj;
}
/**
* @deprecated TO BE REMOVED
*/
@Deprecated
public long getTimestamp() {
return (Long) mObj;
}
/**
* @param hint The hint to check for
* @return true if this item contains the given hint
*/
public boolean hasHint(@Slice.SliceHint String hint) {
return ArrayUtils.contains(mHints, hint);
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public SliceItem(Bundle in) {
mHints = in.getStringArray(HINTS);
mFormat = in.getString(FORMAT);
mSubType = in.getString(SUBTYPE);
mObj = readObj(mFormat, in);
}
/**
* @hide
* @return
*/
@RestrictTo(Scope.LIBRARY)
public Bundle toBundle() {
Bundle b = new Bundle();
b.putStringArray(HINTS, mHints);
b.putString(FORMAT, mFormat);
b.putString(SUBTYPE, mSubType);
writeObj(b, mObj, mFormat);
return b;
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public boolean hasHints(@Slice.SliceHint String[] hints) {
if (hints == null) return true;
for (String hint : hints) {
if (!TextUtils.isEmpty(hint) && !ArrayUtils.contains(mHints, hint)) {
return false;
}
}
return true;
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public boolean hasAnyHints(@Slice.SliceHint String... hints) {
if (hints == null) return false;
for (String hint : hints) {
if (ArrayUtils.contains(mHints, hint)) {
return true;
}
}
return false;
}
private void writeObj(Bundle dest, Object obj, String type) {
switch (type) {
case FORMAT_IMAGE:
dest.putBundle(OBJ, ((IconCompat) obj).toBundle());
break;
case FORMAT_REMOTE_INPUT:
dest.putParcelable(OBJ, (Parcelable) obj);
break;
case FORMAT_SLICE:
dest.putParcelable(OBJ, ((Slice) obj).toBundle());
break;
case FORMAT_ACTION:
dest.putParcelable(OBJ, (PendingIntent) ((Pair<Object, Slice>) obj).first);
dest.putBundle(OBJ_2, ((Pair<Object, Slice>) obj).second.toBundle());
break;
case FORMAT_TEXT:
dest.putCharSequence(OBJ, (CharSequence) obj);
break;
case FORMAT_INT:
dest.putInt(OBJ, (Integer) mObj);
break;
case FORMAT_LONG:
dest.putLong(OBJ, (Long) mObj);
break;
}
}
private static Object readObj(String type, Bundle in) {
switch (type) {
case FORMAT_IMAGE:
return IconCompat.createFromBundle(in.getBundle(OBJ));
case FORMAT_REMOTE_INPUT:
return in.getParcelable(OBJ);
case FORMAT_SLICE:
return new Slice(in.getBundle(OBJ));
case FORMAT_TEXT:
return in.getCharSequence(OBJ);
case FORMAT_ACTION:
return new Pair<>(
in.getParcelable(OBJ),
new Slice(in.getBundle(OBJ_2)));
case FORMAT_INT:
return in.getInt(OBJ);
case FORMAT_LONG:
return in.getLong(OBJ);
}
throw new RuntimeException("Unsupported type " + type);
}
/**
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public static String typeToString(String format) {
switch (format) {
case FORMAT_SLICE:
return "Slice";
case FORMAT_TEXT:
return "Text";
case FORMAT_IMAGE:
return "Image";
case FORMAT_ACTION:
return "Action";
case FORMAT_INT:
return "Int";
case FORMAT_LONG:
return "Long";
case FORMAT_REMOTE_INPUT:
return "RemoteInput";
}
return "Unrecognized format: " + format;
}
/**
* @return A string representation of this slice item.
*/
@Override
public String toString() {
return toString("");
}
/**
* @return A string representation of this slice item.
* @hide
*/
@RestrictTo(Scope.LIBRARY)
public String toString(String indent) {
StringBuilder sb = new StringBuilder();
switch (getFormat()) {
case FORMAT_SLICE:
sb.append(getSlice().toString(indent));
break;
case FORMAT_ACTION:
sb.append(indent).append(getAction()).append(",\n");
sb.append(getSlice().toString(indent));
break;
case FORMAT_TEXT:
sb.append(indent).append('"').append(getText()).append('"');
break;
case FORMAT_IMAGE:
sb.append(indent).append(getIcon());
break;
case FORMAT_INT:
sb.append(indent).append(getInt());
break;
case FORMAT_LONG:
sb.append(indent).append(getLong());
break;
default:
sb.append(indent).append(SliceItem.typeToString(getFormat()));
break;
}
if (!FORMAT_SLICE.equals(getFormat())) {
sb.append(' ');
addHints(sb, mHints);
}
sb.append(",\n");
return sb.toString();
}
}
|
/* -*- Mode: Prolog -*- */
:- module(owlapi_swrl_hooks,
[
]).
:- use_module(library(jpl)).
:- use_module(swrl).
:- use_module(owl2_model).
:- use_module(owl2_metamodel).
prefix('org.semanticweb.owl.model').
:- multifile owl2_java_owlapi:owlterm_java/4.
owl2_java_owlapi:owlterm_java(Fac,rule,Pl,Obj) :-
swrl_java(Fac,Pl,Obj).
swrl_java(Fac,i(V),Ob) :-
!,
owl2_java_owlapi:atom_javaURI(V,VU),
jpl_call(Fac,getSWRLAtomIVariable,[VU],Ob). % TODO: dvariable
swrl_java(Fac,implies(A,C),Ob) :-
!,
maplist(swrl_java(Fac),A,JAL),
list_jset(JAL,SJA),
maplist(swrl_java(Fac),C,JCL),
list_jset(JCL,SJC),
jpl_call(Fac,getSWRLRule,[SJA,SJC],Ob).
swrl_java(Fac,description(CE,I),Ob) :-
!,
swrl_java(Fac,CE,JCE),
swrl_java(Fac,I,JI),
jpl_call(Fac,getSWRLClassAtom,[JCE,JI],Ob).
swrl_java(Fac,sameAs(X,Y),Ob) :-
!,
swrl_java(Fac,X,JX),
swrl_java(Fac,Y,JY),
jpl_call(Fac,getSWRLSameAsAtom,[JX,JY],Ob).
swrl_java(Fac,differentFrom(X,Y),Ob) :-
!,
swrl_java(Fac,X,JX),
swrl_java(Fac,Y,JY),
jpl_call(Fac,getSWRLdifferentFromAtom,[JX,JY],Ob).
swrl_java(Fac,A,Ob) :-
A=..[F,X], % e.g. artist(v(x))
!,
swrl_java(Fac,description(F,X),Ob).
swrl_java(Fac,A,Ob) :-
A=..[P,X,Y], % TODO: datavalue
!,
owl2_java_owlapi:owlterm_java(Fac,_,objectProperty(P),JP),
swrl_java(Fac,X,JX),
swrl_java(Fac,Y,JY),
jpl_call(Fac,getSWRLObjectPropertyAtom,[JP,JX,JY],Ob).
swrl_java(_,A,Ob) :-
owl2_java_owlapi:atom_javaURI(A,Ob).
list_jset(L,JSet) :-
jpl_new('java.util.HashSet',[],JSet),
forall(member(Obj,L),
jpl_call(JSet,add,[Obj],_)).
/** <module> includes SWRL in translation to OWLAPI
---+ Synopsis
==
[owl2_from_rdf].
[swrl].
[swrl_rdf_hooks].
owl_parse_rdf('testfiles/dl-safe-ancestor.owl').
['owl2java/swrl_owlapi_hooks'].
[owl2_java_owlapi].
create_factory(Man,Fac),
build_ontology(Man,Fac,Ont),
save_ontology(Man,Ont,'file:///tmp/foo').
==
---+ Details
*/
|
GRANT ALL PRIVILEGES ON *.* TO root@'%' IDENTIFIED BY 'root';
FLUSH PRIVILEGES;
|
using Generators;
using System.Linq;
namespace Opal.Productions
{
public interface IReduceExpr
{
void Write<T>(T generator) where T:Generator<T>;
}
public class ReduceNullExpr: IReduceExpr
{
public void Write<T>(T generator) where T: Generator<T> =>
generator.Write("null");
}
public class ReduceValueExpr: IReduceExpr
{
private readonly string value;
public ReduceValueExpr(string value) =>
this.value = value;
public void Write<T>(T generator) where T: Generator<T> =>
generator.Write(value);
}
public class ReduceStringExpr: IReduceExpr
{
private readonly string value;
public ReduceStringExpr(string value) =>
this.value = value;
public void Write<T>(T generator) where T: Generator<T> =>
generator.WriteEsc(value);
}
public class ReduceArgExpr: IReduceExpr
{
private readonly int arg;
public ReduceArgExpr(int arg) =>
this.arg = arg;
public void Write<T>(T generator) where T: Generator<T> =>
generator.Write("At(")
.Write(arg)
.Write(")");
}
public class ReduceCastedExpr: IReduceExpr
{
public readonly string cast;
public readonly IReduceExpr expr;
public ReduceCastedExpr(string cast, IReduceExpr expr)
{
this.cast = cast;
this.expr = expr;
}
public void Write<T>(T generator)
where T:Generator<T>
{
generator.Write("(")
.Write(cast)
.Write(")");
expr.Write(generator);
}
}
public class ReduceCastedArgExpr: IReduceExpr
{
public readonly int arg;
public readonly string type;
public ReduceCastedArgExpr(int arg, string type)
{
this.arg = arg;
this.type = type;
}
public void Write<T>(T generator)
where T: Generator<T>
{
generator.Write("At<")
.Write(type)
.Write(">(")
.Write(arg)
.Write(")");
}
}
public class ReduceMethodExpr: IReduceExpr
{
private readonly string methodName;
private readonly IReduceExpr[] args;
public ReduceMethodExpr(string methodName,
params IReduceExpr[] args)
{
this.methodName = methodName;
this.args = args;
}
public void Write<T>(T generator) where T:Generator<T>
{
generator.Write(methodName)
.Write("(")
.Join(args,
(generator, item) => item.Write(generator),
",")
.Write(")");
}
}
public class ReduceNewExpr: IReduceExpr
{
private readonly string typeName;
private readonly IReduceExpr[] args;
public ReduceNewExpr(string typeName,
params IReduceExpr[] args)
{
this.typeName = typeName;
this.args = args;
}
public void Write<T>(T generator)
where T:Generator<T>
{
generator
.Write("new ")
.Write(typeName)
.Write("(")
.Join(args,
(generator, item) => item.Write(generator),
",")
.Write(")");
}
}
public class ReduceFieldExpr: IReduceExpr
{
private readonly IReduceExpr expr;
private readonly string fieldName;
public ReduceFieldExpr(IReduceExpr expr, string fieldName)
{
this.expr = expr;
this.fieldName = fieldName;
}
public void Write<T>(T generator) where T : Generator<T>
{
expr.Write(generator);
generator.Write('.')
.Write(fieldName);
}
}
}
|
<?php
namespace Test;
use ZfCompat\Db\Sql;
class SqlTest extends \DbCase
{
function getDataset()
{
return $this->createFlatXmlDataSet(__DIR__ . '/SqlTest.xml');
}
private function _getAdapter()
{
$params = array(
'driver', 'database', 'username', 'password', 'hostname',
'port', 'charset'
);
$config = array();
foreach ($params as $name) {
$val = getenv($name);
if (empty($val)) continue;
$config[$name] = $val;
}
return new \ZfCompat\Db\Adapter($config);
}
private function getInstance()
{
$adapter = $this->_getAdapter();
return new Sql($adapter, 'zftest');
}
function dataProvider_testFetchAll()
{
$sql = $this->getInstance();
return array(
array(
$sql->select(),
array(
array("id"=>1, "name"=>"山田", "number"=>765, "deci_number"=>"0.999"),
array("id"=>2, "name"=>"本田", "number"=>765, "deci_number"=>"0.999")
)
),
array(
$sql->select()->where(array('id'=>1)),
array(array("id"=>1, "name"=>"山田", "number"=>765, "deci_number"=>"0.999"))
)
);
}
/**
* @dataProvider dataProvider_testFetchAll
* @group Sql
*/
function testFetchAll($sql, $ext)
{
$instance = $this->getInstance();
$result = $instance->fetchAll($sql);
$this->assertEquals($ext, $result);
}
/**
* @group Sql
*/
function testFetchRow()
{
$adapter = $this->getInstance();
$sql = $adapter->select()->where(array('id'=>1));
$ext = array(
"id"=>1,
"name"=>"山田",
"number"=>765,
"deci_number"=>"0.999"
);
$result = $adapter->fetchRow($sql);
$this->assertEquals($ext, $result);
$sql = $adapter->select();
$result2 = $adapter->fetchRow($sql);
$this->assertEquals($result, $result2);
}
/**
* @group Sql
*/
function testFetchRow_emptyresult()
{
$adapter = $this->getInstance();
$sql = $adapter->select()->where(array('id'=>999999));
$result = $adapter->fetchRow($sql);
$this->assertSame(false, $result);
}
/**
* @group Sql
*/
function testFetchOne()
{
$adapter = $this->getInstance();
$sql = $adapter->select()
->columns(array('cnt' => new \Zend\Db\Sql\Expression('count(id)')))
->where(array('id'=>1));
$result = $adapter->fetchOne($sql);
$this->assertEquals(1, $result);
}
function testFetchOne_emptyresult()
{
$adapter = $this->getInstance();
$sql = $adapter->select()
->where(array('id'=>999999));
$result = $adapter->fetchOne($sql);
$this->assertSame(null, $result);
}
}
|
#!/usr/bin/env bash
# installing dependencies for lumen-generators
composer install --no-interaction
composer update --no-interaction
# installing dependencies for lumen-test
cd lumen-test && composer install --no-interaction
|
#!/usr/bin/zsh
set -e
echo "Unmounting iPhone..."
/usr/bin/fusermount -u /media/$USER/iPhone
echo "Unpairing iPhone..."
/usr/local/bin/idevicepair unpair
echo "Done!"
|
import {
Injectable,
CanActivate,
ExecutionContext,
HttpException,
} from '@nestjs/common';
import * as config from 'config';
import { Reflector } from '@nestjs/core';
const jwt = require('jsonwebtoken');
import { PrincipalContext } from '../../../shared/service/principal.context.service';
import { UsersService } from '../../../users/users.service';
import { UserInterface } from '../../../users/interfaces/user.interface';
const serverConfig: {
securityEnabled: boolean;
} = config.get('server');
const jwtConstants: {
secret: boolean;
} = config.get('jwtConstants');
const logOutError: {
error: string;
code: number;
} = config.get('logOutError');
@Injectable()
export class AuthGuard implements CanActivate {
public constructor(
private readonly reflector: Reflector,
private readonly userService: UsersService,
) {}
removeSecurityKeys(request) {
if (request && request.body) {
if (request.body instanceof Array) {
request.body = request.body.map(element => {
if (element && element instanceof Object) {
delete element.globalAccessMask;
delete element.rolesAccessMask;
delete element.usersAccessMask;
}
return element;
});
}
if (request.body instanceof Object) {
delete request.body.globalAccessMask;
delete request.body.rolesAccessMask;
delete request.body.usersAccessMask;
}
}
}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
this.removeSecurityKeys(request);
if (!serverConfig.securityEnabled) {
return true;
}
const isPublic = this.reflector.get<boolean>(
'isPublic',
context.getHandler(),
);
const allowUsersWithAutomatedPassword = this.reflector.get<boolean>(
'allowAutomatedPasswordUsers',
context.getHandler(),
);
if (isPublic) {
return true;
}
const user: UserInterface = AuthGuard.getDecodedUser(request);
if (!user) {
throw new HttpException(logOutError.error, logOutError.code);
}
const dbUser = await this.userService.findOne(user.email);
if (!dbUser || !dbUser._id) {
return false;
}
if (dbUser.isDeactivated) {
throw new HttpException(logOutError.error, logOutError.code);
}
if (dbUser.hasAutomatedPassword && !allowUsersWithAutomatedPassword) {
throw new HttpException(logOutError.error, logOutError.code);
}
PrincipalContext.User = dbUser;
return true;
}
static getDecodedUser(req) {
let token = null;
let decodedUser = null;
if (
req.headers.authorization &&
req.headers.authorization.split(' ')[0] === 'Bearer'
) {
token = req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
token = req.query.token;
} else if (req.cookies && req.cookies.authorization) {
token = req.cookies.authorization;
}
if (!token) {
return null;
}
try {
decodedUser = jwt.verify(token, jwtConstants.secret);
} catch (err) {
return null;
}
return decodedUser;
}
}
|
namespace Jurassic.Library
{
/// <summary>
/// Defines the element type and behaviour of typed array.
/// </summary>
public enum TypedArrayType
{
/// <summary>
/// An array of signed 8-bit elements.
/// </summary>
Int8Array,
/// <summary>
/// An array of unsigned 8-bit elements.
/// </summary>
Uint8Array,
/// <summary>
/// An array of unsigned 8-bit elements, clamped to 0-255.
/// </summary>
Uint8ClampedArray,
/// <summary>
/// An array of signed 16-bit elements.
/// </summary>
Int16Array,
/// <summary>
/// An array of unsigned 16-bit elements.
/// </summary>
Uint16Array,
/// <summary>
/// An array of signed 32-bit elements.
/// </summary>
Int32Array,
/// <summary>
/// An array of unsigned 32-bit elements.
/// </summary>
Uint32Array,
/// <summary>
/// An array of 32-bit floating point elements.
/// </summary>
Float32Array,
/// <summary>
/// An array of 64-bit floating point elements.
/// </summary>
Float64Array,
}
}
|
using System;
namespace FinanceDataMigrationApi.V1.Domain
{
public class SuspenseResolutionInfo
{
public DateTime? ResolutionDate { get; set; }
public bool IsResolve
{
get
{
if (IsConfirmed && IsApproved)
return true;
return false;
}
}
public bool IsConfirmed { get; set; }
public bool IsApproved { get; set; }
public string Note { get; set; }
}
}
|
/* Copyright 2009-2016 EPFL, Lausanne */
package leon
package synthesis
package strategies
import purescala.Common.FreshIdentifier
import graph._
class ManualStrategy(ctx: LeonContext, initCmd: Option[String], strat: Strategy) extends Strategy {
implicit val ctx_ = ctx
import ctx.reporter._
abstract class Command
case class Cd(path: List[Int]) extends Command
case object Parent extends Command
case object Quit extends Command
case object Noop extends Command
case object Best extends Command
case object Tree extends Command
case object Tests extends Command
case object Help extends Command
case object Search extends Command
// Manual search state:
var rootNode: Node = _
var path: List[Int] = Nil
var searchRoot: Option[List[Int]] = None
override def init(n: RootNode) = {
super.init(n)
strat.init(n)
rootNode = n
}
def currentNode(path: List[Int]): Node = {
def findFrom(n: Node, path: List[Int]): Node = {
path match {
case Nil => n
case p :: ps =>
findDescendent(n, p) match {
case Some(d) =>
findFrom(d, ps)
case None =>
n
}
}
}
findFrom(rootNode, path)
}
override def beforeExpand(n: Node) = {
super.beforeExpand(n)
strat.beforeExpand(n)
}
override def afterExpand(n: Node) = {
super.afterExpand(n)
strat.afterExpand(n)
// Backtrack view to a point where node is neither closed nor solved
if (n.isDeadEnd || n.isSolved) {
val backtrackTo = findAncestor(n, n => !n.isDeadEnd && !n.isSolved)
path = backtrackTo.map(pathTo).getOrElse(Nil)
}
}
private def findAncestor(n: Node, f: Node => Boolean): Option[Node] = {
n.parent.flatMap { n =>
if (f(n)) Some(n) else findAncestor(n, f)
}
}
private def pathTo(n: Node): List[Int] = {
n.parent match {
case None => Nil
case Some(p) => pathTo(p) :+ p.descendants.indexOf(n)
}
}
def bestAlternative(n: OrNode) = strat.bestAlternative(n)
def printGraph() {
def title(str: String) = "\u001b[1m" + str + "\u001b[0m"
def failed(str: String) = "\u001b[31m" + str + "\u001b[0m"
def solved(str: String) = "\u001b[32m" + str + "\u001b[0m"
def expanded(str: String) = "\u001b[33m" + str + "\u001b[0m"
def displayNode(n: Node, inTitle: Boolean = false): String = {
n match {
case an: AndNode =>
val app = an.ri.asString(ctx)
s"(${debugInfoFor(n)}) ${indent(app, inTitle)}"
case on: OrNode =>
val p = on.p.asString(ctx)
s"(${debugInfoFor(n)}) ${indent(p, inTitle)}"
}
}
def indent(a: String, inTitle: Boolean): String = {
a.replaceAll("\n", "\n"+(" "*(if(inTitle) 11 else 13)))
}
def pathToString(cd: List[Int]): String = {
cd.map(i => f"$i%2d").mkString(" ")
}
val c = currentNode(path)
println("-"*120)
val at = path.lastOption.map(p => pathToString(List(p))).getOrElse(" R")
println(title(at+" \u2510 "+displayNode(c, true)))
for ((sn, i) <- c.descendants.zipWithIndex) {
val sp = List(i)
if (sn.isSolved) {
println(solved(" "+pathToString(sp)+" \u2508 "+displayNode(sn)))
} else if (sn.isDeadEnd) {
println(failed(" "+pathToString(sp)+" \u2508 "+displayNode(sn)))
} else if (sn.isExpanded) {
println(expanded(" "+pathToString(sp)+" \u2508 "+displayNode(sn)))
} else {
println(" "+pathToString(sp)+" \u2508 "+displayNode(sn))
}
}
println("-"*120)
}
var continue = true
def findDescendent(n: Node, index: Int): Option[Node] = {
n.descendants.zipWithIndex.find(_._2 == index).map(_._1)
}
def manualGetNext(): Option[Node] = {
val c = currentNode(path)
if (!c.isExpanded) {
Some(c)
} else {
printGraph()
nextCommand() match {
case Quit =>
None
case Help =>
val tOpen = "\u001b[1m"
val tClose = "\u001b[0m"
println(s"""|
|${tOpen}Available commands: $tClose
|$tOpen (cd) N $tClose Expand descendant N
|$tOpen cd .. $tClose Go one level up
|$tOpen b $tClose Expand best descendant
|$tOpen p $tClose Display the partial solution around the current node
|$tOpen t $tClose Display tests
|$tOpen s $tClose Search automatically from current node
|$tOpen q $tClose Quit the search
|$tOpen h $tClose Display this message
|""".stripMargin)
manualGetNext()
case Parent =>
if (path.nonEmpty) {
path = path.dropRight(1)
} else {
error("Already at root node!")
}
manualGetNext()
case Tests =>
println(c.p.eb.asString("Tests"))
manualGetNext()
case Tree =>
val hole = FreshIdentifier("\u001b[1;31m??? \u001b[0m", c.p.outType)
val ps = new PartialSolution(this, true)
println("c: "+c)
println("c: "+c.getClass)
ps.solutionAround(c)(hole.toVariable) match {
case Some(sol) =>
println("-"*120)
println(sol.toExpr.asString)
case None =>
error("woot!")
}
manualGetNext()
case Best =>
strat.bestNext(c) match {
case Some(n) =>
val i = c.descendants.indexOf(n)
path = path :+ i
Some(currentNode(path))
case None =>
error("Woot?")
manualGetNext()
}
case Search =>
val continue = searchRoot match {
case Some(sPath) =>
path.size > sPath.size
case None =>
println("Searching...")
searchRoot = Some(path)
true
}
if (continue) {
cmdQueue = Best :: Search :: cmdQueue
} else {
searchRoot = None
}
manualGetNext()
case Cd(Nil) =>
error("Woot?")
None
case Cd(next :: rest) =>
findDescendent(c, next) match {
case Some(_) =>
path = path :+ next
case None =>
warning("Unknown descendant: "+next)
}
if (rest.nonEmpty) {
cmdQueue = Cd(rest) :: cmdQueue
}
manualGetNext()
}
}
}
override def getNextToExpand(root: Node): Option[Node] = {
manualGetNext()
}
def debugInfoFor(n: Node) = strat.debugInfoFor(n)
var cmdQueue = initCmd.map( str => parseCommands(parseString(str))).getOrElse(Nil)
private def parseString(s: String): List[String] = {
Option(s).map(_.trim.split("\\s+|,").toList).getOrElse(fatalError("End of stream"))
}
private def nextCommand(): Command = cmdQueue match {
case c :: cs =>
cmdQueue = cs
c
case Nil =>
print("Next action? (h for help) "+path.mkString(" ")+" $ ")
val line = scala.io.StdIn.readLine()
val parts = parseString(line)
cmdQueue = parseCommands(parts)
nextCommand()
}
private def parseCommands(tokens: List[String]): List[Command] = tokens match {
case "cd" :: ".." :: ts =>
Parent :: parseCommands(ts)
case "cd" :: ts =>
val path = ts.takeWhile { t => t.forall(_.isDigit) }
if (path.isEmpty) {
parseCommands(ts)
} else {
Cd(path.map(_.toInt)) :: parseCommands(ts.drop(path.size))
}
case "p" :: ts =>
Tree :: parseCommands(ts)
case "t" :: ts =>
Tests :: parseCommands(ts)
case "s" :: ts =>
Search :: parseCommands(ts)
case "b" :: ts =>
Best :: parseCommands(ts)
case "h" :: ts =>
Help :: parseCommands(ts)
case "q" :: ts =>
Quit :: Nil
case Nil | "" :: Nil =>
Nil
case ts =>
val path = ts.takeWhile { t => t.forall(_.isDigit) }
if (path.isEmpty) {
error("Unknown command "+ts.head)
parseCommands(ts.tail)
} else {
Cd(path.map(_.toInt)) :: parseCommands(ts.drop(path.size))
}
}
}
|
import 'dart:async';
import 'package:bnb_wallet/infrastructures/grpc/generated/models.pb.dart';
import 'package:bnb_wallet/infrastructures/grpc/generated/quote.pb.dart';
import 'package:bnb_wallet/infrastructures/grpc/market/rpc_quote.dart';
import 'package:bnb_wallet/utils/device_util.dart';
import 'package:bnb_wallet/view/market/market_detail_context.dart';
import 'package:bnb_wallet/view/market/tabview/page_depth_detail_tab_view.dart';
import 'package:flutter/material.dart';
import 'package:grpc/grpc.dart';
import 'package:rxdart/rxdart.dart';
abstract class DepthDetailTabViewState extends State<DepthDetailTabView>
with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
ReplaySubject depthFigureSubject =
ReplaySubject<GetDepthResponse>(maxSize: 1);
PublishSubject<GetDepthResponse> depthSubjectFigure;
ResponseStream stream;
StreamSubscription streamSubscription;
StreamSubscription _rsStreamSubscription;
String tradeMarket;
String payMarket;
MarketDetailContext marketDetailContext;
DepthDetailTabViewState({this.payMarket, this.tradeMarket});
@override
void initState() {
super.initState();
depthSubjectFigure = PublishSubject<GetDepthResponse>();
_initData();
}
///getQuoteDepth
void _initData() async {
var uid = await DeviceUtil.instance.deviceId;
try {
stream = RpcQuoteManager.instance.getQuoteDepthFigure(
uid: uid,
tradeMarket: tradeMarket,
payMarket: payMarket,
);
streamSubscription = stream?.listen((rsp) {
if (!depthFigureSubject.isClosed) {
depthSubjectFigure.add(rsp);
}
}, onDone: () {
//stream?.cancel();
},onError: (e){
if(e is GrpcError && e.code != StatusCode.cancelled){
if (!depthFigureSubject.isClosed) {
depthSubjectFigure.addError(e);
}
}
});
} catch (_) {
if (!depthFigureSubject.isClosed) {
depthSubjectFigure.addError('');
}
}
}
void startLoadAgain() {
depthSubjectFigure.add(null);
_initData();
}
void sortDepth(List<Depth> list, {bool reverse = false}) {
list.sort((Depth a, Depth b) {
if (double.parse(a.price) > double.parse(b.price)) {
return reverse ? -1 : 1;
} else if (double.parse(a.price) == double.parse(b.price)) {
return 0;
} else {
return reverse ? 1 : -1;
}
});
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
marketDetailContext = MarketDetailContext.of(context);
_rsStreamSubscription = widget.reloadSubject.stream.listen((quote) {
if (quote is DynamicQuote) {
if (quote.tradeMarket == tradeMarket && quote.payMarket == payMarket) {
return;
}
if (mounted) {
setState(() {
tradeMarket = quote.tradeMarket;
payMarket = quote.payMarket;
stream?.cancel();
depthSubjectFigure.add(null);
_initData();
});
}
}
});
}
@override
void dispose() {
streamSubscription?.cancel();
depthFigureSubject?.close();
depthSubjectFigure?.close();
_rsStreamSubscription?.cancel();
super.dispose();
}
}
|
// File generated from our OpenAPI spec
package com.jaguar.model;
import com.google.gson.annotations.SerializedName;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public class SourceTransaction extends JaguarObject implements HasId {
@SerializedName("ach_credit_transfer")
AchCreditTransferData achCreditTransfer;
/**
* A positive integer in the smallest currency unit (that is, 100 cents for $1.00, or 1 for ¥1,
* Japanese Yen being a zero-decimal currency) representing the amount your customer has pushed to
* the receiver.
*/
@SerializedName("amount")
Long amount;
@SerializedName("chf_credit_transfer")
ChfCreditTransferData chfCreditTransfer;
/** Time at which the object was created. Measured in seconds since the Unix epoch. */
@SerializedName("created")
Long created;
/**
* Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>,
* in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
*/
@SerializedName("currency")
String currency;
@SerializedName("gbp_credit_transfer")
GbpCreditTransferData gbpCreditTransfer;
/** Unique identifier for the object. */
@Getter(onMethod_ = {@Override})
@SerializedName("id")
String id;
/**
* Has the value {@code true} if the object exists in live mode or the value {@code false} if the
* object exists in test mode.
*/
@SerializedName("livemode")
Boolean livemode;
/**
* String representing the object's type. Objects of the same type share the same value.
*
* <p>Equal to {@code source_transaction}.
*/
@SerializedName("object")
String object;
@SerializedName("paper_check")
PaperCheckData paperCheck;
@SerializedName("sepa_credit_transfer")
SepaCreditTransferData sepaCreditTransfer;
/** The ID of the source this transaction is attached to. */
@SerializedName("source")
String source;
/**
* The status of the transaction, one of {@code succeeded}, {@code pending}, or {@code failed}.
*/
@SerializedName("status")
String status;
/**
* The type of source this transaction is attached to.
*
* <p>One of {@code ach_credit_transfer}, {@code ach_debit}, {@code alipay}, {@code bancontact},
* {@code card}, {@code card_present}, {@code eps}, {@code giropay}, {@code ideal}, {@code
* klarna}, {@code multibanco}, {@code p24}, {@code sepa_debit}, {@code sofort}, {@code
* three_d_secure}, or {@code wechat}.
*/
@SerializedName("type")
String type;
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class AchCreditTransferData extends JaguarObject {
/** Customer data associated with the transfer. */
@SerializedName("customer_data")
String customerData;
/** Bank account fingerprint associated with the transfer. */
@SerializedName("fingerprint")
String fingerprint;
/** Last 4 digits of the account number associated with the transfer. */
@SerializedName("last4")
String last4;
/** Routing number associated with the transfer. */
@SerializedName("routing_number")
String routingNumber;
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class ChfCreditTransferData extends JaguarObject {
/** Reference associated with the transfer. */
@SerializedName("reference")
String reference;
/** Sender's country address. */
@SerializedName("sender_address_country")
String senderAddressCountry;
/** Sender's line 1 address. */
@SerializedName("sender_address_line1")
String senderAddressLine1;
/** Sender's bank account IBAN. */
@SerializedName("sender_iban")
String senderIban;
/** Sender's name. */
@SerializedName("sender_name")
String senderName;
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class GbpCreditTransferData extends JaguarObject {
/**
* Bank account fingerprint associated with the Stripe owned bank account receiving the
* transfer.
*/
@SerializedName("fingerprint")
String fingerprint;
/**
* The credit transfer rails the sender used to push this transfer. The possible rails are:
* Faster Payments, BACS, CHAPS, and wire transfers. Currently only Faster Payments is
* supported.
*/
@SerializedName("funding_method")
String fundingMethod;
/** Last 4 digits of sender account number associated with the transfer. */
@SerializedName("last4")
String last4;
/** Sender entered arbitrary information about the transfer. */
@SerializedName("reference")
String reference;
/** Sender account number associated with the transfer. */
@SerializedName("sender_account_number")
String senderAccountNumber;
/** Sender name associated with the transfer. */
@SerializedName("sender_name")
String senderName;
/** Sender sort code associated with the transfer. */
@SerializedName("sender_sort_code")
String senderSortCode;
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class PaperCheckData extends JaguarObject {
/**
* Time at which the deposited funds will be available for use. Measured in seconds since the
* Unix epoch.
*/
@SerializedName("available_at")
String availableAt;
/** Comma-separated list of invoice IDs associated with the paper check. */
@SerializedName("invoices")
String invoices;
}
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
public static class SepaCreditTransferData extends JaguarObject {
/** Reference associated with the transfer. */
@SerializedName("reference")
String reference;
/** Sender's bank account IBAN. */
@SerializedName("sender_iban")
String senderIban;
/** Sender's name. */
@SerializedName("sender_name")
String senderName;
}
}
|
/**
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
* This file is licensed under the Apache Software License,
* v. 2 except as noted otherwise in the LICENSE file
* https://github.com/SAP/cloud-security-xsuaa-integration/blob/master/LICENSE
*/
package com.sap.xsa.security.container;
/**
* API for OAuth resource servers to extract authentication and authorization
* information from the OAuth token.
*/
public interface XSUserInfo {
/**
* User name used for authentication, e.g. an email address or other
* identifier. A user might exist in multiple identity providers. The
* following information is required to to uniquely identify a user: - -
*
*
* - username: name of the user in an identity provider
*
* - origin: alias to an identity provider
*
* - subaccount id: identifier for the subaccount
*
* @return user name
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getLogonName() throws XSUserInfoException;
/**
* Given name of the user.
*
* @return given name
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getGivenName() throws XSUserInfoException;
/**
* Familiy name of the user.
*
* @return family name
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getFamilyName() throws XSUserInfoException;
/**
* Return the user origin. The origin is an alias that refers to a user store in which the user is persisted.
* For example, users that are authenticated by the UAA itself with a username/password combination
* have their origin set to the value uaa.
*
* @return user origin
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getOrigin() throws XSUserInfoException;
/**
* Return identity zone
*
* @return identity zone
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
String getIdentityZone() throws XSUserInfoException;
/**
* Return subaccount identifier
*
* @return subaccount identifier
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getSubaccountId() throws XSUserInfoException;
/**
* Return the subdomain of this subaccount
*
* @return subdomain
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getSubdomain() throws XSUserInfoException;
/**
* Return the client id of the authentication token
*
* @return client id
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getClientId() throws XSUserInfoException;
@Deprecated
public String getJsonValue(String attribute) throws XSUserInfoException;
/**
* Return the email of the user
*
* @return email
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getEmail() throws XSUserInfoException;
@Deprecated // use getHdbToken
public String getDBToken() throws XSUserInfoException;
public String getHdbToken() throws XSUserInfoException;
/**
* Return authentication token
*
* @return authentication token
*/
public String getAppToken();
@Deprecated
public String getToken(String namespace, String name) throws XSUserInfoException;
/**
* Return user attributes
*
* @param attributeName
* name of attribute
* @return attribute values array
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String[] getAttribute(String attributeName) throws XSUserInfoException;
/**
* Check if the authentication token contains user attributes
*
* @return true if user attributes are available
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public boolean hasAttributes() throws XSUserInfoException;
@Deprecated
public String[] getSystemAttribute(String attributeName) throws XSUserInfoException;
/**
* Check if a scope is present in the authentication token
*
* @param scope
* name of fully qualified scope
* @return true if scope is available
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public boolean checkScope(String scope) throws XSUserInfoException;
/**
* Check if a local scope is available in the authentication token
*
* @param scope
* name of local scope (ommitting the xsappid)
* @return true if local scope (scope without xsappid) is available
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public boolean checkLocalScope(String scope) throws XSUserInfoException;
/**
* Return additional authentication attributes included by the OAuth client
* component. Note: this is data controlled by the requester of a token.
* Might be not trustworthy.
*
* @param attributeName
* name of the authentication attribute
* @return addition authentication attributes
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getAdditionalAuthAttribute(String attributeName) throws XSUserInfoException;
/**
* In case of xsuaa broker plan tokens, it contains the service instance id
*
* @return service instance id
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getCloneServiceInstanceId() throws XSUserInfoException;
/**
* OAuth Grant Type used for this token
*
* @return grant type
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String getGrantType() throws XSUserInfoException;
/**
* Check if a token issued for another OAuth client has been forwarded to a
* different client,
*
* @return true if token was forwarded
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public boolean isInForeignMode() throws XSUserInfoException;
@Deprecated // use requestToken
public String requestTokenForClient(String clientId, String clientSecret, String uaaUrl) throws XSUserInfoException;
/**
* Exchange a token into a token from another service instance
*
* @param tokenRequest
* request data
* @return requested token
* @throws XSUserInfoException
* if attribute is not available in the authentication token
*/
public String requestToken(XSTokenRequest tokenRequest) throws XSUserInfoException;
}
|
using System.Xml.Linq;
namespace Knapcode.ExplorePackages.Entities
{
public class FindMixedDependencyGroupStylesNuspecQuery : INuspecQuery
{
public string Name => PackageQueryNames.FindMixedDependencyGroupStylesNuspecQuery;
public string CursorName => CursorNames.FindMixedDependencyGroupStylesNuspecQuery;
public bool IsMatch(XDocument nuspec)
{
return NuspecUtility.HasMixedDependencyGroupStyles(nuspec);
}
}
}
|
/*
* vRealize Network Insight API Reference
*
* vRealize Network Insight API Reference
*
* API version: 1.1.8
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package vrni
// WebProxyRequest struct for WebProxyRequest
type WebProxyRequest struct {
// Descriptor or identifier for particular web proxy. It should be unique
NickName string `json:"nick_name,omitempty"`
// IP address of web Proxy server
TargetIp string `json:"target_ip,omitempty"`
// Port number of web Proxy server
TargetPort int32 `json:"target_port,omitempty"`
// Type of web Proxy being configured. [Permitted Values - HTTP/HTTPS]
ProxyType string `json:"proxy_type,omitempty"`
// Type of authentication. [Permitted Values - Basic/NTLM]
AuthType string `json:"auth_type,omitempty"`
// Credentials required for this web proxy
UseCredentials bool `json:"use_credentials,omitempty"`
// Username for web proxy authentication
UserName string `json:"user_name,omitempty"`
// Password for web proxy authentication
Password string `json:"password,omitempty"`
}
|
//go:generate go-bindata -pkg web -o templates_and_migrations_gen.go templates/... db_migrations
package web
|
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Projet;
use Illuminate\Support\Facades\Auth;
class ProjetController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$projets = Projet::all();
return view('projet.index')->with(compact('projets'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$users = User::all()->lists('name', 'type',
'descriptif', 'context', 'objectif', 'contrainte');
return view('projet.create')->with(compact('users'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Requests\ProjetRequest $request)
{
$projet = new Projet;
$projet->user_id = Auth::user()->id;
$projet->username = Auth::user()->name;
$projet->id = $request->id;
$projet->validate = $request->validate;
$projet->name = $request->name;
$projet->type = $request->type;
$projet->typeother = $request->typeother;
$projet->descriptif = $request->descriptif;
$projet->context = $request->context;
$projet->objectif = $request->objectif;
$projet->contrainte = $request->contrainte;
$projet->save();
return redirect()
->route('projet.show', $projet->id)
->with(compact('projet'));
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
try{
$projet = Projet::findOrFail($id);
return view('projet.show')->with(compact('projet'));
}catch(\Exception $e){
return redirect()->route('projet.index')->with(['erreur'=>'Whoooooops']);
}
return view('projet.show')->with(compact('projet'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$projet = Projet::find($id);
$users = User::all()->lists('name', 'id') ;
return view('projet.edit')->with(compact('projet', 'users')); }
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$projet = Projet::find($id);
$projet->validate = $request->validate;
$projet->name = $request->name;
$projet->username = $request->username;
$projet->type = $request->type;
$projet->typeother = $request->typeother;
$projet->descriptif = $request->descriptif;
$projet->context = $request->context;
$projet->objectif = $request->objectif;
$projet->contrainte = $request->contrainte;
$projet->descriptif = $request->descriptif;
// $projet->user_id = $request->user_id;
$projet->save();
return redirect()->route('projet.show', $projet->id);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
} |
#!/bin/bash
# Color log lines according to level
case $1 in
-h | --help ) echo "usage: $(basename $0)"; exit;;
esac
if [ $# -ne 0 ]; then
2>&1 echo "error: wrong number of arguments"
exit 1
fi
awk '
/INFO/ {print "\033[32m" $0 "\033[39m"; next}
/WARNING/ {print "\033[33m" $0 "\033[39m"; next}
/CRITICAL/ {print "\033[31m" $0 "\033[39m"; next}
/FATAL/ {print "\033[31m" "\033[1m" $0 "\033[0m" "\033[39m"; next}
// {print $0}
'
|
# coc-lines
Lines source for coc.nvim
## Install
`:CocInstall coc-lines`
## Usages
- line sources added to completion sources, with `[LN]` shortcut
- `:CocList fuzzy_lines`: list current buffer lines with fuzzy search
## License
MIT
---
> This extension is created by [create-coc-extension](https://github.com/fannheyward/create-coc-extension)
|
using AGO.Tasks.Controllers;
namespace AGO.Tasks.Test
{
public class AbstractDictionaryTest: AbstractTest
{
protected DictionaryController Controller { get; private set; }
public override void FixtureSetUp()
{
base.FixtureSetUp();
Controller = IocContainer.GetInstance<DictionaryController>();
}
}
} |
package config
import (
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
var C Config
type Config struct {
Kafka KafkaServiceConfig
}
type KafkaServiceConfig struct {
Rpc map[string]string
Isolations []KafkaIsolation
}
type KafkaIsolation struct {
Keyword string
ProducerConfig map[string]interface{}
ConsumerConfig map[string]interface{}
}
func InitConfig(path string) {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(path)
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Fatal("Config file not found; ignore error if desired")
} else {
log.Fatal("Config file was found but another error was produced")
}
}
err := viper.Unmarshal(&C)
if err != nil {
log.Fatalf("unable to decode into struct, %v", err)
}
}
func (T *Config) GetKafkaServiceConfig() KafkaServiceConfig {
return T.Kafka
}
|
package plus.yuhaozhang.service.cos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
* @author Yuh Z
* @date 1/19/22
*/
@SpringBootApplication
@ComponentScan(basePackages = {"plus.yuhaozhang"})
public class CosApplication {
public static void main(String[] args) {
SpringApplication.run(CosApplication.class,args);
}
}
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'endpoint.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Map<String, dynamic> _$EndpointToJson(Endpoint instance) => <String, dynamic>{
'path': instance.path,
'method': instance.method,
'name': instance.name,
'responseType': instance.responseType,
'parameters': instance.parameters.map((e) => e.toJson()).toList(),
'requestType': instance.requestType,
'paramsType': instance.paramsType,
'requiresAuthentication': instance.requiresAuthentication,
'hasParams': instance.hasParams,
'hasRequest': instance.hasRequest,
'queryParameters':
instance.queryParameters.map((e) => e.toJson()).toList(),
'headerParameters':
instance.headerParameters.map((e) => e.toJson()).toList(),
'pathParameters': instance.pathParameters.map((e) => e.toJson()).toList(),
'isInFunctionsObjects': instance.isInFunctionsObjects,
'pathWithParams': instance.pathWithParams,
};
|
//
// IMPORTS
//
// libraries
// app modules
import linkupRadar from './radar/linkupRadar'
import linkupTables from './radar/linkupTables'
import { showFilterTagForm, updateFilterList, filterBlips } from './radar/filterTags'
import { getStatsActive, getTags, setStatsActive, updateTags } from './util/localStore'
import showAlert from './util/alert'
import { login, logout } from './user/login'
import changePassword from './user/userSettings'
import {
createUser,
deleteUser,
updateUsersDetails,
updateUsersPassword,
} from './admin/userActions'
import { createRadar, updateRadar, deleteRadar, advanceRadar } from './admin/radarActions'
import { createProject, deleteProject, updateProject, importProjects } from './admin/projectActions'
import { addClassification, addScore } from './admin/scoreAndClassify'
import { getName } from '../../common/datamodel/jrc-taxonomy'
import { searchProjects, clearProjects } from './radar/search.js'
import { fetchRendering, fetchStats } from './radar/asyncRendering'
import { RadarCoordinates } from '../../common/widgets/radar-location/radar-coords'
import { RadarLocation } from '../../common/widgets/radar-location/radar-location'
import { SimpleMetric } from '../../common/widgets/simple-metric/simple-metric'
import { SDLCPosition } from '../../common/widgets/sdlc-position/sdlc-position'
import { MTRLPerformance } from '../../common/widgets/mtrl-performance/mtrl-performance'
import { MTRLGraph } from '../../common/widgets/mtrlScoreGraph/mtrl-graph'
import { MTRLHist } from '../../common/widgets/mtrlScoreHist/mtrl-hist'
/**************************************/
/* */
/* C U S T O M E L E M E N T S */
/* */
/**************************************/
// register custom HTML elements for this radar
customElements.define('simple-metric', SimpleMetric)
customElements.define('sdlc-position', SDLCPosition)
customElements.define('radar-coords', RadarCoordinates)
customElements.define('mtrl-performance', MTRLPerformance)
customElements.define('radar-location', RadarLocation)
customElements.define('mtrl-graph', MTRLGraph)
customElements.define('mtrl-hist', MTRLHist)
/***********************/
/* */
/* D O C U M E N T */
/* */
/***********************/
//
// add keyboard listener
//
document.addEventListener('keydown', (e) => {
// ESC key closes modals
if (e.key === 'Escape') {
const modals = document.getElementById('modals').childNodes
if (modals && modals.length > 0) {
modals[modals.length - 1].remove()
}
}
})
/****************************************************************
* *
* M E N U B A R *
* *
****************************************************************/
//
// RADAR MENU BUTTONS EVENT
//
const radarButtons = document.querySelectorAll('.radar')
if (radarButtons) {
radarButtons.forEach((btn) => {
btn.addEventListener('click', (event) => {
event.preventDefault()
const slug = event.target.getAttribute('radar')
location.assign(`/radar/${slug}`)
})
})
}
//
// ADMIN MENU BUTTONS EVENT
//
const adminButtons = document.querySelectorAll('.admin')
if (adminButtons) {
adminButtons.forEach((btn) => {
btn.addEventListener('click', (event) => {
event.preventDefault()
const route = event.target.getAttribute('route')
location.assign(route)
})
})
}
//
// Disclaimer button
//
const disclaimerButton = document.querySelector('.disclaimer')
if (disclaimerButton) {
disclaimerButton.addEventListener('click', (e) => {
e.preventDefault()
const route = e.target.getAttribute('route')
location.assign(route)
})
}
//
// Documentation button
//
const documentationButton = document.querySelector('.documentation')
if (documentationButton) {
documentationButton.addEventListener('click', (e) => {
e.preventDefault()
const route = e.target.getAttribute('route')
location.assign(route)
})
}
/****************************************************************
* *
* U S E R A C C O U N T A C T I O N S *
* *
****************************************************************/
//
// Login form
//
const loginForm = document.getElementById('login-form')
if (loginForm) {
loginForm.addEventListener('submit', (e) => {
e.preventDefault()
const name = document.getElementById('name').value
const password = document.getElementById('password').value
login(name, password, document.referrer)
})
}
//
// Logout
//
const logOutBtn = document.querySelector('.nav__el--logout')
if (logOutBtn) logOutBtn.addEventListener('click', logout)
//
// Change password
//
const passwordForm = document.getElementById('password-form')
if (passwordForm) {
passwordForm.addEventListener('submit', async (e) => {
e.preventDefault()
document.querySelector('.btn--update-password').textContent = 'Updating...'
const current = document.getElementById('current').value
const newPass = document.getElementById('newPass').value
const newConfirm = document.getElementById('newConfirm').value
await changePassword(current, newPass, newConfirm)
document.querySelector('.btn--update-password').textContent = 'Change password'
document.getElementById('current').textContent = ''
document.getElementById('newPass').textContent = ''
document.getElementById('newConfirm').textContent = ''
})
}
/****************************************************************
* *
* R A D A R D I S P L A Y *
* *
****************************************************************/
//
// Interactive search form
//
const searchField = document.getElementById('search_term')
if (searchField) {
searchField.addEventListener('keyup', () => searchProjects(searchField.value))
}
// clear button
const clearBtn = document.getElementById('search_clear')
if (clearBtn) {
clearBtn.addEventListener('click', () => {
if (searchField) searchField.value = ''
clearProjects()
})
}
// stats panel checkbox
const statsCheckbox = document.getElementById('active')
if (statsCheckbox) {
const node = document.querySelector('#stats > .stats_panel')
getStatsActive().then((isActive) => {
if (isActive) {
statsCheckbox.checked = true
node.style.display = 'flex'
} else {
statsCheckbox.checked = false
node.style.display = 'none'
}
})
statsCheckbox.addEventListener('click', (e) => {
// react to event
node.style.display = e.target.checked ? 'flex' : 'none'
// and update local storage
setStatsActive(e.target.checked)
// trigger updating the stats
fetchStats(e.target.checked)
})
}
//
// Display the radar
//
const radarSection = document.getElementById('radar')
if (radarSection) {
// 1) Fetch the radar and local storage data
let tasks = []
tasks.push(fetchRendering(window.location.href))
tasks.push(getTags())
tasks.push(getStatsActive())
Promise.all(tasks)
.then((results) => {
// 2) Add rendering and tables as hidden element to the UI
if (results[0]) {
// svg
const temp = document.createElement('div')
temp.innerHTML = results[0].data.rendering.rendering.svg
temp.firstChild.style.display = 'none'
document.getElementById('rendering').appendChild(temp.firstChild)
// tables
document.getElementById('tables').innerHTML =
results[0].data.rendering.rendering.tables
}
// set up a new batch of parallel tasks and fire away
if (results[1]) {
tasks = [
tasks[2], // push down the stats task for the next .then()
filterBlips(results[1], updateFilterList(results[1], getName)),
linkupRadar(), // make radar and tables interactive
linkupTables(),
]
return Promise.all(tasks)
}
})
.then((results) => {
// 3) fetch and display the statistics
fetchStats(results[0])
// 4) Show radar, while loadStats executes (or not)
const loadWait = document.getElementById('loadwait')
loadWait.remove()
const svg = document.querySelector('#rendering svg')
svg.style.display = 'block'
})
.catch((err) => {
showAlert('error', err)
})
}
//
// Show JRC tag filter modal form
//
const jrcTagFormButton = document.querySelector('#jrctagsfilter button')
if (jrcTagFormButton) {
// wire up the button to show the filter tags meny
jrcTagFormButton.addEventListener('click', (event) => {
event.preventDefault()
// show modal
showFilterTagForm()
})
}
//
// Radio buttons for any or all matching
//
const anyAllRadios = document.querySelectorAll('div.ops input')
if (anyAllRadios) {
anyAllRadios.forEach((radio) => {
radio.addEventListener('click', async (event) => {
const filter = await getTags()
filter.union = event.target.value
await updateTags(filter)
await filterBlips(filter)
fetchStats(await getStatsActive())
})
})
}
/*********************************************************/
/*********************************************************/
/*********************************************************/
/*********************************************************/
/*********************************************************/
//
// Create user
//
const newUserForm = document.getElementById('new-user-form')
if (newUserForm) {
newUserForm.addEventListener('submit', async (e) => {
e.preventDefault()
document.getElementById('btn--create-user').textContent = 'Updating...'
const name = document.getElementById('name').value
const email = document.getElementById('email').value
const password = document.getElementById('password').value
const confirm = document.getElementById('confirm').value
const role = document.getElementById('role').value
await createUser(name, email, password, confirm, role, location.href)
document.getElementById('btn--create-user').textContent = 'Create user'
document.getElementById('name').textContent = ''
document.getElementById('email').textContent = ''
document.getElementById('password').textContent = ''
document.getElementById('confirm').textContent = ''
})
}
//
// DELETE USER LINKS
//
const deleteUserLinks = document.querySelectorAll('.delete-user')
if (deleteUserLinks) {
deleteUserLinks.forEach((link) => {
link.addEventListener('click', async (event) => {
event.preventDefault()
await deleteUser(event.path[1].getAttribute('route'), location.href)
})
})
}
//
// EDIT USER LINKS
//
const editUserLinks = document.querySelectorAll('.edit-user')
if (editUserLinks) {
editUserLinks.forEach((link) => {
link.addEventListener('click', async (event) => {
event.preventDefault()
location.assign(event.path[1].getAttribute('route'))
})
})
}
//
// UPDATE USER'S DETAILS BUTTON
//
const updateUserDetailsForm = document.getElementById('edit-user-form')
if (updateUserDetailsForm) {
updateUserDetailsForm.addEventListener('submit', async (event) => {
event.preventDefault()
const name = document.getElementById('name').value
const email = document.getElementById('email').value
const role = document.getElementById('role').value
const id = document.getElementById('userid').value
await updateUsersDetails(name, email, role, id)
})
}
//
// UPDATE USER'S PASSWORD BUTTON
//
const setUserPasswordForm = document.getElementById('set-password-form')
if (setUserPasswordForm) {
setUserPasswordForm.addEventListener('submit', async (event) => {
event.preventDefault()
const userid = document.getElementById('userid').value
const password = document.getElementById('newPass').value
const confirm = document.getElementById('newConfirm').value
await updateUsersPassword(userid, password, confirm)
})
}
//
// CREATE RADAR FORM
//
const createRadarForm = document.getElementById('new-radar-form')
if (createRadarForm) {
createRadarForm.addEventListener('submit', async (event) => {
event.preventDefault()
const edition = document.getElementById('edition').value
const year = document.getElementById('year').value
const summary = document.getElementById('summary').value
await createRadar(edition, year, summary)
})
}
//
// EDIT RADAR BUTTONS
//
const editRadarLinks = document.querySelectorAll('.edit-radar')
if (editRadarLinks) {
editRadarLinks.forEach((link) => {
link.addEventListener('click', async (event) => {
event.preventDefault()
location.assign(event.path[1].getAttribute('route'))
})
})
}
//
// DELETE RADAR BUTTONS
//
const deleteRadarLinks = document.querySelectorAll('.delete-radar')
if (deleteRadarLinks) {
deleteRadarLinks.forEach((link) => {
link.addEventListener('click', async (event) => {
event.preventDefault()
console.log(event.path[1].getAttribute('route'))
await deleteRadar(event.path[1].getAttribute('route'), location.href)
})
})
}
//
// EDIT INDIVIDUAL RADAR
//
const updateRadarForm = document.getElementById('edit-radar-form')
if (updateRadarForm) {
updateRadarForm.addEventListener('submit', async (event) => {
event.preventDefault()
const id = document.getElementById('radarid').value
const summary = document.getElementById('summary').value
await updateRadar(id, summary)
})
}
//
// ADMINISTER RADAR BUTTONS
//
const administerRadarForms = document.querySelectorAll('.administer-radar-form')
if (administerRadarForms) {
administerRadarForms.forEach((form) => {
form.addEventListener('submit', async (event) => {
event.preventDefault()
const cutoff = document.getElementById('cutoff').value
const route = event.target.getAttribute('route')
advanceRadar(route, cutoff, location.href)
})
})
}
//
// CREATE NEW PROJECT FORM
//
const newProjectForm = document.getElementById('new-project-form')
if (newProjectForm) {
newProjectForm.addEventListener('submit', async (event) => {
event.preventDefault()
const values = {
acronym: document.getElementById('acronym').value,
rcn: document.getElementById('rcn').value,
title: document.getElementById('title').value,
startDate: document.getElementById('startdate').value,
endDate: document.getElementById('enddate').value,
call: document.getElementById('fundingcall').value,
type: document.getElementById('projecttype').value,
totalCost: document.getElementById('totalCost').value,
url: document.getElementById('url').value,
fundingBodyLink: document.getElementById('fundingbodylink').value,
cwurl: document.getElementById('cwprojecthublink').value,
teaser: document.getElementById('teaser').value,
}
await createProject(values)
})
}
//
// DELETE PROJECT LINKS
//
const deleteProjectLinks = document.querySelectorAll('.delete-project')
if (deleteProjectLinks) {
deleteProjectLinks.forEach((link) => {
link.addEventListener('click', async (event) => {
event.preventDefault()
await deleteProject(event.path[1].getAttribute('route'), location.href)
})
})
}
//
// EDIT PROJECT BUTTONS
//
const editProjectLinks = document.querySelectorAll('.edit-project')
if (editProjectLinks) {
editProjectLinks.forEach((link) => {
link.addEventListener('click', async (event) => {
event.preventDefault()
location.assign(event.target.parentNode.getAttribute('route'))
})
})
}
//
// EDIT PROJECT FORM
//
const editProjectForm = document.getElementById('edit-project-form')
if (editProjectForm) {
editProjectForm.addEventListener('submit', async (event) => {
event.preventDefault()
const values = {
id: document.getElementById('projectid').value,
cw_id: document.getElementById('project_cwid').value,
acronym: document.getElementById('acronym').value,
rcn: document.getElementById('rcn').value,
title: document.getElementById('title').value,
startDate: document.getElementById('startdate').value,
endDate: document.getElementById('enddate').value,
call: document.getElementById('fundingcall').value,
type: document.getElementById('projecttype').value,
totalCost: document.getElementById('totalCost').value,
url: document.getElementById('url').value,
fundingBodyLink: document.getElementById('fundingbodylink').value,
cwurl: document.getElementById('cwprojecthublink').value,
teaser: document.getElementById('teaser').value,
}
await updateProject(values)
})
}
//
// Upload a file and import the projects
//
const uploadImportForm = document.getElementById('import-projects-form')
if (uploadImportForm) {
uploadImportForm.addEventListener('submit', async (event) => {
event.preventDefault()
const form = new FormData()
form.append('importfile', document.getElementById('importfile').files[0])
importProjects(form)
})
}
//
// Add a category to a project
//
const addCategoryForm = document.getElementById('add-category-form')
if (addCategoryForm) {
addCategoryForm.addEventListener('submit', async (event) => {
event.preventDefault()
const cw_id = document.getElementById('cwid').value
const classification = document.getElementById('classification').value
const classifiedBy = 'Cyberwatching' // for now this is hardcoded when using the web UI
const changeSummary = document.getElementById('changeSummary').value
addClassification(cw_id, classification, classifiedBy, changeSummary)
})
}
//
// Add a MTRL score to a project
//
const addScoreForm = document.getElementById('add-score-form')
if (addScoreForm) {
addScoreForm.addEventListener('submit', async (event) => {
event.preventDefault()
const cw_id = document.getElementById('cwid').value
const mrl = document.getElementById('mrl').value
const trl = document.getElementById('trl').value
const scoringDate = document.getElementById('scoringdate').value
const description = document.getElementById('scoreDescription').value
addScore(cw_id, mrl, trl, scoringDate, description)
})
}
//
// Taxonomy tag checkboxes
//
// when selecting a dimension header, unselect al the dimension's terms
const dimensionHeaders = document.querySelectorAll('.dimension-header')
if (dimensionHeaders) {
dimensionHeaders.forEach((box) => {
box.addEventListener('click', (event) => {
const termBoxes = box.parentNode.parentNode.querySelectorAll('.term')
termBoxes.forEach((tB) => (tB.checked = false))
})
})
}
// when selecting a dimension's term, unselect the dimension header
const dimensionTerms = document.querySelectorAll('.term')
if (dimensionTerms) {
dimensionTerms.forEach((termBox) => {
termBox.addEventListener('click', (event) => {
const parentBox = termBox.parentNode.parentNode.parentNode.parentNode.querySelector(
'.dimension-header'
)
parentBox.checked = false
})
})
}
//
// Taxonomy tags submit
//
const taxonomySubmit = document.getElementById('edit-tags-form')
if (taxonomySubmit) {
taxonomySubmit.addEventListener('submit', async (event) => {
event.preventDefault()
const values = {
cw_id: document.getElementById('project_cwid').value,
tags: [],
}
document.querySelectorAll('.term:checked,.dimension-header:checked').forEach((c) => {
values.tags.push(c.value)
})
await updateProject(values)
})
}
//
// Radar description expander
//
const rdExpander = document.querySelector('#overview #summary-flicker')
if (rdExpander) {
rdExpander.addEventListener('click', (event) => {
event.target.classList.toggle('open')
event.target.parentNode.parentNode.classList.toggle('open')
})
}
// show alerts sent by the server
const alertMsg = document.querySelector('body').dataset.alertmsg
const alertType = document.querySelector('body').dataset.alerttype
if (alertMsg && alertType) showAlert(alertType, alertMsg, 2000)
|
import clsx from 'clsx';
import React from 'react';
import { Link as GatsbyLink } from 'gatsby';
import Box from '@material-ui/core/Box';
import MuiLink from '@material-ui/core/Link';
import Typography from '@material-ui/core/Typography';
import { makeStyles, withStyles } from '@material-ui/core/styles';
//------------------------------------------------------------------------------
export const PageTitle = withStyles((theme) => ({
title: {
fontSize: theme.typography.pxToRem(28),
marginBottom: theme.spacing(2),
[theme.breakpoints.down('sm')]: {
display: 'none',
},
}
}))((props) => {
return (
<Typography
component="h1"
className={clsx(props.classes.title, props.className)}
>
{props.children}
</Typography>
);
});
//------------------------------------------------------------------------------
const contentHeadingStyles = makeStyles((theme) => ({
typography: {
marginBottom: theme.spacing(1),
// '&::before': {
// content: '" "',
// display: 'block',
// height: theme.spacing(2),
// marginTop: -theme.spacing(2),
// pointerEvents: 'none',
// visibility: 'hidden',
//
// [theme.breakpoints.up('md')]: {
// height: theme.appbar.height + theme.spacing(2),
// marginTop: -(theme.appbar.height + theme.spacing(2)),
// },
// },
},
underline: {
borderBottom: `1px solid #424242`,
paddingBottom: theme.spacing(0.5),
},
// h1: { fontSize: theme.typography.pxToRem(24) },
// h2: { fontSize: theme.typography.pxToRem(20) },
// h3: { fontSize: theme.typography.pxToRem(18) },
// h4: { fontSize: theme.typography.pxToRem(16) },
}));
export function ContentHeading(props) {
const classes = contentHeadingStyles();
const {
children,
underline,
variant,
...typographyProps
} = props;
const _variant = variant || 'h2';
const classNames = [classes.typography, classes[_variant]];
if (underline) {
classNames.push(classes.underline);
}
return (
<Typography
className={clsx(classNames)}
variant={_variant}
{...typographyProps}
>
{children}
</Typography>
);
}
//------------------------------------------------------------------------------
export function ContentSection(props) {
const { className, children, ...boxProps } = props;
if (!boxProps.marginBottom) {
boxProps.marginBottom = 4;
}
return (
<Box
component="section"
className={className}
{...boxProps}
>
{children}
</Box>
);
}
//------------------------------------------------------------------------------
export const Paragraph = withStyles((theme) => ({
typography: {
lineHeight: 1.7,
}
}))(({ children, classes, className, disableGutterBottom }) => {
return (
<Typography
className={clsx(classes.typography, className)}
gutterBottom={!disableGutterBottom}
>
{children}
</Typography>
);
});
//------------------------------------------------------------------------------
export function Link(props) {
const { children, ...linkProps } = props;
if (linkProps.onClick) {
linkProps.component = 'button';
} else if (linkProps.to) {
linkProps.component = GatsbyLink;
} else if (linkProps.target === '_blank') {
linkProps.rel = 'noopener';
}
return (
<MuiLink {...linkProps}>
{children}
</MuiLink>
);
}
|
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes to handle dependencies for concepts.
At runtime, resources can be parsed and initialized using the information given
in the Deps object. All the information given by the user in the command line is
available in the Deps object. It may also access other information (such as
information provided by the user during a prompt or properties that are changed
during runtime before the Deps object is used) when Get() is called for a given
attribute, depending on the fallthroughs.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import abc
from googlecloudsdk.calliope.concepts import util
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
import six
class Error(exceptions.Error):
"""Base exception type for this module."""
class FallthroughNotFoundError(Error):
"""Raised when an attribute value is not found by a Fallthrough object."""
class AttributeNotFoundError(Error, AttributeError):
"""Raised when an attribute value cannot be found by a Deps object."""
class _FallthroughBase(six.with_metaclass(abc.ABCMeta, object)):
"""Represents a way to get information about a concept's attribute.
Specific implementations of Fallthrough objects must implement the method:
_Call():
Get a value from information given to the fallthrough.
GetValue() is used by the Deps object to attempt to find the value of an
attribute. The hint property is used to provide an informative error when an
attribute can't be found.
"""
def __init__(self, hint, active=False, plural=False):
"""Initializes a fallthrough to an arbitrary function.
Args:
hint: str, The user-facing message for the fallthrough when it cannot be
resolved.
active: bool, True if the fallthrough is considered to be "actively"
specified, i.e. on the command line.
plural: bool, whether the expected result should be a list. Should be
False for everything except the "anchor" arguments in a case where a
resource argument is plural (i.e. parses to a list).
"""
self._hint = hint
self.active = active
self.plural = plural
def GetValue(self, parsed_args):
"""Gets a value from information given to the fallthrough.
Args:
parsed_args: the argparse namespace.
Raises:
FallthroughNotFoundError: If the attribute is not found.
Returns:
The value of the attribute.
"""
value = self._Call(parsed_args)
if value:
return self._Pluralize(value)
raise FallthroughNotFoundError()
@abc.abstractmethod
def _Call(self, parsed_args):
pass
def _Pluralize(self, value):
"""Pluralize the result of calling the fallthrough. May be overridden."""
if not self.plural or isinstance(value, list):
return value
return [value] if value else []
@property
def hint(self):
"""String representation of the fallthrough for user-facing messaging."""
return self._hint
def __hash__(self):
return hash(self.hint) + hash(self.active)
def __eq__(self, other):
return (isinstance(other, self.__class__)
and other.hint == self.hint
and other.active == self.active
and other.plural == self.plural)
class Fallthrough(_FallthroughBase):
"""A fallthrough that can get an attribute value from an arbitrary function.
"""
def __init__(self, function, hint, active=False, plural=False):
"""Initializes a fallthrough to an arbitrary function.
Args:
function: f() -> value, A no argument function that returns the value of
the argument or None if it cannot be resolved.
hint: str, The user-facing message for the fallthrough when it cannot be
resolved. Should start with a lower-case letter.
active: bool, True if the fallthrough is considered to be "actively"
specified, i.e. on the command line.
plural: bool, whether the expected result should be a list. Should be
False for everything except the "anchor" arguments in a case where a
resource argument is plural (i.e. parses to a list).
Raises:
ValueError: if no hint is provided
"""
if not hint:
raise ValueError('Hint must be provided.')
super(Fallthrough, self).__init__(hint, active=active, plural=plural)
self._function = function
def _Call(self, parsed_args):
del parsed_args
return self._function()
def __eq__(self, other):
return (super(Fallthrough, self).__eq__(other)
and other._function == self._function) # pylint: disable=protected-access
class PropertyFallthrough(_FallthroughBase):
"""Gets an attribute from a property."""
def __init__(self, prop, plural=False):
"""Initializes a fallthrough for the property associated with the attribute.
Args:
prop: googlecloudsdk.core.properties._Property, a property.
plural: bool, whether the expected result should be a list. Should be
False for everything except the "anchor" arguments in a case where a
resource argument is plural (i.e. parses to a list).
"""
hint = 'set the property [{}]'.format(prop)
super(PropertyFallthrough, self).__init__(hint, plural=plural)
self.property = prop
def _Call(self, parsed_args):
del parsed_args # Not used.
try:
return self.property.GetOrFail()
except (properties.InvalidValueError, properties.RequiredPropertyError):
return None
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return other.property == self.property
def __hash__(self):
return hash(self.property)
class ArgFallthrough(_FallthroughBase):
"""Gets an attribute from the argparse parsed values for that arg."""
def __init__(self, arg_name, plural=False):
"""Initializes a fallthrough for the argument associated with the attribute.
Args:
arg_name: str, the name of the flag or positional.
plural: bool, whether the expected result should be a list. Should be
False for everything except the "anchor" arguments in a case where a
resource argument is plural (i.e. parses to a list).
"""
super(ArgFallthrough, self).__init__(
'provide the argument [{}] on the command line'.format(arg_name),
active=True, plural=plural)
self.arg_name = arg_name
def _Call(self, parsed_args):
arg_value = getattr(parsed_args, util.NamespaceFormat(self.arg_name),
None)
return arg_value
def _Pluralize(self, value):
if not self.plural:
# Positional arguments will always be stored in argparse as lists, even if
# nargs=1. If not supposed to be plural, transform into a single value.
if isinstance(value, list):
return value[0] if value else None
return value
if value and not isinstance(value, list):
return [value]
return value if value else []
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return other.arg_name == self.arg_name
def __hash__(self):
return hash(self.arg_name)
class FullySpecifiedAnchorFallthrough(_FallthroughBase):
"""A fallthrough that gets a parameter from the value of the anchor."""
def __init__(self, fallthrough, collection_info, parameter_name,
plural=False):
"""Initializes a fallthrough getting a parameter from the anchor.
For anchor arguments which can be plural, returns the list.
Args:
fallthrough: _FallthroughBase, any fallthrough for an anchor arg.
collection_info: the info of the collection to parse the anchor as.
parameter_name: str, the name of the parameter
plural: bool, whether the expected result should be a list. Should be
False for everything except the "anchor" arguments in a case where a
resource argument is plural (i.e. parses to a list).
"""
hint = fallthrough.hint + (' with a fully specified name')
super(FullySpecifiedAnchorFallthrough, self).__init__(
hint, active=fallthrough.active, plural=plural)
self.fallthrough = fallthrough
self.parameter_name = parameter_name
self.collection_info = collection_info
self._resources = resources.REGISTRY.Clone()
self._resources.RegisterApiByName(self.collection_info.api_name,
self.collection_info.api_version)
def _GetFromAnchor(self, anchor_value):
try:
resource_ref = self._resources.Parse(
anchor_value,
collection=self.collection_info.full_name)
except resources.Error:
return None
# This should only be called for final parsing when the anchor attribute
# has been split up into non-plural fallthroughs; thus, if an AttributeError
# results from the parser being passed a list, skip it for now.
except AttributeError:
return None
return getattr(resource_ref, self.parameter_name, None)
def _Call(self, parsed_args):
try:
anchor_value = self.fallthrough.GetValue(parsed_args)
except FallthroughNotFoundError:
return None
return self._GetFromAnchor(anchor_value)
def __eq__(self, other):
return (isinstance(other, self.__class__)
and other.fallthrough == self.fallthrough
and other.collection_info == self.collection_info
and other.parameter_name == self.parameter_name)
def __hash__(self):
return sum(map(hash, [self.fallthrough, str(self.collection_info),
self.parameter_name]))
def Get(attribute_name, attribute_to_fallthroughs_map, parsed_args=None):
"""Gets the value of an attribute based on fallthrough information.
If the attribute value is not provided by any of the fallthroughs, an
error is raised with a list of ways to provide information about the
attribute.
Args:
attribute_name: str, the name of the attribute.
attribute_to_fallthroughs_map: {str: [_FallthroughBase], a map of attribute
names to lists of fallthroughs.
parsed_args: a parsed argparse namespace.
Returns:
the value of the attribute.
Raises:
AttributeNotFoundError: if no value can be found.
"""
fallthroughs = attribute_to_fallthroughs_map.get(attribute_name, [])
return GetFromFallthroughs(fallthroughs, parsed_args,
attribute_name=attribute_name)
def GetFromFallthroughs(fallthroughs, parsed_args, attribute_name=None):
"""Gets the value of an attribute based on fallthrough information.
If the attribute value is not provided by any of the fallthroughs, an
error is raised with a list of ways to provide information about the
attribute.
Args:
fallthroughs: [_FallthroughBase], list of fallthroughs.
parsed_args: a parsed argparse namespace.
attribute_name: str, the name of the attribute. Used for error message,
omitted if not provided.
Returns:
the value of the attribute.
Raises:
AttributeNotFoundError: if no value can be found.
"""
for fallthrough in fallthroughs:
try:
return fallthrough.GetValue(parsed_args)
except FallthroughNotFoundError:
continue
fallthroughs_summary = '\n'.join(
['- {}'.format(f.hint) for f in fallthroughs])
raise AttributeNotFoundError(
'Failed to find attribute{}. The attribute can be set in the '
'following ways: \n{}'.format(
'' if attribute_name is None else ' [{}]'.format(attribute_name),
fallthroughs_summary))
|
;;;-*- Mode: Lisp; Package: CCL -*-
;;;
;;; Copyright 1994-2009 Clozure Associates
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(in-package "CCL")
(eval-when (:compile-toplevel)
(require "NUMBER-MACROS"))
(defun coerce-to-complex-type (num type)
(cond ((complexp num)
(let ((real (%realpart num))
(imag (%imagpart num)))
(if (and (typep real type)
(typep imag type))
num
(complex (coerce real type)
(coerce imag type)))))
(t (complex (coerce num type)))))
;;; end of l0-complex.lisp
|
import Model from './Model';
class Direccion extends Model{
static url(){
return 'direccion';
}
constructor(){
super();
this.calle = '';
this.altura = '';
this.piso = '';
this.dpto = '';
this.localidad_id = '';
}
static model(){
return 'Comensal'
}
}
export default Direccion; |
// --- Directions
// Given a string, return true if the string is a palindrome
// or false if it is not. Palindromes are strings that
// form the same word if it is reversed. *Do* includes spaces
// and punctuations in determinig if the string is a palindromw.
// --- Examples:
// palindrome("abba") == true
// palindrome("abcdefg") == false
#include <bits/stdc++.h>
using namespace std;
bool palindrome(string str);
|
#!/usr/bin/env bash
set -e
set -u
set -o pipefail
############################################################
# Functions
############################################################
###
### Change UID
###
fix_perm() {
local uid_varname="${1}"
local gid_varname="${2}"
local directory="${3}"
local recursive="${4}"
local debug="${5}"
local perm=
# Get uid
if env_set "${uid_varname}"; then
perm="$( env_get "${uid_varname}" )"
fi
# Get gid
if env_set "${gid_varname}"; then
perm="${perm}:$( env_get "${gid_varname}" )"
fi
if [ -n "${perm}" ]; then
if [ "${recursive}" = "1" ]; then
run "chown -R ${perm} ${directory}" "${debug}"
else
run "chown ${perm} ${directory}" "${debug}"
fi
fi
}
|
# SagaSplash
[](https://github.com/facebook/jest)
An unsplash image gallery built with redux saga

# Starter
After cloning, checkout the `starter` branch
```bash
git checkout starter
```
|
class MoveCodeToPromotionCode < ActiveRecord::Migration
def change
Spree::Promotion.find_each do |promotion|
next if promotion.code.nil?
promotion.codes.create!(code: promotion.code)
end
end
end
|
package icfp2019.analyzers
import icfp2019.loadProblem
import icfp2019.model.GameState
import icfp2019.model.RobotId
import icfp2019.parseDesc
import kMetis
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
internal class KMetisTest {
@Test
fun kMetis() {
val problemInput = loadProblem(3)
val desc = parseDesc(problemInput, "Test")
val gameState = GameState(desc)
val boardCells = BoardCellsGraphAnalyzer.analyze(gameState)(RobotId.first, gameState)
val split = kMetis(boardCells, setOf(), 4)
split.forEachIndexed { idx, x ->
println("$idx: $x")
}
println(split)
}
}
|
use std::io;
use bitflags::bitflags;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use failure::Fail;
use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::{FromPrimitive, ToPrimitive};
use crate::{gcc, impl_from_error, PduParsing};
const SYNCHRONIZE_PDU_SIZE: usize = 2 + 2;
const CONTROL_PDU_SIZE: usize = 2 + 2 + 4;
const FONT_PDU_SIZE: usize = 2 * 4;
const SYNCHRONIZE_MESSAGE_TYPE: u16 = 1;
const MAX_MONITOR_COUNT: u32 = 64;
#[derive(Debug, Clone, PartialEq)]
pub struct SynchronizePdu {
pub target_user_id: u16,
}
impl PduParsing for SynchronizePdu {
type Error = FinalizationMessagesError;
fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> {
let message_type = stream.read_u16::<LittleEndian>()?;
if message_type != SYNCHRONIZE_MESSAGE_TYPE {
return Err(FinalizationMessagesError::InvalidMessageType);
}
let target_user_id = stream.read_u16::<LittleEndian>()?;
Ok(Self { target_user_id })
}
fn to_buffer(&self, mut stream: impl io::Write) -> Result<(), Self::Error> {
stream.write_u16::<LittleEndian>(SYNCHRONIZE_MESSAGE_TYPE)?;
stream.write_u16::<LittleEndian>(self.target_user_id)?;
Ok(())
}
fn buffer_length(&self) -> usize {
SYNCHRONIZE_PDU_SIZE
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ControlPdu {
pub action: ControlAction,
pub grant_id: u16,
pub control_id: u32,
}
impl PduParsing for ControlPdu {
type Error = FinalizationMessagesError;
fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> {
let action = ControlAction::from_u16(stream.read_u16::<LittleEndian>()?)
.ok_or(FinalizationMessagesError::InvalidControlAction)?;
let grant_id = stream.read_u16::<LittleEndian>()?;
let control_id = stream.read_u32::<LittleEndian>()?;
Ok(Self {
action,
grant_id,
control_id,
})
}
fn to_buffer(&self, mut stream: impl io::Write) -> Result<(), Self::Error> {
stream.write_u16::<LittleEndian>(self.action.to_u16().unwrap())?;
stream.write_u16::<LittleEndian>(self.grant_id)?;
stream.write_u32::<LittleEndian>(self.control_id)?;
Ok(())
}
fn buffer_length(&self) -> usize {
CONTROL_PDU_SIZE
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FontPdu {
pub number: u16,
pub total_number: u16,
pub flags: SequenceFlags,
pub entry_size: u16,
}
impl PduParsing for FontPdu {
type Error = FinalizationMessagesError;
fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> {
let number = stream.read_u16::<LittleEndian>()?;
let total_number = stream.read_u16::<LittleEndian>()?;
let flags = SequenceFlags::from_bits(stream.read_u16::<LittleEndian>()?)
.ok_or(FinalizationMessagesError::InvalidListFlags)?;
let entry_size = stream.read_u16::<LittleEndian>()?;
Ok(Self {
number,
total_number,
flags,
entry_size,
})
}
fn to_buffer(&self, mut stream: impl io::Write) -> Result<(), Self::Error> {
stream.write_u16::<LittleEndian>(self.number)?;
stream.write_u16::<LittleEndian>(self.total_number)?;
stream.write_u16::<LittleEndian>(self.flags.bits())?;
stream.write_u16::<LittleEndian>(self.entry_size)?;
Ok(())
}
fn buffer_length(&self) -> usize {
FONT_PDU_SIZE
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MonitorLayoutPdu {
pub monitors: Vec<gcc::Monitor>,
}
impl PduParsing for MonitorLayoutPdu {
type Error = FinalizationMessagesError;
fn from_buffer(mut stream: impl io::Read) -> Result<Self, Self::Error> {
let monitor_count = stream.read_u32::<LittleEndian>()?;
if monitor_count > MAX_MONITOR_COUNT {
return Err(FinalizationMessagesError::InvalidMonitorCount(
monitor_count,
));
}
let mut monitors = Vec::with_capacity(monitor_count as usize);
for _ in 0..monitor_count {
monitors.push(gcc::Monitor::from_buffer(&mut stream)?);
}
Ok(Self { monitors })
}
fn to_buffer(&self, mut stream: impl io::Write) -> Result<(), Self::Error> {
stream.write_u32::<LittleEndian>(self.monitors.len() as u32)?;
for monitor in self.monitors.iter() {
monitor.to_buffer(&mut stream)?;
}
Ok(())
}
fn buffer_length(&self) -> usize {
gcc::MONITOR_COUNT_SIZE + self.monitors.len() * gcc::MONITOR_SIZE
}
}
#[repr(u16)]
#[derive(Debug, Clone, PartialEq, FromPrimitive, ToPrimitive)]
pub enum ControlAction {
RequestControl = 1,
GrantedControl = 2,
Detach = 3,
Cooperate = 4,
}
bitflags! {
pub struct SequenceFlags: u16 {
const FIRST = 1;
const LAST = 2;
}
}
#[derive(Debug, Fail)]
pub enum FinalizationMessagesError {
#[fail(display = "IO error: {}", _0)]
IOError(#[fail(cause)] io::Error),
#[fail(display = "Monitor Data error: {}", _0)]
MonitorDataError(#[fail(cause)] gcc::MonitorDataError),
#[fail(display = "Invalid message type field in Synchronize PDU")]
InvalidMessageType,
#[fail(display = "Invalid control action field in Control PDU")]
InvalidControlAction,
#[fail(display = "Invalid grant id field in Control PDU")]
InvalidGrantId,
#[fail(display = "Invalid control id field in Control PDU")]
InvalidControlId,
#[fail(display = "Invalid list flags field in Font List PDU")]
InvalidListFlags,
#[fail(display = "Invalid monitor count field: {}", _0)]
InvalidMonitorCount(u32),
}
impl_from_error!(
io::Error,
FinalizationMessagesError,
FinalizationMessagesError::IOError
);
impl_from_error!(
gcc::MonitorDataError,
FinalizationMessagesError,
FinalizationMessagesError::MonitorDataError
);
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class MainMenu : MonoBehaviour
{
public GameObject optionScreen;
public string firstlevel;
// Start is called before the first frame update
public GameObject loadingScreen, loadingIcon; //Loading screen
public Text loadingText; //Loading screen
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void StartGame(){
//SceneManager.LoadScene(firstlevel);
StartCoroutine(LoadStart());
}
public void OpenOptions(){
optionScreen.SetActive (true);
}
public void CloseOptions(){
optionScreen.SetActive(false);
}
public void QuitGame(){
Application.Quit();
}
public IEnumerator LoadStart() //this starts a coroutine
{
loadingScreen.SetActive(true);
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(firstlevel);
asyncLoad.allowSceneActivation = false;
while (!asyncLoad.isDone)
{
if (asyncLoad.progress >= .9f)
{
loadingText.text = "Press any key to continue";
loadingIcon.SetActive(false);
if (Input.anyKeyDown)
{
asyncLoad.allowSceneActivation = true;
Time.timeScale = 1f;
}
}
yield return null;
}
}
}
|
<?php
/**
* This file is part of the Krystal Framework
*
* Copyright (c) No Global State Lab
*
* For the full copyright and license information, please view
* the license file that was distributed with this source code.
*/
namespace Krystal\Captcha\Standard\Text;
abstract class AbstractGenerator
{
/**
* Target answer
*
* @var string
*/
protected $answer;
/**
* Returns an answer
*
* @return string
*/
final public function getAnswer()
{
return $this->answer;
}
/**
* Defines a answer
*
* @param string $answer
* @return void
*/
final public function setAnswer($answer)
{
$this->answer = $answer;
}
/**
* Generates a random string and saves it as an answer into the memory
*
* @return string
*/
abstract public function generate();
}
|
<?php
namespace App\Http\Livewire\Admin;
use App\Models\AttributeGroup;
use Livewire\Component;
class AddAttributeGroupComponent extends Component
{
public $name;
public $sort_order = 1;
public function addAttributeGroup()
{
$this->validate([
'name' => 'required',
]);
$attributeGroup = new AttributeGroup();
$attributeGroup->name = $this->name;
$attributeGroup->sort_order = $this->sort_order;
$attributeGroup->save();
session()->flash('success', 'Attribute Group has been created successfully');
return redirect()->to('/admin/attribute-groups');
}
public function render()
{
return view('livewire.admin.add-attribute-group-component')->layout('layouts.admin');
}
}
|
# PokemonClass
Using a Pokemon team to review Ch4-6 in EE422C
#MainPokemon, Pokemon, and Trainer Java Classes cover:
- Syntax
- Inheritance
- Getters
- Setters
- Extension
- Super
- Equals/Comparing Functions for Classes
- Typecasting
- instanceOf
- Polymorphism
- Casting References
- Interfaces
|
var gulp = require('gulp'),
gutil = require('gulp-util'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat');
var del = require('del');
var minifyHTML = require('gulp-minify-html');
var minifyCSS = require('gulp-minify-css');
var karma = require('gulp-karma');
gulp.task('minify', function () {
gulp.src('javascripts/temperature.js')
.pipe(uglify())
.pipe(gulp.dest('minified'));
gulp.src('./index.html')
.pipe(minifyHTML())
.pipe(gulp.dest('./minified/'))
gulp.src('./*.css')
.pipe(minifyCSS({keepBreaks:true}))
.pipe(gulp.dest('./minified/'))
});
gulp.task('clean', function(cb) {
del(['minified/*'], cb);
});
gulp.task('test', function() {
// Be sure to return the stream
return gulp.src([])
.pipe(karma({
configFile: 'conf.js',
action: 'run'
}))
.on('error', function(err) {
// Make sure failed tests cause gulp to exit non-zero
throw err;
});
});
gulp.task('default', function() {
gulp.src([])
.pipe(karma({
configFile: 'conf.js',
action: 'watch'
}));
}); |
# frozen_string_literal: true
require 'vvm/state/base'
require 'vvm/state/empty_balance'
require 'vvm/state/positive_balance'
require 'vvm/state/sold_out'
module Vvm
module State
end
end
|
/*
* Copyright (c) 2017 - 2021 CiBO Technologies - All Rights Reserved
* You may use, distribute, and modify this code under the
* terms of the BSD 3-Clause license.
*
* A copy of the license can be found on the root of this repository,
* at https://github.com/cibotech/ScalaStan/blob/master/LICENSE,
* or at https://opensource.org/licenses/BSD-3-Clause
*/
package com.cibo.scalastan
import java.io.{PrintStream, PrintWriter}
import scala.language.implicitConversions
import com.cibo.scalastan.ast._
import com.cibo.scalastan.run.StanCompiler
import com.cibo.scalastan.transform.StanTransform
import scala.collection.mutable.ArrayBuffer
trait StanModel extends StanCodeBlock with StanContext { self =>
type ParameterDeclaration[T <: StanType] = StanParameterDeclaration[T]
type DataDeclaration[T <: StanType] = StanDataDeclaration[T]
// Maximum number of models to cache.
val maxCacheSize: Int = 100
// Generated quantities aren't referenced from the model, so we need some way to cause them
// to be generated. To deal with this, generated quantities are created inside the model
// so that we can track them and generate them when the model is generated.
private val generatedQuantities: ArrayBuffer[GeneratedQuantity[_]] = new ArrayBuffer[GeneratedQuantity[_]]()
// Code loaded from a file or string.
private var rawCode: Option[String] = None
def data[T <: StanType](typeConstructor: T)(implicit name: sourcecode.Name): StanDataDeclaration[T] = {
StanDataDeclaration[T](typeConstructor, fixName(name.value))
}
def parameter[T <: StanType](
typeConstructor: T
)(
implicit ev: T#ELEMENT_TYPE =:= StanReal,
name: sourcecode.Name
): StanParameterDeclaration[T] = {
StanParameterDeclaration[T](typeConstructor, fixName(name.value))
}
def int(
lower: StanValue[StanInt] = StanUnknownInt,
upper: StanValue[StanInt] = StanUnknownInt
): StanInt = StanInt(StanUnknown.boundOpt(lower), StanUnknown.boundOpt(upper))
def categorical(): StanCategorical = StanCategorical()
def real(
lower: StanValue[StanReal] = StanUnknownReal,
upper: StanValue[StanReal] = StanUnknownReal
): StanReal = StanReal(StanUnknown.boundOpt(lower), StanUnknown.boundOpt(upper))
def vector(
dim: StanValue[StanInt] = StanUnknownInt,
lower: StanValue[StanReal] = StanUnknownReal,
upper: StanValue[StanReal] = StanUnknownReal
): StanVector = StanVector(dim, StanUnknown.boundOpt(lower), StanUnknown.boundOpt(upper))
def simplex(dim: StanValue[StanInt]): StanVector =
StanVector(dim, constraint = VectorConstraint.Simplex)
def unitVector(dim: StanValue[StanInt]): StanVector =
StanVector(dim, constraint = VectorConstraint.UnitVector)
def ordered(dim: StanValue[StanInt]): StanVector =
StanVector(dim, constraint = VectorConstraint.Ordered)
def positiveOrdered(dim: StanValue[StanInt]): StanVector =
StanVector(dim, constraint = VectorConstraint.PositiveOrdered)
def rowVector(
dim: StanValue[StanInt],
lower: StanValue[StanReal] = StanUnknownReal,
upper: StanValue[StanReal] = StanUnknownReal
): StanRowVector = StanRowVector(dim, StanUnknown.boundOpt(lower), StanUnknown.boundOpt(upper))
def matrix(
rows: StanValue[StanInt],
cols: StanValue[StanInt],
lower: StanValue[StanReal] = StanUnknownReal,
upper: StanValue[StanReal] = StanUnknownReal
): StanMatrix = StanMatrix(rows, cols, StanUnknown.boundOpt(lower), StanUnknown.boundOpt(upper))
def corrMatrix(
dim: StanValue[StanInt]
): StanMatrix = StanMatrix(dim, dim, constraint = MatrixConstraint.CorrMatrix)
def choleskyFactorCorr(
dim: StanValue[StanInt]
): StanMatrix = StanMatrix(dim, dim, constraint = MatrixConstraint.CholeskyFactorCorr)
def covMatrix(
dim: StanValue[StanInt]
): StanMatrix = StanMatrix(dim, dim, constraint = MatrixConstraint.CovMatrix)
def choleskyFactorCov(
dim: StanValue[StanInt]
): StanMatrix = StanMatrix(dim, dim, constraint = MatrixConstraint.CholeskyFactorCov)
def choleskyFactorCov(
rows: StanValue[StanInt],
cols: StanValue[StanInt]
): StanMatrix = StanMatrix(rows, cols, constraint = MatrixConstraint.CholeskyFactorCov)
abstract class Function[RETURN_TYPE <: StanType](
returnType: RETURN_TYPE = StanVoid()
)(
implicit sourceName: sourcecode.Enclosing
) extends StanTransformBase[RETURN_TYPE, StanLocalDeclaration[RETURN_TYPE]] with StanFunction {
implicit val _context: StanContext = self._context
val name: String = fixEnclosingName(sourceName.value)
lazy val result: StanLocalDeclaration[RETURN_TYPE] =
StanLocalDeclaration[RETURN_TYPE](returnType, name, owner = Some(this))
private val inputs = new ArrayBuffer[StanLocalDeclaration[_ <: StanType]]()
def input[T <: StanType](typeConstructor: T)(implicit name: sourcecode.Name): StanLocalDeclaration[T] = {
val decl = StanLocalDeclaration[T](typeConstructor, fixName(name.value))
inputs += decl
decl
}
def output(value: StanValue[RETURN_TYPE]): Unit = {
_code.append(StanReturnStatement(value))
}
def apply(args: StanValue[_ <: StanType]*)(implicit code: StanProgramBuilder): StanCall[RETURN_TYPE] = {
val node = StanCall[RETURN_TYPE](returnType, this, args)
if (returnType == StanVoid()) {
code.append(StanValueStatement(node))
}
node
}
def export(builder: StanProgramBuilder): Unit = builder.append(this)
private[scalastan] lazy val generate: StanFunctionDeclaration = StanFunctionDeclaration(
result,
inputs,
_code.results
)
}
abstract class TransformedData[T <: StanType](typeConstructor: T)(
implicit sourceName: sourcecode.Enclosing
) extends StanTransformBase[T, StanLocalDeclaration[T]] {
implicit val _context: StanContext = self._context
val name: String = fixEnclosingName(sourceName.value)
protected implicit val _rngAvailable: RngAvailable = RngAvailable
lazy val result: StanLocalDeclaration[T] = StanLocalDeclaration[T](
typeConstructor, name, derivedFromData = true, owner = Some(this)
)
def export(builder: StanProgramBuilder): Unit = builder.append(this)
private[scalastan] lazy val generate: StanTransformedData = StanTransformedData(result, _code.results)
}
abstract class TransformedParameter[T <: StanType](
typeConstructor: T
)(
implicit sourceName: sourcecode.Enclosing
) extends StanTransformBase[T, StanParameterDeclaration[T]] {
implicit val _context: StanContext = self._context
val name: String = fixEnclosingName(sourceName.value)
lazy val result: StanParameterDeclaration[T] =
StanParameterDeclaration[T](typeConstructor, name, owner = Some(this))
protected implicit val _parameterTransform: InParameterTransform = InParameterTransform
def export(builder: StanProgramBuilder): Unit = builder.append(this)
private[scalastan] lazy val generate: StanTransformedParameter = StanTransformedParameter(result, _code.results)
}
abstract class GeneratedQuantity[T <: StanType](
typeConstructor: T
)(
implicit sourceName: sourcecode.Enclosing
) extends StanTransformBase[T, StanParameterDeclaration[T]] {
implicit val _context: StanContext = self._context
val name: String = fixEnclosingName(sourceName.value)
lazy val result: StanParameterDeclaration[T] = {
if (!generatedQuantities.exists(_.name == name)) {
generatedQuantities += this
}
StanParameterDeclaration[T](typeConstructor, name, owner = Some(this))
}
StanParameterDeclaration[T](typeConstructor, name, owner = Some(this))
protected implicit val _rngAvailable: RngAvailable = RngAvailable
def export(builder: StanProgramBuilder): Unit = builder.append(this)
private[scalastan] lazy val generate: StanGeneratedQuantity = StanGeneratedQuantity(result, _code.results)
}
// Log probability function.
final protected def target: StanTargetValue = StanTargetValue()
def emit(writer: PrintWriter): Unit = rawCode match {
case Some(code) => writer.println(code)
case None => TransformedModel(this).emit(writer)
}
def program: StanProgram = {
generatedQuantities.foreach(_code.append)
_code.program
}
final def emit(ps: PrintStream): Unit = {
val pw = new PrintWriter(ps)
emit(pw)
pw.flush()
}
def transform(t: StanTransform[_]): TransformedModel = TransformedModel(this).transform(t)
def compile(implicit compiler: StanCompiler): CompiledModel = TransformedModel(this).compile(compiler)
/** Create a model from Stan code. */
def loadFromString(code: String): Unit = {
require(rawCode.isEmpty, "Code loaded multiple times")
rawCode = Some(code)
}
/** Create a model from a Stan file. */
def loadFromFile(path: String): Unit = loadFromString(scala.io.Source.fromFile(path).getLines.mkString("\n"))
implicit def dataTransform2Value[T <: StanType](
transform: StanModel#TransformedData[T]
): StanLocalDeclaration[T] = transform.result
implicit def paramTransform2Value[T <: StanType](
transform: StanModel#TransformedParameter[T]
): StanParameterDeclaration[T] = transform.result
implicit def generatedQuantity2Value[T <: StanType](
quantity: StanModel#GeneratedQuantity[T]
): StanParameterDeclaration[T] = quantity.result
}
object StanModel {
implicit def compile(model: StanModel)(implicit compiler: StanCompiler): CompiledModel = model.compile(compiler)
}
|
## 注意:我们暂时不再维护此项目,请前往[此处](https://github.com/yahb/scraino-gui)查看Scraino的最新内容.
# scraino-gui
The development is based on the foundation of [scratch-gui](https://github.com/LLK/scratch-gui)
## Installation
This requires you to have Git and Node.js installed.
In your own node environment/application:
```bash
npm install https://github.com/scraino/scraino-gui.git
```
If you want to edit/play yourself:
```bash
git clone https://github.com/scraino/scraino-gui.git
cd scraino-gui
npm install
```
## Getting started
Running the project requires Node.js to be installed.
## Running
Open a Command Prompt or Terminal in the repository and run:
```bash
npm start
```
Then go to [http://localhost:8601/](http://localhost:8601/) - the playground outputs the default GUI component
|
import { useState, useEffect } from 'react';
export default function usePublicationIsTrackEnabled(publication) {
const [isEnabled, setIsEnabled] = useState(publication ? publication.isTrackEnabled : false);
useEffect(() => {
setIsEnabled(publication ? publication.isTrackEnabled : false);
if (publication) {
const setEnabled = () => setIsEnabled(true);
const setDisabled = () => setIsEnabled(false);
publication.on('trackEnabled', setEnabled);
publication.on('trackDisabled', setDisabled);
return () => {
publication.off('trackEnabled', setEnabled);
publication.off('trackDisabled', setDisabled);
};
}
}, [publication]);
return isEnabled;
}
|
import React from "react";
export type Storage = {
theme: "light" | "dark" | null;
};
function isSupported() {
return "localStorage" in globalThis;
}
export function getKey<T extends keyof Storage>(key: T): Storage[T] | null {
if (!isSupported()) {
return null;
}
const localStorage = globalThis.localStorage as any;
try {
return localStorage.getItem(key);
} catch (e) {
return null;
}
}
export function removeKey<T extends keyof Storage>(key: T): Storage[T] | null {
if (!isSupported()) {
return null;
}
const localStorage = globalThis.localStorage as any;
try {
return localStorage.removeItem(key);
} catch (e) {
return null;
}
}
export function saveKey<T extends keyof Storage>(
key: T,
value: Storage[T]
): Storage | null {
if (!isSupported()) {
return null;
}
const localStorage = globalThis.localStorage as any;
try {
localStorage.setItem(key, value);
} catch (e) {
return null;
}
return localStorage;
}
export function useLocalStorage<T extends keyof Storage>(
key: T
): [Storage[T] | null, (value: Storage[T]) => void] {
const [storedValue, setStoredValue] = React.useState(() => {
return getKey(key);
});
function setValue(value: Storage[T]) {
if (value === null) {
setStoredValue(null);
removeKey(key);
return;
}
setStoredValue(value);
saveKey(key, value);
}
return [storedValue, setValue];
}
|
---
author: Heather Luna
category: Sponsorship
date: 2018-09-21 12:30:02
layout: post
image: /static/img/blog/caktusgolf.png
title: "Are You Game? Play Mini Golf & Meet the Caktus Team"
---
<img src="/static/img/blog/caktusgolf.jpg" />
Play a free round of mini golf with the Caktus team! This is the ninth
year [Caktus Group](https://www.caktusgroup.com/?utm_source=djangoconsite&utm_medium=blog01&utm_campaign=djangocon2018)
has sponsored DjangoCon US, and this year they’re hosting a mini golf
event that’s open to all DjangoCon attendees.
Whoever shoots the lowest score will win a **$100 Amazon gift card.***
Look for the Caktus insert in your conference tote bag. On the back of
the insert is a free pass to Tiki Town Adventure Golf for **Tuesday,
October 16, at 7:00 p.m.** [RSVP for the event](https://learn.caktusgroup.com/djangocon18rsvp?utm_source=djangoconsite&utm_medium=blog01&utm_campaign=djangocon2018)
and you’ll also receive a $10 credit for Lyft, which you can use from
the conference hotel. Carpooling is strongly encouraged.
[RSVP Now to Play Mini Golf with Caktus](https://learn.caktusgroup.com/djangocon18rsvp?utm_source=djangoconsite&utm_medium=blog01&utm_campaign=djangocon2018)
Not into mini golf? You can still [find a time](https://app.hubspot.com/meetings/tscales/djangocon2018?utm_source=djangoconsite&utm_medium=blog01&utm_campaign=djangocon2018)
to chat with a Caktus team member during DjangoCon. Talk tech, learn
about Caktus job openings, and more.
## Caktus is Hiring
See openings on the [Caktus Careers page](https://www.caktusgroup.com/careers/?utm_source=djangoconsite&utm_medium=blog01&utm_campaign=djangocon2018)
and apply online. Benefits include a generous professional development
budget that employees use to attend conferences like DjangoCon, learn
new technologies, and grow as a developer. Caktus also offers 25 days
of paid time off, plus sick leave, health insurance, a retirement plan,
and all the coffee you could ask for.
## About Caktus
The [Caktus Group](https://www.caktusgroup.com/?utm_source=djangoconsite&utm_medium=blog01&utm_campaign=djangocon2018) grows sharp web apps and websites for businesses
and social good. Located in downtown Durham, North Carolina, Caktus
offers a range of web services, including custom Django app development,
discovery workshops, and best practices consulting. They build
solutions for higher education, media, entertainment, and energy,
as well as the nonprofit sector.
Follow Caktus and their work on [Facebook](https://www.facebook.com/CaktusGroup/),
[Twitter](https://twitter.com/CaktusGroup), and
[LinkedIn](https://www.linkedin.com/company/caktus-consulting-group-llc/),
or sign up for the [Caktus newsletter](https://learn.caktusgroup.com/newsletter?utm_source=djangoconsite&utm_medium=blog01&utm_campaign=djangocon2018),
which is sent out quarterly.
**Caktus employees will be playing mini golf, but won’t be eligible
for any prizes.*
|
+++
draft = false
+++
_Hmmm... slight size difference... Peruvians are short in general, but the young girls are little more than midgets._
|
# frozen_string_literal: true
require_relative "cache_entry_metadata"
module Grape
module Cache
module Backend
class Memory
# @param key[String] Cache key
# @param response[Rack::Response]
# @param metadata[Grape::Cache::Backend::CacheEntryMetadata] Expiration time
def store(key, response, metadata)
storage[key] = [response, metadata]
end
# @param key[String] Cache key
def fetch(key)
response, metadata = storage[key]
return response if response.nil?
if metadata.expired?
storage.delete(key)
return nil
end
response
end
# @param key[String] Cache key
def fetch_metadata(key)
return nil unless storage.has_key?(key)
storage[key].last
end
def flush!
storage.clear
end
private
def storage
@storage ||= {}
end
end
end
end
end
|
package com.kansus.teammaker.android.ui.games
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.annotation.StringRes
import com.kansus.teammaker.R
import com.kansus.teammaker.android.Navigator
import com.kansus.teammaker.android.core.BaseFragment
import com.kansus.teammaker.android.extension.*
import com.kansus.teammaker.core.exception.Failure
import com.kansus.teammaker.core.exception.Failure.NetworkConnection
import com.kansus.teammaker.core.exception.Failure.ServerError
import com.kansus.teammaker.domain.model.Game
import kotlinx.android.synthetic.main.fragment_games.*
import javax.inject.Inject
/**
*
*/
class GamesFragment : BaseFragment() {
@Inject
lateinit var navigator: Navigator
private lateinit var gamesAdapter: GamesAdapter
private lateinit var viewModel: GamesViewModel
override fun layoutId() = R.layout.fragment_games
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = viewModel(viewModelFactory) {
observe(games, ::showGames)
failure(failure, ::handleFailure)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initializeView()
loadGames()
fab.setOnClickListener { Log.d("AAA", "CLICKED") }
}
override fun onAttach(context: Context) {
super.onAttach(context)
}
override fun onDetach() {
super.onDetach()
}
private fun initializeView() {
gamesAdapter = GamesAdapter(listOf()) { game, navigationExtras ->
navigator.showGameDetails(activity!!, game, navigationExtras)
Log.d("AAA", "Selected game ${game.id}")
}
with(recycler_view) {
adapter = gamesAdapter
setHasFixedSize(true)
}
}
private fun loadGames() {
//emptyView.invisible()
recycler_view?.visible()
showProgress()
viewModel.getGames()
}
private fun showGames(games: List<Game>?) {
gamesAdapter.mValues = games.orEmpty()
hideProgress()
}
private fun handleFailure(failure: Failure?) {
when (failure) {
is NetworkConnection -> renderFailure(R.string.app_name)
is ServerError -> renderFailure(R.string.app_name)
}
}
private fun renderFailure(@StringRes message: Int) {
recycler_view.invisible()
//emptyView.visible()
hideProgress()
notifyWithAction(message, R.string.app_name, ::loadGames)
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Stellinator.Configuration;
using Stellinator.Interfaces;
namespace StellinatorTests
{
public class TestWorkflow : IWorkflow
{
private readonly int seq;
public TestWorkflow(int seq) => this.seq = seq;
public AstroFile[] Process(Options options, AstroFile[] files)
{
files ??= Array.Empty<AstroFile>();
foreach (var file in files)
{
file.Valid = false;
}
var newFiles = new[]
{
new AstroFile()
{
FileName = seq.ToString(),
FileExtension = "test",
Valid = true
}
};
return newFiles.Union(files).ToArray();
}
}
}
|
import { NgModule } from '@angular/core';
import { CommonModule } from "@angular/common";
import { TvInputService } from "../tv";
import { TvScreenService } from "./tv-screen.service";
import { TvInputComponent } from "./tv-input.component";
import { TvRowComponent } from "./tv-row.component";
import { TvRowItemComponent } from "./tv-row-item.component";
import { TvLaneComponent } from "./tv-lane.component";
import { TvScreenComponent } from "./tv-screen.component";
import { TvSliderComponent } from "./tv-slider.component";
import { TvSliderTitleComponent } from "./tv-slider-title.component";
import { TvMenuHeadingComponent } from "./tv-menu-heading.component";
import { TvMenuComponent } from "./tv-menu.component";
import { TvMenuItemComponent } from "./tv-menu-item.component";
import { TvScrollViewComponent } from "./tv-scroll-view.component";
import { TvMenuSwitchComponent } from "./tv-menu-switch.component";
import { TvSwitchComponent } from "./tv-switch-component";
@NgModule({
imports: [
CommonModule,
],
exports: [
TvInputComponent,
// TvRowComponent,
// TvRowItemComponent,
// TvLaneComponent,
TvScreenComponent,
// TvSliderComponent,
// TvSliderTitleComponent,
// TvMenuHeadingComponent,
// TvMenuComponent,
// TvMenuItemComponent,
// TvScrollViewComponent,
// TvMenuSwitchComponent,
// TvSwitchComponent
],
declarations: [
TvInputComponent,
// TvRowComponent,
// TvRowItemComponent,
// TvLaneComponent,
TvScreenComponent,
// TvSliderComponent,
// TvSliderTitleComponent,
// TvMenuHeadingComponent,
// TvMenuComponent,
// TvMenuItemComponent,
// TvScrollViewComponent,
// TvMenuSwitchComponent,
// TvSwitchComponent
],
providers: [
TvInputService,
TvScreenService,
],
})
export class TvComponentsModule { }
export * from "./tv-input.component";
export * from "./tv-row.component";
export * from "./tv-row-item.component";
export * from "./tv-lane.component";
export * from "./tv-screen.component";
export * from "./tv-slider.component";
export * from "./tv-slider-title.component";
export * from "./tv-menu-heading.component";
export * from "./tv-menu.component";
export * from "./tv-menu-item.component";
export * from "./tv-scroll-view.component";
export * from "./tv-screen.service";
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zeppelin.socket;
import java.util.HashMap;
import java.util.Map;
/**
* Zeppelin websocker massage template class.
*/
public class Message {
/**
* Representation of event type.
*/
public static enum OP {
GET_HOME_NOTE, // [c-s] load note for home screen
GET_NOTE, // [c-s] client load note
// @param id note id
NOTE, // [s-c] note info
// @param note serlialized Note object
PARAGRAPH, // [s-c] paragraph info
// @param paragraph serialized paragraph object
PROGRESS, // [s-c] progress update
// @param id paragraph id
// @param progress percentage progress
NEW_NOTE, // [c-s] create new notebook
DEL_NOTE, // [c-s] delete notebook
// @param id note id
CLONE_NOTE, // [c-s] clone new notebook
// @param id id of note to clone
// @param name name fpor the cloned note
IMPORT_NOTE, // [c-s] import notebook
// @param object notebook
NOTE_UPDATE,
RUN_PARAGRAPH, // [c-s] run paragraph
// @param id paragraph id
// @param paragraph paragraph content.ie. script
// @param config paragraph config
// @param params paragraph params
COMMIT_PARAGRAPH, // [c-s] commit paragraph
// @param id paragraph id
// @param title paragraph title
// @param paragraph paragraph content.ie. script
// @param config paragraph config
// @param params paragraph params
CANCEL_PARAGRAPH, // [c-s] cancel paragraph run
// @param id paragraph id
MOVE_PARAGRAPH, // [c-s] move paragraph order
// @param id paragraph id
// @param index index the paragraph want to go
INSERT_PARAGRAPH, // [c-s] create new paragraph below current paragraph
// @param target index
COMPLETION, // [c-s] ask completion candidates
// @param id
// @param buf current code
// @param cursor cursor position in code
COMPLETION_LIST, // [s-c] send back completion candidates list
// @param id
// @param completions list of string
LIST_NOTES, // [c-s] ask list of note
RELOAD_NOTES_FROM_REPO, // [c-s] reload notes from repo
NOTES_INFO, // [s-c] list of note infos
// @param notes serialized List<NoteInfo> object
PARAGRAPH_REMOVE,
PARAGRAPH_CLEAR_OUTPUT,
PING,
ANGULAR_OBJECT_UPDATE, // [s-c] add/update angular object
ANGULAR_OBJECT_REMOVE, // [s-c] add angular object del
ANGULAR_OBJECT_UPDATED // [c-s] angular object value updated
}
public OP op;
public Map<String, Object> data = new HashMap<String, Object>();
public Message(OP op) {
this.op = op;
}
public Message put(String k, Object v) {
data.put(k, v);
return this;
}
public Object get(String k) {
return data.get(k);
}
}
|
module Bobkit
module SlimBridge
def render(*args)
SlimHandler.instance.render *args
end
class SlimHandler
include Singleton
include FileHelpers
include SlimOptions
include LocationOptions
include ScopeOptions
include I18nBridge
def render(options={}, extra_options={})
if options.is_a? String
options = { partial: options }.merge(extra_options)
elsif options.respond_to? :to_partial
scope options
options = { partial: options.to_partial }.merge(extra_options)
end
partial = options.delete :partial
layout = options.delete :layout
output = options.delete :output
content = options.delete :content
context = options.empty? ? scope : options
if context.is_a? Hash or !context
context = Scope.new context
end
content ||= Slim::Template.new(partial_filename(partial), slim_options).render(context)
content = Slim::Template.new(layout_filename(layout), slim_options).render(context) { content } if layout
create_file "#{output_folder}/#{output}.html", content if output
content
end
private
def partial_filename(partial)
localized_template templates_folder, partial
end
def layout_filename(layout)
localized_template layouts_folder, layout
end
def localized_template(folder, basename)
preferred = "#{folder}/#{basename}.#{locale}.slim"
return preferred if File.exist? preferred
"#{folder}/#{basename}.slim"
end
end
end
end
|
package io.collapp.model
import ch.digitalfondue.npjt.ConstructorAnnotationRowMapper.Column
import io.collapp.common.Json
import java.util.*
class ProjectMailTicketConfig(@Column("MAIL_CONFIG_ID") val id: Int,
@Column("MAIL_CONFIG_NAME") val name: String,
@Column("MAIL_CONFIG_ENABLED") val enabled: Boolean,
@Column("MAIL_CONFIG_PROJECT_ID_FK") val projectId: Int,
@Column("MAIL_CONFIG_LAST_CHECKED") val lastChecked: Date?,
@Column("MAIL_CONFIG_CONFIG") @Transient val configJson: String,
@Column("MAIL_CONFIG_SUBJECT") val subject: String,
@Column("MAIL_CONFIG_BODY") val body: String) {
val config: ProjectMailTicketConfigData
val entries: List<ProjectMailTicket>
init {
config = Json.GSON.fromJson(configJson, ProjectMailTicketConfigData::class.java)
entries = ArrayList<ProjectMailTicket>()
}
}
|
$package_file = Pathname.new('package.json')
def current_version
JSON.parse($package_file.read)['version']
end
def current_version_split
current_version.split('.').map { |i| i.to_i }
end
def save_version(new_version)
json = JSON.parse($package_file.read)
json['version'] = new_version.join('.')
$package_file.open('w') { |f| f.write(JSON.pretty_generate(json)) }
system "git add package.json"
end
|
import 'package:injectable/injectable.dart';
import 'package:logger/logger.dart';
@module
abstract class LoggerDi {
@LazySingleton()
Logger get logger => Logger(
printer: PrettyPrinter(),
);
}
|
const validator = require('validatorjs');
const puppeteer = require('puppeteer');
const GetMetaData = async (page) => {
const meta = await page.$$('meta')
const metaElements = []
for (const [i, element] of meta.entries()) {
metaElements[i] = {
httpEquiv: await page.evaluate((el) => Promise.resolve(el.getAttribute("http-equiv")), element),
name: await page.evaluate((el) => Promise.resolve(el.getAttribute("name")), element),
property: await page.evaluate((el) => Promise.resolve(el.getAttribute("property")), element),
content: await page.evaluate((el) => Promise.resolve(el.getAttribute("content")), element)
}
}
return metaElements
}
const GetPageTtile = async (page)=>{
const element = await page.$('title')
return (await page.evaluate((el) => Promise.resolve(el.innerText), element))
}
module.exports = async (req, res) => {
let metaElements = []
let pageTitle = ''
let validation = new validator(req.query, {
url: 'required|url',
});
if (validation.fails() === true) {
return res.status(403).json(validation.errors.all())
}
console.log('Starting meta search')
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"]
})
try {
const page = await browser.newPage()
await page.setViewport({
width: 1300,
height: 700,
deviceScaleFactor: 1,
})
await page.goto(req.query.url, {
waitUntil: "domcontentloaded"
});
metaElements = await GetMetaData(page)
pageTitle = await GetPageTtile(page)
} catch (error) {
console.log(error)
return res.status(500).json('Meta search faced an internal issue. Please try again')
} finally {
browser.close()
console.log('Closing meta search')
return res.status(200).json({
message: 'Metadata succesfully searched',
pageTitle,
data: metaElements,
})
}
} |
## Copyright (c) 2014-2015 André Erdmann <[email protected]>
##
## Distributed under the terms of the MIT license.
## (See LICENSE.MIT or http://opensource.org/licenses/MIT)
##
<% if FOREIGN_INITRAMFS=0 %>
case "${INITRAMFS_LOGFILE=}" in
?*/*)
autodie mkdir -p -- "${INITRAMFS_LOGFILE%/*}"
;;
esac
<% endif %>
|
const defaultTheme = require('tailwindcss/defaultTheme');
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
safelist: [
{
pattern: /bg-(yellow|green|violet|sky|rose)-100/,
},
{
pattern: /bg-(yellow|green|violet|sky|rose)-200/,
variants: ['hover'],
},
{
pattern: /text-(yellow|green|violet|sky|rose)-500/,
},
{
pattern: /text-(yellow|green|violet|sky|rose)-700/,
variants: ['hover'],
},
{
pattern: /(w|h)-(5|6|14)/,
},
],
theme: {
extend: {
fontFamily: {
mono: ['"JetBrains Mono"', ...defaultTheme.fontFamily.mono],
},
borderWidth: {
6: '6px',
},
listStyleType: {
circle: 'circle',
'lower-roman': 'lower-roman',
},
screens: {
xl: '1024px',
'2xl': '1024px',
},
maxWidth: {
'2/5': '40%',
},
lineHeight: {
relaxed: '1.75',
inherit: 'inherit',
},
},
},
plugins: [],
};
|
namespace E_MaxSequenceOfIncreasingElements
{
using System;
using System.Linq;
public class IncreasingElements
{
public static void Main()
{
var arrayOfIntegers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
var sequenceLength = 1;
var sequenceLongitude = new int[arrayOfIntegers.Length];
sequenceLongitude[0] = 1;
for (int i = 0; i < arrayOfIntegers.Length - 1; i++)
{
if (arrayOfIntegers[i + 1] > arrayOfIntegers[i])
{
sequenceLength++;
}
else
{
sequenceLength = 1;
}
sequenceLongitude[i + 1] = sequenceLength;
}
var maxLongitude = sequenceLongitude.Max();
var sequenceStart = Array.IndexOf(sequenceLongitude, maxLongitude) - maxLongitude + 1;
for (int j = sequenceStart; j < maxLongitude + sequenceStart; j++)
{
Console.Write($"{arrayOfIntegers[j]} ");
}
Console.WriteLine();
}
}
} |
const dropZone = document.getElementById("dropZone");
dropZone.addEventListener('drop', (event) => {
event.preventDefault();
event.stopPropagation();
console.log("Dropped");
var paths = [];
for (const f of event.dataTransfer.files) {
console.log('File Path of dragged files: ', f.path);
paths.push(f.path);
}
window.sendFilePaths(paths);
});
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
});
document.querySelector('#fileBrowser').addEventListener('click', function (event) {
window.selectFile();
});
|
<div class="form-group">
{!! Form::label('currency', 'Валюта', ["class"=>"col-sm-3 control-label"]) !!}
<div class="col-sm-6">
{!! Form::text('name', '', ["class"=>"form-control",
"placeholder"=>"Название валюты",'required' => 'required' ]) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('course_purchase', 'Покупка', ["class"=>"col-sm-3 control-label"]) !!}
<div class="col-sm-6">
{!! Form::text('course_purchase', '', ["class"=>"form-control",
"placeholder"=>"Число через точку, например: 0.5",'required' => 'required']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('wallet', 'Номер счета', ["class"=>"col-sm-3 control-label"]) !!}
<div class="col-sm-6">
{!! Form::text('wallet', '', ["class"=>"form-control",
"placeholder"=>"Номер счета",'required' => 'required']) !!}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
{!! Form::button('<i class="fa fa-btn fa-save"></i> Сохранить', ['type'=>'submit',
'class' =>
'btn btn-primary']) !!}
</div>
</div> |
class Option {
constructor(value, status){
this.value = value;
this.status = status;
}
}
class CountMatrix {
constructor(data, maxWidth){
this.data = data.slice();
this.totalLength = data.length;
this.maxWidth = maxWidth;
this.rows = [];
this.start = true;
this.currentRow = null;
this.processed = this.process(data);
this.currentIdx = 0;
this.currentRowIdx = 0;
this.currentRow = this.rows[0]
}
process(){
while (this.data.length > 0){
if (this.start) {
this.start = false;
this.currentRow = new CountRow(this.maxWidth);
this.rows.push(this.currentRow);
}
let number = this.data[this.data.length - 1];
let result = this.currentRow.push(number);
if (result.status == "ERROR"){
this.currentRow = new CountRow(this.maxWidth);
this.rows.push(this.currentRow);
} else {
this.currentRow.push(number);
this.data.pop();
}
}
}
reset(){
this.currentIdx = 0;
this.currentRowIdx = 0;
this.currentRow = this.rows[0];
}
concat(){
const allCountRows = [].concat.apply(this, this.rows).slice(1);
const listOfRows = allCountRows.map(
function(x){
return x.row;
});
const allTotals = [].concat.apply(this, listOfRows).slice(1);
return allTotals;
}
}
class CountRow {
constructor(maxWidth){
this.row = [];
this.totals = [];
this.index = 0;
this.total = 0;
this.max = -1;
this.maxWidth = maxWidth;
}
push(number){
let total = this.total + number;
if (total > this.maxWidth){
return new Option("row is full", "ERROR");
} else {
this.row.push(number);
this.row.push(total);
this.max = Math.max(this.max, number);
this.total += number;
this.index += 1;
return new Option(this, "OK");
}
}
length(){
return this.row.length;
}
}
class Data {
constructor(data, n){
this.width = 1200;
this.height = 800;
this.maxNodeRadius = 300;
this.data = Data.trimData(data,n);
const extent = Data.getExtent(this.data);
this.min = extent[0];
this.max = extent[1];
this.xScale = Data.xScale(n, this.width);
this.yScale = Data.yScale(this.min, this.max, this.maxNodeRadius);
this.count = Data.collectCount(this.data);
this.words = Data.collectWords(this.data);
this.scaledCount = this.count.map(this.yScale);
const x = new CountMatrix(this.scaledCount, this.width)
x.process()
this.countMatrix = x.concat();
}
static trimData(data, n){
return data.slice(-n).map(function(d){
return {
word:d.word,
count: +d.count
}
});
}
static collectWords(data){
return data.map(function(d){
return d.word;
});
}
static collectCount(data){
return data.map(function(d){
return d.count;
});
}
// i mean scaled counts
static precalculateCount(counts, heights, maxWidth){
const countAccumulate = [];
let n = counts.length;
for(let i = 0; i < n; i++){
let current = counts[i];
if (i != 0){
current += counts[i-1];
}
countAccumulate.push(current);
}
}
static getExtent(data){
const extent = d3.extent(data, function(d){
return d.count;
});
return extent;
}
static xScale(n, width){
return d3.scaleLinear()
.domain([0,n])
.range([0,width]);
}
static yScale(min, max, maxNodeRadius){
return d3.scaleLinear()
.domain([min, max])
.range([0, maxNodeRadius]);
}
}
|
create table "trello_data"."analytics"."daily_total_cards_each_stage__dbt_tmp"
as (
with trello_boards as (
select "id" as board_id, "name" as board_name from "trello_data"."analytics"."trello_boards"
),
trello_lists as (
select id_list, id_board, "name" as stage_name from "trello_data"."analytics"."trello_lists"
) ,
trello_cards as (
select id_list, recent_cards from "trello_data"."analytics"."track_cards_snapshot"
),
final as (
select trello_boards.board_name, trello_lists.stage_name, trello_cards.recent_cards
from trello_boards, trello_lists, trello_cards
where trello_boards.board_id = trello_lists.id_board
and trello_cards.id_list = trello_lists.id_list
)
select board_name, stage_name, count(recent_cards) as num_of_cards from final
group by board_name, stage_name
); |
// @flow strict
import { spawn } from "./reflex/Application.js"
import * as Main from "./Allusion/Main.js"
if (location.protocol === "dat:") {
window.main = spawn(Main, window.main, window.document)
}
|
# frozen_string_literal: true
FactoryBot.define do
UPLOADED_PDF_PROPS = {
source: nil, doc_type: 'Unknown', total_documents: 2, total_pages: 2,
content: { page_count: 1, dimensions: { height: 8.5, width: 11.0, oversized_pdf: false },
attachments: [{ page_count: 1, dimensions: { height: 8.5, width: 11.0, oversized_pdf: false } }] }
}.freeze
factory :upload_submission, class: 'VBADocuments::UploadSubmission' do
guid { 'f7027a14-6abd-4087-b397-3d84d445f4c3' }
status { 'pending' }
consumer_id { 'f7027a14-6abd-4087-b397-3d84d445f4c3' }
consumer_name { 'adhoc' }
trait :status_received do
status { 'received' }
end
trait :version_2 do
guid { 'aa65a6a3-4193-46f5-90de-12026ffd40a1' }
metadata { { 'version': 2 } }
end
trait :status_uploaded do
guid { 'da65a6a3-4193-46f5-90de-12026ffd40a1' }
status { 'uploaded' }
updated_at { Time.now.utc }
uploaded_pdf { UPLOADED_PDF_PROPS }
end
trait :status_uploaded_11_min_ago do
guid { 'da65a6a3-4193-46f5-90de-12026ffd4011' }
status { 'uploaded' }
updated_at { 11.minutes.ago }
uploaded_pdf { UPLOADED_PDF_PROPS }
end
trait :status_error do
status { 'error' }
code { 'DOC104' }
detail { 'Upload rejected' }
end
end
factory :upload_submission_large_detail, class: 'VBADocuments::UploadSubmission', parent: :upload_submission do
detail { 'abc' * 500 }
guid { '60719ee0-44fe-40ca-9b03-755fdb8c7884' }
end
factory :upload_submission_manually_removed, class: 'VBADocuments::UploadSubmission' do
guid { 'f7027a14-6abd-4087-b397-3d84d445f4c2' }
status { 'received' }
consumer_id { 'f7027a14-6abd-4087-b397-3d84d445f4c2' }
consumer_name { 'adhoc' }
end
end
|
require File.expand_path('../../../spec_helper', __FILE__)
describe GithubBackup::Wiki do
it 'acts lie a Repository' do
GithubBackup::Wiki.new(sawyer_repo).
must_be_kind_of GithubBackup::Repository
end
describe '#clone_url' do
it 'returns the repository clone URL' do
repo = GithubBackup::Wiki.new(sawyer_repo)
repo.clone_url.must_equal 'https://github.com/ddollar/github-backup.wiki.git'
end
end
describe '#backup_path' do
it 'returns the repository backup path' do
repo = GithubBackup::Wiki.new(sawyer_repo)
repo.backup_path.must_equal 'ddollar/github-backup.wiki.git'
end
end
end
|
using System;
using GGJ2020.Managers.Scores;
using GGJ2020.Stages;
using UniRx;
using UniRx.Async;
using UnityEngine;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using UniRx.Async;
using UniRx.Async.Triggers;
using Zenject;
namespace GGJ2020.Managers
{
public class StageManager : MonoBehaviour
{
[Header("パーツセットが中央まで移動するにかかる時間")] [SerializeField]
private float partsMoveToCenterTime;
[Header("パーツセットが納品にかかる時間")] [SerializeField]
private float partsShippingTime;
[Header("パーツセットの納品完了から新しいパーツセットが出現するまでの間隔")] [SerializeField]
private int waitForNewPartsMillisecond;
[SerializeField] private ShippingButton[] _shippingButtons;
[SerializeField] private GameObject assemblyAreaPrefab;
[SerializeField] private GGJ2020.Stages.BeltConveyor _beltConveyor;
private AssemblyArea _assemblyArea;
[Inject] private StageAudioManager _audioManager;
/// <summary>
/// 出荷されたPartリストを外部に通知する
/// </summary>
public IObservable<ShippingParts> ShippingPartsAsObservable
=> _shippingPartSubject;
private Subject<ShippingParts> _shippingPartSubject = new Subject<ShippingParts>();
[Inject] private GameStateManager _gameStateManager;
void Start()
{
_shippingPartSubject.AddTo(this);
_gameStateManager.CurrentState
.FirstOrDefault(x => x == GameState.BATTLE)
.Subscribe(_ =>
CreateLoopAsync(this.GetCancellationTokenOnDestroy()).Forget());
}
private async UniTaskVoid CreateLoopAsync(CancellationToken token)
{
var shipEvent = _shippingButtons
.Select(x => x.OnPushed)
.Merge()
.Publish();
shipEvent.Connect().AddTo(this);
// 開始直後にちょっと待つ
await UniTask.Delay(1000, cancellationToken: token);
while (!token.IsCancellationRequested)
{
// 新しいAssemblyAreaを生成して配置
await CreateNewAssemblyAreaAsync();
// 出荷ボタンが押されるのをまつ
var orderName = await shipEvent.ToUniTask(useFirstValue: true,
cancellationToken: token);
// 出荷する
var shippingParts = await WaitForShippingAsync(orderName);
// 出荷したPartを通知
_shippingPartSubject.OnNext(shippingParts);
await UniTask.Delay(waitForNewPartsMillisecond, cancellationToken: token);
}
}
private async UniTask<ShippingParts> WaitForShippingAsync(OrderName orderName)
{
await _beltConveyor.MoveToShippingAsync(partsShippingTime);
var currentParts = _assemblyArea
.CurrentPartObjects
.Select(x => x.Part)
.ToArray();
_assemblyArea.DestroyAllParts();
Destroy(_assemblyArea.gameObject);
return new ShippingParts(currentParts, orderName);
}
private async UniTask CreateNewAssemblyAreaAsync()
{
var assemblyAreaObj =
Instantiate<GameObject>(
assemblyAreaPrefab,
_beltConveyor.PartsAppPoint,
Quaternion.identity);
_assemblyArea = assemblyAreaObj.GetComponent<AssemblyArea>();
_assemblyArea.Init();
_beltConveyor.SetFieldAssemblyArea(assemblyAreaObj.GetComponent<AssemblyArea>());
await _beltConveyor.MoveToCenterAsync(partsMoveToCenterTime);
}
}
} |
#!/bin/bash
if [ "${CLUSTER}" == "k3s" ]; then
source ./tests/scripts/install_k3s.sh
elif [ "${CLUSTER}" == "gke" ]; then
source ./tests/scripts/install_gke.sh
elif [ "${CLUSTER}" == "rke" ]; then
source ./tests/scripts/install_rke.sh
else
echo "Using given cluster with given kubeconfig..."
fi
# Get rio binary
curl -sfL https://get.rio.io | sh - > /dev/null 2>&1
# Install rio if it isn't already installed
if ! [ "$(rio info | grep "Cluster Domain IPs")" ] ; then rio install ; fi
if [ "${CLUSTER}" == "k3s" ]; then kubectl delete svc traefik -n kube-system ; fi
exec "$@"
|
// <copyright file="TalkScript.cs" company="bisu">
// © 2021 bisu
// </copyright>
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using Yomiage.SDK.Common;
using Yomiage.SDK.Config;
using Yomiage.SDK.VoiceEffects;
namespace Yomiage.SDK.Talk
{
/// <summary>
/// 文章の読み上げ指示情報
/// フレーズ編集情報
/// </summary>
public class TalkScript : VoiceEffectValueBase
{
/// <inheritdoc/>
[JsonIgnore]
public override string Type => "Sentence";
/// <summary>
/// ユーザーが打ち込んだ文字列そのもの
/// </summary>
public string OriginalText { get; set; }
/// <summary>
/// ボイスプリセットタグで指定がある場合に一時的に使用される。
/// </summary>
[JsonIgnore]
public string PresetName { get; set; }
/// <summary>
/// IFileConverter でローカル辞書を登録するとき登録先エンジン名を指定するために一時的に使用される。
/// </summary>
[JsonIgnore]
public string EngineName { get; set; }
/// <summary>
/// 複数のmoraとポーズからなるアクセント句のリスト。
/// </summary>
public List<Section> Sections { get; set; } = new List<Section>();
/// <summary>
/// 文末のポーズと音声効果。モーラは無いかわりに、?や!などの記号情報が入る。
/// </summary>
[JsonPropertyName("End")]
public EndSection EndSection { get; set; } = new EndSection();
/// <summary>
/// モーラのトータル数
/// </summary>
public int MoraCount
{
get => this.Sections.Select(s => s.Moras.Count).Sum();
}
/// <summary>
/// GetPhraseJsonText_toSave() で作った保存用テキストから
/// 読み上げ指示情報 を復元する。
/// </summary>
/// <param name="jsonText">jsonテキスト</param>
/// <returns>復元した情報</returns>
public static TalkScript GetTalkScript_fromPhraseJsonText(string jsonText)
{
if (jsonText.Contains("\""))
{
return JsonUtil.DeserializeFromString<TalkScript>(jsonText);
}
return JsonUtil.DeserializeFromString<TalkScript>(jsonText.Replace("!", "\""));
}
/// <summary>
/// nullになっている部分を全て埋める
/// </summary>
/// <param name="config">エンジンコンフィグ</param>
/// <param name="shortPause">短ポーズ</param>
/// <param name="longPause">長ポーズ</param>
public void Fill(EngineConfig config, int shortPause, int longPause)
{
var section = new VoiceEffectValue(config);
var mora = new VoiceEffectValue(config);
Sections.ForEach(s => s.Fill(section, mora, shortPause, longPause));
EndSection.Fill(section, mora, config, shortPause, longPause);
var curve = new VoiceEffectValue(config);
EndSection.FillCurve(curve, config);
for (int i = Sections.Count - 1; i >= 0; i--)
{
Sections[i].FillCurve(curve, config);
}
{
var talk = new VoiceEffectValue(config);
Volume ??= talk.Volume;
Speed ??= talk.Speed;
Pitch ??= talk.Pitch;
Emphasis ??= talk.Emphasis;
foreach (var s in talk.AdditionalEffect)
{
var val = GetAdditionalValue(s.Key);
if (val == null)
{
SetAdditionalValue(s.Key, s.Value);
}
}
}
}
/// <summary>
/// 不要なパラメータを削除する。
/// </summary>
/// <param name="engineConfig">エンジンコンフィグ</param>
public new void RemoveUnnecessaryParameters(EngineConfig engineConfig)
{
Sections.ForEach(s =>
{
s.RemoveUnnecessaryParameters(engineConfig);
s.Moras.ForEach(m => m.RemoveUnnecessaryParameters(engineConfig));
});
EndSection.RemoveUnnecessaryParameters(engineConfig);
base.RemoveUnnecessaryParameters(engineConfig);
}
/// <summary>
/// プリセット名付きのテキストを返す
/// </summary>
/// <param name="promptString">></param>
/// <returns>プリセット名付きのテキスト</returns>
public string GetOriginalTextWithPresetName(string promptString = ">")
{
if (!string.IsNullOrWhiteSpace(PresetName))
{
return PresetName + promptString + OriginalText;
}
return OriginalText;
}
/// <summary>
/// Jsonに保存する用のテキストを取得する。
/// </summary>
/// <returns>Jsonに保存する用のテキスト</returns>
public string GetPhraseJsonText_toSave()
{
this.OriginalText = null;
var copy = JsonUtil.DeepClone(this);
var jsonText = JsonUtil.SerializeToString(copy);
if (jsonText.Contains("!"))
{
return jsonText;
}
return jsonText.Replace("\"", "!");
}
/// <summary>
/// 読み(全部カタカナ)を取得する。
/// </summary>
/// <param name="withSpace">空白をセクションの間に入れるか</param>
/// <returns>読み</returns>
public string GetYomi(bool withSpace = true)
{
string yomi = string.Empty;
this.Sections.ForEach(s =>
{
s.Moras.ForEach(m =>
{
yomi += m.Character;
});
if (withSpace)
{
yomi += " ";
}
});
yomi += EndSection.EndSymbol;
return yomi;
}
/// <summary>
/// 全てのカナはカタカナで記述される
/// アクセント句は/または、で区切る。、で区切った場合に限り無音区間が挿入される。
/// カナの手前に_を入れるとそのカナは無声化される
/// アクセント位置を'で指定する。全てのアクセント句にはアクセント位置を1つ指定する必要がある。
/// 長音は使えない
/// </summary>
/// <param name="splitChar">区切り文字 / or 、</param>
/// <returns>AquesTalkライクなテキスト</returns>
public string GetYomiForAquesTalkLike(string splitChar = "/")
{
var vowel = "ア";
string yomi = string.Empty;
this.Sections.ForEach(s =>
{
bool accentFlag = true;
for (int i = 0; i < s.Moras.Count; i++)
{
var m = s.Moras[i];
var character = m.Character;
if (character == "ー")
{
character = vowel;
}
else if(character == "ン")
{
vowel = "ウ";
}
else
{
var v = CharacterUtil.FindBoin(m);
if (v != null)
{
vowel = v;
}
}
yomi += (m.Voiceless == true ? "_" : string.Empty) + character;
if (accentFlag &&
(m == s.Moras.Last() || (m.Accent && !s.Moras[i + 1].Accent)))
{
yomi += "'";
accentFlag = false;
}
}
if (s != Sections.Last())
{
yomi += splitChar;
}
});
return yomi;
}
}
}
|
# Quiwi 🥝
[](https://pkg.go.dev/github.com/goburrow/quic)

QUIC transport protocol (https://quicwg.org/) implementation in Go.
The goal is to provide low level APIs for applications or protocols using QUIC as a transport.
TLS 1.3 support is based on standard Go TLS package (https://github.com/golang/go/tree/master/src/crypto/tls),
licensed under the 3-clause BSD license.
## Features
- [X] Handshake with TLS 1.3
- [X] Version negotiation
- [X] Address validation
- [X] Loss detection
- [X] Congestion control
- [X] Streams
- [X] Flow control
- [X] ChaCha20 header protection
- [X] TLS session resumption
- [X] Anti-amplification
- [X] Unreliable datagram
- [X] qlog
- [X] Key update
- [ ] Connection migration
- [ ] Path MTU discovery
- [ ] Zero RTT
- [ ] HTTP/3
## Development
Run tests:
```
go test ./...
```
Build command:
```
cd cmd/quiwi
go build
# To enable tracing
go build -tags quicdebug
# Check heap allocations
go build -gcflags '-m' 2>&1 | sort -V > debug.txt
# Raspberry Pi Zero
GOOS=linux GOARCH=arm GOARM=6 CGO_ENABLED=0 go build
```
### APIs
Package [transport](https://pkg.go.dev/github.com/goburrow/quic@main/transport) provides
low-level APIs to control QUIC connections.
Applications write input data to the connection and read output data for sending to peer.
```go
config := transport.NewConfig()
server, err := transport.Accept(scid, odcid, config)
```
```go
config := transport.NewConfig()
client, err := transport.Connect(scid, config)
```
```go
for !conn.IsClosed() { // Loop until the connection is closed
timeout := conn.Timeout()
// (A negative timeout means that the timer should be disarmed)
select {
case data := <-dataChanel: // Got data from peer
n, err := conn.Write(data)
case <-time.After(timeout): // Got receiving timeout
n, err := conn.Write(nil)
}
// Get and process connection events
events = conn.Events(events)
for { // Loop until err != nil or n == 0
n, err := conn.Read(buf)
// Send buf[:n] to peer
}
}
```
The root package [quic](https://pkg.go.dev/github.com/goburrow/quic@main) instead provides
high-level APIs where QUIC data are transferred over UDP.
It also handles version negotiation, address validation and logging.
```go
server := quic.NewServer(config)
server.SetHandler(handler)
err := server.ListenAndServe(address)
```
```go
client := quic.NewClient(config)
client.SetHandler(handler)
err := client.ListenAndServe(address)
err = client.Connect(serverAddress)
// wait
client.Close()
```
Applications get connection events in the handler to control QUIC connections:
```go
func (handler) Serve(conn *quic.Conn, events []transport.Event) {
for _, e := range events {
switch e.Type {
case transport.EventConnOpen:
case transport.EventConnClosed:
}
}
}
```
### Server
See [cmd/quiwi/server.go](cmd/quiwi/server.go)
```
Usage: quiwi server [arguments]
-cache string
certificate cache directory when using ACME (default ".")
-cert string
TLS certificate path
-domains string
allowed host names for ACME (separated by a comma)
-key string
TLS certificate key path
-listen string
listen on the given IP:port (default ":4433")
-qlog string
write logs to qlog file
-retry
enable address validation using Retry packet
-root string
root directory (default "www")
-v int
log verbose: 0=off 1=error 2=info 3=debug 4=trace (default 2)
```
Examples:
```
# Listen on port 4433:
./quiwi server -cert ../../testdata/cert.pem -key ../../testdata/key.pem
# Automatically get certificate from Let's Encrypt:
# (This will also listen on TCP port 443 to handle "tls-alpn-01" challenge)
./quiwi server -domains example.com
```
Add `SSLKEYLOGFILE=key.log` to have TLS keys logged to file.
### Client
See [cmd/quiwi/client.go](cmd/quiwi/client.go)
```
Usage: quiwi client [arguments] <url>
-cipher string
TLS 1.3 cipher suite, e.g. TLS_CHACHA20_POLY1305_SHA256
-insecure
skip verifying server certificate
-listen string
listen on the given IP:port (default "0.0.0.0:0")
-qlog string
write logs to qlog file
-root string
root download directory
-v int
log verbose: 0=off 1=error 2=info 3=debug 4=trace (default 2)
```
Examples
```
./quiwi client https://quic.tech:4433/
./quiwi client -insecure https://localhost:4433/file.txt
```
### Datagram
See [cmd/quiwi/datagram.go](cmd/quiwi/datagram.go)
```
Usage: quiwi datagram [arguments] [url]
-cert string
TLS certificate path (server only) (default "cert.pem")
-data string
Datagram for sending (or from stdin if empty)
-insecure
skip verifying server certificate (client only)
-key string
TLS certificate key path (server only) (default "key.pem")
-listen string
listen on the given IP:port (default "0.0.0.0:0")
-v int
log verbose: 0=off 1=error 2=info 3=debug 4=trace (default 2)
```
Examples:
```
# Server
./quiwi datagram -listen 127.0.0.1:4433
# Client
./quiwi datagram -insecure -data hello https://127.0.0.1:4433
```
## Testing
See [interop/README.md](interop/README.md)
## Fuzzing
See https://github.com/goburrow/quic-fuzz
|
var classnd_body_player_capsule_impulse_solver =
[
[ "ndBodyPlayerCapsuleImpulseSolver", "classnd_body_player_capsule_impulse_solver.html#a3ae756969dcc80eeba89db0f91d1f304", null ],
[ "AddAngularRows", "classnd_body_player_capsule_impulse_solver.html#a9dbc07c777d1c21ae5639d6623ae26ca", null ],
[ "AddContactRow", "classnd_body_player_capsule_impulse_solver.html#ad7aeb9fce8a5bec38a6682d2c085771f", null ],
[ "AddLinearRow", "classnd_body_player_capsule_impulse_solver.html#af3aee0e659c6680947467ec20a30fc17", null ],
[ "ApplyReaction", "classnd_body_player_capsule_impulse_solver.html#af5ab3bcdb83ef432b34f3b28ea29d781", null ],
[ "CalculateImpulse", "classnd_body_player_capsule_impulse_solver.html#a6963a4a584b406147ab6bd4e3a37d1ed", null ],
[ "Reset", "classnd_body_player_capsule_impulse_solver.html#a6663967079743d330392f296e0f312f4", null ],
[ "m_contactPoint", "classnd_body_player_capsule_impulse_solver.html#ae49fc4adcec6a394a2ab654f6b234548", null ],
[ "m_high", "classnd_body_player_capsule_impulse_solver.html#a3c4016a17bc1d3b9684f18199f7fbbfe", null ],
[ "m_impulseMag", "classnd_body_player_capsule_impulse_solver.html#a842ee5516302520b18639fdc4d2bc1b8", null ],
[ "m_invInertia", "classnd_body_player_capsule_impulse_solver.html#a61ae81a371aae1073f549714725d4333", null ],
[ "m_invMass", "classnd_body_player_capsule_impulse_solver.html#ad18ea14e4a480581f40755ab150c5565", null ],
[ "m_jacobianPairs", "classnd_body_player_capsule_impulse_solver.html#a95377b2b7fff6c21bee0ea6f02011a92", null ],
[ "m_low", "classnd_body_player_capsule_impulse_solver.html#a412ff0714ea5cc2531228542f0edee1f", null ],
[ "m_mass", "classnd_body_player_capsule_impulse_solver.html#a6aedb99c60895a695acf9cb94a88432f", null ],
[ "m_normalIndex", "classnd_body_player_capsule_impulse_solver.html#a7c519e2bd64a1b5fe639478968f5f26a", null ],
[ "m_rhs", "classnd_body_player_capsule_impulse_solver.html#a454227fdc7fe9bb71424f76ab5389427", null ],
[ "m_rowCount", "classnd_body_player_capsule_impulse_solver.html#a14b83750bc29ed75628efbefe7c01d13", null ],
[ "m_veloc", "classnd_body_player_capsule_impulse_solver.html#a84c79c3ae098ca7c345a3ca0cdac54fd", null ]
]; |
package com.kostasdrakonakis.notes.ui
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.ViewModel
import com.kostasdrakonakis.notes.managers.note.NoteManager
import io.reactivex.disposables.CompositeDisposable
import org.koin.core.KoinComponent
import org.koin.core.inject
abstract class BaseViewModel : ViewModel(), LifecycleObserver, KoinComponent {
protected val noteManager by inject<NoteManager>()
protected val compositeDisposable: CompositeDisposable = CompositeDisposable()
override fun onCleared() {
super.onCleared()
if (!compositeDisposable.isDisposed) {
compositeDisposable.dispose()
compositeDisposable.clear()
}
}
} |
package com.fahad.sicpa.activities.search
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fahad.sicpa.network.source.Resource
import com.fahad.sicpa.repositories.article.IArticleRepository
import com.fahad.sicpa.repositories.article.remote.requests.SearchArticleRequest
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SearchViewModel @Inject constructor(
private val articleRepository: IArticleRepository
) : ViewModel() {
private val _state = MutableStateFlow<SearchState>(SearchState.Init)
internal val state: StateFlow<SearchState>
get() = _state
private var searchJob: Job? = null
internal fun searchArticle(query: String) {
searchJob?.cancel()
searchJob = viewModelScope.launch {
articleRepository.searchArticles(
SearchArticleRequest(
query = query
)
).onStart {
_state.value = SearchState.LoadingSearchArticle
}.collect { result ->
when (result) {
is Resource.Success -> {
_state.value = SearchState.GetSearchArticleSuccess(result.data)
}
is Resource.Failed -> {
_state.value = SearchState.GetSearchArticleFailed(result.error)
}
else -> Unit
}
}
}
}
} |
1125667387301421056
1214315619031478272
802210891
487118986
1614378918
980486295993667584
94711461
1098866340
882911602139430913
928202035123703808
342581272
301544479
795829049742467072
909367913009811457
746271034005917696
228745438
47983504
76314876
260773264
2517526903
1090582062006980609
3805497017
1067376950518448128
268308138
201333588
887033296949055494
1018434783922319362
914850453157969920
918409881786429440
3382046475
390670328
1283600144
2361206551
197962366
22637159
961258391023902721
3063498987
4172012380
592495181
123287597
1941552596
1320053646
24167314
2270977421
1110890216
943798626
21313364
1459774501
727462551043317760
778098651335888896
743432061088899073
143554758
3396006639
716003995
20696007
744110870477803520
785292762
153836373
4137115401
1560098432
3392314954
289236741
2935594991
1613344746
719530778460340224
83826746
266653632
2364612763
4531940473
2593561027
2155215398
16497528
4816121122
1484677214
2899748807
239783899
113346902
2468003900
1062594367
6652032
1367353994
229966616
340580013
911033347
4490760735
1536013260
2876393283
49586084
133663801
490126636
427288938
28332028
79145543
70385068
18814998
35777570
82353781
250495004
451221834
3312654241
2383597357
110891415
29701712
16389180
22090282
25103967
19106719
47399805
2184489764
3083395917
2306273234
338985020
380648579
2770773650
3322970356
302475083
348982404
1464243415
2835245361
404140249
3096112079
551707148
374008782
3027816952
631452769
46830041
1976143068
93644596
2613608820
1971628710
176763706
2835127642
756762998
90556897
2649991
65416867
96847764
313143181
1968943153
197816493
260280517
398000696
62747302
888568968
1690415646
2283632178
475166265
233631354
767240250
229375729
435823876
18969131
17169453
14140057
1675637528
1864425979
2367645667
2450441156
2481706232
386449515
1886255694
74413414
51015054
87212906
2528065846
484837252
490400673
485115603
122115981
99743526
92004185
2437546298
492003056
200191749
205302139
2411145954
1650872978
2433439777
1735676780
2431610544
464643212
2466999033
285609251
492316378
598419228
1704357560
239734415
2427573487
2427585512
2249803275
989554916
592872760
88657577
299741759
1304851238
104894691
1966152649
510393893
2423841156
2455773251
81063019
406863200
368707563
356701494
215246156
2257493831
216105673
2420892145
1241797638
297355884
501850990
249584113
28977778
2446606287
2418806719
104071332
151361543
2440584759
2344424805
136596610
2320316953
455078038
304243011
2410888056
1323096356
1588938685
2414240078
2433691131
2435894867
2412291000
235146669
124397732
1080398370
2438276147
2433815979
2428364685
2436025372
2278710065
102961250
2202053331
55222230
1410339452
709124264
91079862
108506538
1519212080
833641560
92329403
25262387
47917037
2408772584
988166575
14400737
2291011155
2393820385
393491873
58913261
40205617
344016850
57568585
869504161
412165494
834355502
1376423492
1386086917
951480480
1100188033
2173679916
1341255338
761527008
166960398
1307172588
1008210156
413642033
2272608259
1903930436
2278875343
2278837958
88289675
192851564
1425073231
2274708450
843130302
384486719
44342524
2223668637
2223683596
2245716919
2223566458
2247510050
1734417787
1001562325
17013028
2196235670
1704337218
2252341052
61581813
199594782
478322930
568688257
311954809
140341940
103810199
2213884818
2213874781
1128560318
299671273
1657508443
85932386
170308855
147526628
206589337
313212733
196199069
225006757
1593563090
46432706
188443944
38395124
519525122
34898575
143089501
283878271
242603803
53873753
110995176
30010590
1451957396
313132260
24744541
18980478
|
3733,300,0
2522,36,0
2531,600,0
2534,120,0
14885,285,0
14921,400,0
8187,25,0
562,290,0
575,2400,0
590,1700,0
7895,259,0
628,37,0
638,1600,0
681,75,0
475,3000,0
699,2700,0
797,390,0
711,500,0
2505,700,0
750,94,0
3734,420,0
937,69,0
927,400,0
5055,70,0
3754,64,0
14961,31,0
14528,581,0
491,1300,0
511,5000,0
536,1300,0
556,600,0
565,550,0
14525,37,0
2537,75,0
2542,17,0
2543,400,0
2547,9,0
2549,60,0
14426,196,0
3755,8,0
499,12,0
3999,17,0
525,2900,0
560,47,0
600,210,0
2568,23,0
2554,1530,0
2560,1400,0
2561,2500,0
2912,78,0
2565,570,0
2576,37,0
2583,50,0
2598,32,0
2602,24,0
2603,5,0
2604,41,0
2605,31,0
2606,18,0
2612,1650,0
3727,303,0
2620,297,0
2621,56,0
8193,780,0
3945,8,0
12535,50,0
12532,71,0
3936,13,0
14427,147,0
14428,10,0
507,880,0
495,64,0
12742,440,0
12741,274,0
3834,31,0
538,200,0
2638,33,0
601,100,0
611,4000,0
3815,200,0
14825,200,0
653,45,0
2595,11,0
754,413,0
14435,500,0
786,3300,0
799,24,0
3877,400,0
14494,202,0
11239,1900,0
14826,240,0
14436,110,0
823,100,0
14924,910,0
2646,120,0
2647,16,0
2649,18,0
529,800,0
537,338,0
3960,2610,0
14920,22,0
567,4,0
14910,800,0
12536,700,0
3831,90,0
14512,285,0
603,2800,0
2654,2070,0
2655,90,0
2667,900,0
3873,72,0
614,200,0
607,2640,0
12537,144,0
3965,78,0
582,75,0
2660,31,0
570,1,0
543,1200,0
532,600,0
503,1350,0
3962,2300,0
3892,1020,0
490,39,0
2672,120,0
2673,97,0
14908,9,0
512,1386,0
14430,920,0
3772,2,0
534,6,0
13330,3900,0
587,1200,0
569,61,0
573,50,0
4138,16,0
622,200,0
629,1500,0
642,800,0
649,4900,0
660,700,0
665,400,0
674,630,0
14422,49,0
477,400,0
487,400,0
492,1000,0
505,720,0
531,15,0
624,702,0
656,500,0
2729,120,0
2733,32,0
14513,300,0
671,2720,0
2722,51,0
2724,11,0
2725,16,0
8022,6100,0
2726,110,0
14433,487,0
3747,113,0
677,100,0
684,69,0
14429,1062,0
766,200,0
2744,5,0
2736,300,0
574,1200,0
533,900,0
526,1950,0
14929,601,0
610,1800,0
658,900,0
662,2800,0
668,700,0
724,300,0
2794,9,0
770,34,0
14495,249,0
2797,11,0
3959,35,0
577,2150,0
591,4000,0
2801,25,0
2802,30,0
2804,10,0
2805,400,0
652,700,0
686,23,0
14434,5,0
3852,900,0
14432,480,0
2806,450,0
2808,29,0
3833,67,0
793,44,0
14891,1065,0
14890,660,0
890,4950,0
3866,3300,0
916,31,0
922,29,0
509,48,0
13312,25,0
762,900,0
2856,82,0
980,328,0
2859,40,0
987,1926,0
988,1053,0
992,2500,0
4123,90,0
14370,1590,0
1000,2400,0
12530,200,0
14273,64,0
4087,350,0
2868,500,0
2869,100,0
540,5,0
13505,2318,0
14431,2660,0
547,1400,0
566,900,0
606,75,0
615,22,0
3855,300,0
12543,63,0
12542,25,0
640,51,0
14386,22,0
14387,22,0
14519,82,0
14424,224,0
14423,490,0
14046,1,0
14515,10,0
2876,240,0
2877,80,0
2878,150,0
2778,1500,0
729,900,0
3898,700,0
14492,4600,0
14911,537,0
8185,18,0
8186,7,0
14425,30,0
501,800,0
14221,600,0
14220,400,0
2886,90,0
3925,1,0
13287,60,0
559,90,0
14919,19,0
14917,440,0
579,11,0
2891,900,0
4005,34,0
3933,120,0
14514,136,0
12531,1500,0
14523,140,0
3769,113,0
3957,2,0
2897,55,0
639,2800,0
14374,3100,0
3878,1700,0
651,35,0
2898,14,0
3797,81,0
2901,800,0
685,200,0
2511,1200,0
2540,696,0
2550,750,0
2494,21,0
5218,1530,0
2685,5,0
5220,150,0
7906,22,0
9391,84,0
2669,28,0
5202,41,0
2662,3,0
3828,41,0
4031,4300,0
7939,40,0
946,21,0
12738,130,0
3854,240,0
2498,13,0
2687,23,0
2545,2100,0
2500,1900,0
8140,1200,0
2520,50,0
943,6,0
2506,30,0
2719,300,0
14594,1,0
2338,3,0
4280,4,0
2339,6,0
4347,100,0
4496,47,0
3846,124,0
4075,100,0
4182,200,0
2357,20,0
2358,20,0
2359,20,0
8131,6,0
2374,8,0
2375,5,0
3840,10,0
6513,100,0
12683,24,0
4285,1,0
2388,4000,0
949,30,0
4452,100,0
4233,50,0
12626,200,0
12616,24,0
12953,34,0
13244,4,0
8177,19,0
12587,9,0
12937,36,0
12586,42,0
12941,8,0
6044,600,0
6322,6,0
4463,10,0
4464,5,0
6280,13,0
875,45,0
11537,88,0
14605,24,0
2435,13,0
2436,7,0
4472,7,0
4494,17,0
12701,100,0
904,7,0
12581,1,0
9395,50,0
9394,55,0
8098,39,0
8121,30,0
|
import { assign, noop } from '../utils/helpers';
const handlers = {};
export default {
load: noop,
addHandlers(obj) {
assign(handlers, obj);
},
onHandle({ cmd, data }) {
handlers[cmd]?.(data);
},
};
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.