text
stringlengths 27
775k
|
|---|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Mtrangchu extends MY_Model {
public function __construct()
{
parent::__construct();
}
function get_dmsanpham(){
return $this->db->get('tbl_danhmuc_sanpham')->result_array();
}
function get_sanphamslide($limit, $offset){
$this->db->select('*, tbl_loaisanpham.ten_loaisanpham');
$this->db->from('tbl_sanpham');
$this->db->join('tbl_loaisanpham', 'tbl_loaisanpham.ma_loaisanpham = tbl_sanpham.ma_loaisanpham', 'inner');
$this->db->join('tbl_anhsanpham', 'tbl_anhsanpham.ma_sanpham = tbl_sanpham.ma_sanpham', 'inner');
$this->db->order_by('ngaydang desc');
$this->db->limit($limit,$offset);
$query = $this->db->get();
return $query->result_array();
}
function get_sanpham(){
$this->db->select('*');
$this->db->from('tbl_sanpham');
$this->db->join('tbl_loaisanpham', 'tbl_loaisanpham.ma_loaisanpham = tbl_sanpham.ma_loaisanpham', 'inner');
$this->db->join('tbl_danhmuc_sanpham', 'tbl_danhmuc_sanpham.ma_dmsanpham = tbl_loaisanpham.ma_dmsanpham', 'inner');
$this->db->join('tbl_donvitinh_sanpham', 'tbl_donvitinh_sanpham.ma_donvitinh = tbl_sanpham.ma_donvitinh', 'inner');
$this->db->join('tbl_nhacungcap', 'tbl_nhacungcap.ma_nhacungcap = tbl_sanpham.ma_nhacungcap', 'inner');
$this->db->join('tbl_anhsanpham', 'tbl_anhsanpham.ma_sanpham = tbl_sanpham.ma_sanpham', 'inner');
$this->db->join('tbl_taikhoan', 'tbl_taikhoan.ma_taikhoan = tbl_sanpham.nguoidang_sp', 'inner');
$query = $this->db->get();
// echo $this->db->last_query();
return $query->result_array();
}
/*Lấy dữ liêu đầy đủ của một sản phẩm*/
public function getdulieu($ma_sanpham){
$this->db->select('*');
$this->db->where('ma_sanpham',$ma_sanpham);
$this->db->where('trangthai_dang_sanpham', 1);
$this->db->where('trangthai_hot_sanpham', 1);
return $this->db->get('tbl_sanpham')->row_array();
}
public function get_SumCart($matv){
$this->db->select('count("ma_sanpham") as tongCart');
$this->db->where("ma_thanhvien", $matv);
return $this->db->get('tbl_cart')->row_array();
}
}
|
@if($data['header'] == 'tak')
<div class="text--center title--icon">
<img src="@asset("images/leaf.png")" alt="lasagne">
<h2 class="title title--section">
{{ $data['title'] }}
</h2>
@if($menu)
<a class="button button--pdf" href="{{ $menu['url'] }}">
PDF
</a>
@endif
</div>
@endif
|
mod class;
mod class_loader;
mod class_member;
mod class_ref;
mod constant_pool;
mod field;
mod field_ref;
mod member_ref;
mod method;
mod object;
mod symbol_ref;
|
import 'package:byr_mobile_app/customizations/theme_controller.dart';
import 'package:byr_mobile_app/reusable_components/refreshers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
class ScreenshotFooter extends LoadIndicator {
final VoidCallback onClick;
ScreenshotFooter({this.onClick})
: super(onClick: onClick, loadStyle: LoadStyle.ShowWhenLoading, height: recommendedHeight);
static double recommendedHeight = 55;
@override
State<StatefulWidget> createState() {
return _ScreenshotFooterState();
}
}
class _ScreenshotFooterState extends LoadIndicatorState<ScreenshotFooter> with SingleTickerProviderStateMixin {
@override
void initState() {
super.initState();
}
@override
void dispose() {
super.dispose();
}
@override
Future<void> endLoading() {
return super.endLoading();
}
@override
Future<void> readyToLoad() {
return super.readyToLoad();
}
@override
void resetValue() {
super.resetValue();
}
@override
Widget buildContent(BuildContext context, LoadStatus mode) {
Widget body;
if (mode == LoadStatus.idle) {
body = Text(
"pullUpToScreenshot".tr,
style: TextStyle(
color: E().threadListOtherTextColor,
),
);
} else if (mode == LoadStatus.loading) {
body = Theme(
data: ThemeData(
cupertinoOverrideTheme: CupertinoThemeData(
brightness: !E().isThemeDarkStyle ? Brightness.light : Brightness.dark,
)),
child: CupertinoActivityIndicator());
} else if (mode == LoadStatus.canLoading) {
body = Text(
"releaseToScreenshot".tr,
style: TextStyle(
color: E().threadListOtherTextColor,
),
);
} else if (mode == LoadStatus.failed) {
body = Text(
"screenshotFailed".tr,
style: TextStyle(
color: E().threadListOtherTextColor,
),
);
} else {
body = Text("");
}
return Container(
height: 55.0,
child: Center(child: body),
);
}
}
|
package se.gigurra.renderer
trait TextRenderer {
def print(text: String, font: Font)
def printLn(text: String, font: Font)
def getTextWidth(text: String, font: Font): Float
}
|
---
layout: post
categories: [tech, life]
title: The first post
---
Just setup my blog using Jekyll and testing it with this first post.
The initial theme is inspired by [Paul Chiusano's blog](https://pchiusano.github.io/).
(Updated on 09/11/2018)
|
//! The memory caching implementation.
use crate::{common::*, profiling::Timing};
// cache loader
/// Image caching processor.
#[derive(Debug)]
pub struct MemoryCache {
image_size: usize,
image_channels: usize,
device: Device,
cache: flurry::HashMap<String, CacheEntry>,
}
#[derive(Debug)]
struct CacheEntry(Tensor);
impl CacheEntry {
pub fn new(tensor: Tensor) -> Self {
Self(tensor)
}
pub fn get(&self) -> Tensor {
self.0.shallow_clone()
}
}
unsafe impl Sync for CacheEntry {}
impl MemoryCache {
/// Build a new memory caching processor.
///
/// * `image_size` - The outcome image size in pixels.
/// * `image_channels` - The expected number of image channels.
/// * `device` - The outcome image device. It defaults to CPU if set to `None`.
pub async fn new(
image_size: usize,
image_channels: usize,
device: impl Into<Option<Device>>,
) -> Result<Self> {
ensure!(image_size > 0, "image_size must be positive");
ensure!(image_channels > 0, "image_channels must be positive");
let loader = Self {
image_size,
image_channels,
device: device.into().unwrap_or(Device::Cpu),
cache: flurry::HashMap::new(),
};
Ok(loader)
}
/// Load image and boxes.
///
/// If cache hit, it loads the cached image and boxes from cache directory.
/// If cache miss, it loads and resizes the image from original path and saves it to cache directory.
pub async fn load_cache(
&self,
image_path: impl AsRef<async_std::path::Path>,
orig_size: &PixelSize<usize>,
bboxes: impl IntoIterator<Item = impl Borrow<PixelRectLabel<R64>>>,
) -> Result<(Tensor, Vec<RatioRectLabel<R64>>)>
where {
let Self {
image_size,
image_channels,
device,
ref cache,
} = *self;
let image_path = image_path.as_ref();
let [orig_h, orig_w] = orig_size.hw();
ensure!(
image_channels == 3,
"image_channels other than 3 is not supported"
);
// compute cache size
let resize_ratio =
(image_size as f64 / orig_h as f64).min(image_size as f64 / orig_w as f64);
let cache_h = (orig_h as f64 * resize_ratio) as usize;
let cache_w = (orig_w as f64 * resize_ratio) as usize;
let mut timing = Timing::new("cache_loader");
// compute padding size
let top_pad = (image_size - cache_h) / 2;
let bottom_pad = image_size - cache_h - top_pad;
let left_pad = (image_size - cache_w) / 2;
let right_pad = image_size - cache_w - left_pad;
// construct cache path
let cache_key = format!(
"{}-{}-{}-{}",
percent_encoding::utf8_percent_encode(image_path.to_str().unwrap(), NON_ALPHANUMERIC),
image_channels,
cache_h,
cache_w,
);
// write cache if the cache is not valid
let entry = cache
.pin()
.get(&cache_key)
.map(|entry| entry.get().to_device(device));
let image = match entry {
Some(entry) => entry,
None => {
// load and resize image
let image_path = image_path.to_owned();
let (image, timing_) = async_std::task::spawn_blocking(move || -> Result<_> {
tch::no_grad(|| -> Result<_> {
let image = vision::image::load(image_path)?;
{
let shape = image.size3()?;
let expect_shape =
(image_channels as i64, orig_h as i64, orig_w as i64);
ensure!(
shape == expect_shape,
"image size does not match, expect {:?}, but get {:?}",
expect_shape,
shape
);
}
let image = image
// resize on cpu before moving to CUDA due to this issue
// https://github.com/LaurentMazare/tch-rs/issues/286
.resize2d_exact(cache_h as i64, cache_w as i64)?
.to_kind(Kind::Float)
.g_div_scalar(255.0)
.set_requires_grad(false);
timing.add_event("load & resize");
// resize and center
let image = {
image
.view([1, image_channels as i64, cache_h as i64, cache_w as i64])
.zero_pad2d(
left_pad as i64,
right_pad as i64,
top_pad as i64,
bottom_pad as i64,
)
.view([image_channels as i64, image_size as i64, image_size as i64])
.set_requires_grad(false)
};
timing.add_event("pad");
Ok((image, timing))
})
})
.await?;
timing = timing_;
cache
.pin()
.insert(cache_key, CacheEntry::new(image.shallow_clone()));
image
}
};
// compute new bboxes
let transform = {
let src = PixelTLBR::from_tlbr(0.0, 0.0, orig_h as f64, orig_w as f64).unwrap();
let tgt = PixelTLBR::from_tlhw(
top_pad as f64,
left_pad as f64,
cache_h as f64,
cache_w as f64,
)
.unwrap();
PixelRectTransform::from_rects(&src, &tgt)
.cast::<R64>()
.unwrap()
};
let output_bboxes: Vec<_> = {
let image_size = R64::new(image_size as f64);
bboxes
.into_iter()
.map(|orig_label| -> Result<_> {
let orig_label = orig_label.borrow();
let new_label = (&transform * orig_label)
.to_ratio_label(&PixelSize::from_hw(image_size, image_size)?);
Ok(new_label)
})
.try_collect()?
};
timing.add_event("compute bboxes");
timing.report();
Ok((image, output_bboxes))
}
}
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'creating a draft DOI', :datacite_api, :js do
let(:model_class) do
Class.new(GenericWork) do
include Hyrax::DOI::DOIBehavior
include Hyrax::DOI::DataCiteDOIBehavior
end
end
let(:form_class) do
Class.new(Hyrax::GenericWorkForm) do
include Hyrax::DOI::DOIFormBehavior
include Hyrax::DOI::DataCiteDOIFormBehavior
self.model_class = GenericWork
end
end
let(:helper_module) do
Module.new do
include ::BlacklightHelper
include Hyrax::BlacklightOverride
include Hyrax::HyraxHelperBehavior
include Hyrax::DOI::HelperBehavior
end
end
let(:solr_document_class) do
Class.new(SolrDocument) do
include Hyrax::DOI::SolrDocument::DOIBehavior
include Hyrax::DOI::SolrDocument::DataCiteDOIBehavior
end
end
let(:controller_class) do
Class.new(::ApplicationController) do
# Adds Hyrax behaviors to the controller.
include Hyrax::WorksControllerBehavior
include Hyrax::BreadcrumbsForWorks
self.curation_concern_type = GenericWork
# Use this line if you want to use a custom presenter
self.show_presenter = Hyrax::GenericWorkPresenter
helper Hyrax::DOI::Engine.helpers
end
end
let(:prefix) { '10.1234' }
let(:user) { create(:admin) }
before do
# Override test app classes and module to simulate generators having been run
stub_const("GenericWork", model_class)
stub_const("Hyrax::GenericWorkForm", form_class)
stub_const("HyraxHelper", helper_module)
stub_const("SolrDocument", solr_document_class)
stub_const("Hyrax::GenericWorksController", controller_class)
Hyrax.config.identifier_registrars = { datacite: Hyrax::DOI::DataCiteRegistrar }
Hyrax::DOI::DataCiteRegistrar.mode = :test
Hyrax::DOI::DataCiteRegistrar.prefix = prefix
Hyrax::DOI::DataCiteRegistrar.username = 'username'
Hyrax::DOI::DataCiteRegistrar.password = 'password'
allow_any_instance_of(Ability).to receive(:admin_set_with_deposit?).and_return(true)
allow_any_instance_of(Ability).to receive(:can?).and_call_original
allow_any_instance_of(Ability).to receive(:can?).with(:new, anything).and_return(true)
sign_in user
end
scenario 'creates a draft DOI on the form' do
visit "/concern/generic_works/new"
click_link "doi-create-draft-btn"
expect(page).to have_field('generic_work_doi', with: '10.1234/draft-doi')
end
end
|
package io.arkstud.wordbox_roberto.network.person.model
import java.io.Serializable
data class GetPersonsResponse (
var results: List<PersonResponse>,
var info: Info
)
data class Info (
var seed: String,
var results: Int,
var page: Int,
var version: String
)
data class PersonResponse (
var name: PersonName,
var gender: String,
var email: String,
var picture: PersonPicture
)
data class PersonPicture (
var thumbnail: String? = null,
var medium: String? = null,
var large: String? = null
) : Serializable
data class PersonName (
var title: String,
var first: String,
var last: String
)
|
export * from './lib/datasets';
export * from './lib/detailed-dataset';
export * from './lib/select-dataset';
|
import torch
from torch.autograd import Variable
import utils
import dataset
from PIL import Image
import models.crnn as crnn
model_path = './expr/netCRNN_99_100.pth'
img_path = '../text2font/imgs/x14y24pxHeadUpDaisy_2.png'
#alphabet = '0123456789abcdefghijklmnopqrstuvwxyz'
with open('alphabets.txt', 'r', encoding='utf8') as f:
alphabet = f.read()
model = crnn.CRNN(32, 1, (len(alphabet)+1), 256)
if torch.cuda.is_available():
model = model.cuda()
print('loading pretrained model from %s' % model_path)
param_odict = torch.load(model_path)
for key in list(param_odict.keys()):
param_odict[key.replace('module.', '')] = param_odict[key]
param_odict.pop(key)
#crnn.load_state_dict(torch.load(opt.crnn))
model.load_state_dict(param_odict)
#model.load_state_dict(torch.load(model_path))
converter = utils.strLabelConverter(alphabet)
image = Image.open(img_path).convert('L')
transformer = dataset.resizeNormalize((int(image.size[0]/50.*32.), 32))
image = transformer(image)
if torch.cuda.is_available():
image = image.cuda()
image = image.view(1, *image.size())
image = Variable(image)
model.eval()
preds = model(image)
_, preds = preds.max(2)
preds = preds.transpose(1, 0).contiguous().view(-1)
preds_size = Variable(torch.IntTensor([preds.size(0)]))
raw_pred = converter.decode(preds.data, preds_size.data, raw=True)
sim_pred = converter.decode(preds.data, preds_size.data, raw=False)
print('%-20s => %-20s' % (raw_pred, sim_pred))
|
USE SnakesAndLadder;
drop procedure if exists ProvidingAdminAccess;
DELIMITER //
Create procedure ProvidingAdminAccess (pUsername varchar(50))
begin
declare countExistedUsername int;
START TRANSACTION;
select count(Username) from Account
where Username = pUsername
into countExistedUsername;
if countExistedUsername = 1 then
Update Account
Set AdminPermission = 'Yes'
where Username = pUsername;
else
Select 'The Username doesnt exists' as message;
end if;
END //
DELIMITER ;
call ProvidingAdminAccess ('Bryan902');
select * from account
where (Username = 'Bryan902');
|
---
id: 9d7123c8c441eeafaeb5bdef
title: Remove Elements from an Array Using slice Instead of splice
challengeType: 1
forumTopicId: 301236
localeTitle: 使用 slice 而不是 splice 从数组中移除元素
---
## Description
<section id='description'>
使用数组时经常遇到要删除一些元素并保留数组剩余部分的情况。为此,JavaScript 提供了<code>splice</code>方法,它接收两个参数:从哪里开始删除项目的索引,和要删除的项目数。如果没有提供第二个参数,默认情况下是移除到结尾的元素。但<code>splice</code>方法会改变调用它的原始数组。举个例子:
```js
var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
cities.splice(3, 1); // Returns "London" and deletes it from the cities array
// cities is now ["Chicago", "Delhi", "Islamabad", "Berlin"]
```
正如我们在上一次挑战中看到的那样,<code>slice</code>方法不会改变原始数组,而是返回一个可以保存到变量中的新数组。回想一下,<code>slice</code>方法接收两个参数,从开始索引开始选取到结束(不包括该元素),并在新数组中返回这些元素。使用<code>slice</code>方法替代<code>splice</code>有助于避免数组变化产生的副作用。
</section>
## Instructions
<section id='instructions'>
用<code>slice</code>代替<code>splice</code>重写<code>nonMutatingSplice</code>函数。将<code>cities</code>数组长度限制为3,并返回一个仅包含前 3 项的新数组。
不要改变提供给函数的原始数组。
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 应该使用<code>slice</code>方法。
testString: assert(code.match(/\.slice/g));
- text: 不能使用<code>splice</code>方法。
testString: assert(!code.match(/\.splice/g));
- text: 不能改变<code>inputCities</code>数组。
testString: assert(JSON.stringify(inputCities) === JSON.stringify(["Chicago", "Delhi", "Islamabad", "London", "Berlin"]));
- text: "<code>nonMutatingSplice(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])</code>应返回<code>['Chicago', 'Delhi', 'Islamabad']</code>。"
testString: assert(JSON.stringify(nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])) === JSON.stringify(["Chicago", "Delhi", "Islamabad"]));
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function nonMutatingSplice(cities) {
// Add your code below this line
return cities.splice(3);
// Add your code above this line
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function nonMutatingSplice(cities) {
// Add your code below this line
return cities.slice(0,3);
// Add your code above this line
}
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
```
</section>
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Category extends CI_Controller {
function __construct()
{
parent::__construct();
//Load Dependencies
$this->load->library(array('template', 'form_validation'));
$this->load->model('admin');
}
public function index()
{
$this->cek_login();
$data['header'] = 'Manage Category';
$data['category'] = $this->admin->get_all('t_category');
$this->template->admin('category', $data);
}
public function category()
{
$data['header'] = 'Input Category';
$this->template->admin('input_category' ,$data);
}
public function add()
{
if ($this->input->post('submit', TRUE) == 'Submit') {
$this->form_validation->set_rules('cat_nm', 'Category Name', 'required');
$this->form_validation->set_rules('division', 'Division', 'required');
if ($this->form_validation->run() == TRUE) {
$data = array(
'CAT_NM' => $this->input->post('cat_nm', TRUE),
'DIVISION' => $this->input->post('division', TRUE)
);
$this->admin->insert_last('t_category',$data);
$this->session->set_flashdata('alert', 'Sukses Menyimpan data !!!');
redirect('Category','refresh');
} else {
$this->session->set_flashdata('alert-danger', 'Gagal Menyimpan data !!!');
}
}
$data['CAT_NM'] = $this->input->post('cat_nm', TRUE);
$data['DIVISION'] = $this->input->post('division', TRUE);
$data['header'] = 'Input Category';
$this->template->admin('input_category' ,$data);
}
public function detail()
{
if (!is_numeric($this->uri->segment(3)))
{
redirect('Category');
}
$data['header'] = 'Detail Category';
$data['data'] = $this->admin->get_where('t_category',['CAT_ID' => $this->uri->segment(3)]);
$this->template->admin('detail_category', $data);
}
public function update()
{
if ($this->input->post('submit', TRUE) == 'Submit') {
//validasi
$this->form_validation->set_rules('cat_nm', 'Category Name', 'required');
$this->form_validation->set_rules('division', 'Division', 'required');
if ($this->form_validation->run() == TRUE)
{
$data = array(
'CAT_NM' => $this->input->post('cat_nm', TRUE),
'DIVISION' => $this->input->post('division', TRUE)
);
$this->admin->update('t_category', $data, array('CAT_ID' => $this->input->post('cat_id', TRUE)));
}
else {
$this->admin->update('t_category', $data, array('CAT_ID' => $this->input->post('cat_id', TRUE)));
}
redirect('Category','refresh');
}
}
//Delete one item
public function delete( $id = NULL )
{
if (!is_numeric($this->uri->segment(3))) {
redirect('Category');
}
$table = 't_category';
$this->admin->delete($table, ['CAT_ID' => $this->uri->segment(3)]);
$this->session->set_flashdata('alert', 'Sukses Menghapus data !!!');
redirect('Category');
}
function cek_login()
{
if (!$this->session->userdata('login_user'))
{
redirect('login');
}
}
}
|
using Clide;
using System;
using System.Linq;
using System.Collections.Generic;
namespace NuGet.Packaging.VisualStudio
{
class MoveProjectItemsToProjectVisitor : ISolutionVisitor
{
readonly Stack<ISolutionExplorerNode> stack;
readonly List<ISolutionExplorerNode> nodesToBeDeleted;
readonly Func<IProjectItemNode, bool> filterItem = x => false; // null filter
public MoveProjectItemsToProjectVisitor(IProjectNode targetProject, Func<IProjectItemNode, bool> filterItem = null)
{
stack = new Stack<ISolutionExplorerNode>();
stack.Push(targetProject);
if (filterItem != null)
this.filterItem = filterItem;
nodesToBeDeleted = new List<ISolutionExplorerNode>();
}
public bool VisitEnter(IProjectNode project) => true;
public bool VisitEnter(IFolderNode folder)
{
if (filterItem(folder))
return false;
var parent = stack.Peek();
var targetFolder = parent
.Nodes
.FirstOrDefault(x => string.Equals(x.Name, folder.Name, StringComparison.OrdinalIgnoreCase));
if (targetFolder == null)
targetFolder = parent.As<IProjectItemContainerNode>().CreateFolder(folder.Name);
stack.Push(targetFolder);
return true;
}
public bool VisitEnter(IItemNode item)
{
if (filterItem(item))
return false;
var parent = stack.Peek();
var targetItem = parent
.Nodes
.OfType<IItemNode>()
.FirstOrDefault(x => string.Equals(x.Name, item.Name, StringComparison.OrdinalIgnoreCase));
// Delete the existing item in the target project
if (targetItem != null)
targetItem.Delete();
// And add the new one
parent.As<IProjectItemContainerNode>().AddItem(item.PhysicalPath);
return false;
}
public bool VisitEnter(IReferencesNode references) => false;
public bool VisitEnter(IReferenceNode reference) => false;
public bool VisitEnter(IGenericNode node) => true;
public bool VisitLeave(IFolderNode folder)
{
if (filterItem(folder))
return false;
stack.Pop();
nodesToBeDeleted.Add(folder);
return true;
}
public bool VisitLeave(IReferencesNode references) => true;
public bool VisitLeave(IGenericNode node) => true;
public bool VisitLeave(IReferenceNode reference) => false;
public bool VisitLeave(IItemNode item)
{
if (filterItem(item))
return false;
nodesToBeDeleted.Add(item);
return false;
}
public bool VisitLeave(IProjectNode project)
{
// Once the project has been processed, delete all nodes
// in order to avoid CollectionModified exception
foreach (var node in nodesToBeDeleted)
{
var deletableNode = node.As<IDeletableNode>();
if (deletableNode != null)
{
try
{
deletableNode.Delete();
}
catch
{
// Ignore?
}
}
}
return false;
}
public bool VisitEnter(ISolutionItemNode solutionItem)
{
throw new NotSupportedException();
}
public bool VisitEnter(ISolutionFolderNode solutionFolder)
{
throw new NotSupportedException();
}
public bool VisitEnter(ISolutionNode solution)
{
throw new NotSupportedException();
}
public bool VisitLeave(ISolutionFolderNode solutionFolder)
{
throw new NotSupportedException();
}
public bool VisitLeave(ISolutionItemNode solutionItem)
{
throw new NotSupportedException();
}
public bool VisitLeave(ISolutionNode solution)
{
throw new NotSupportedException();
}
}
}
|
class Import < ApplicationRecord
belongs_to :medium
belongs_to :teachable, polymorphic: true
validates :medium, uniqueness: { scope: [:teachable] }
end
|
namespace Buildron.Domain.Users
{
/// <summary>
/// Arguments for user updated events.
/// </summary>
public class UserUpdatedEventArgs : UserEventArgsBase
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Buildron.Domain.Users.UserUpdatedEventArgs"/> class.
/// </summary>
/// <param name="user">The user.</param>
public UserUpdatedEventArgs(IUser user)
: base (user)
{
}
#endregion
}
}
|
class SellCupcakeJob < ApplicationJob
queue_as :default
def perform(cupcakes = [])
json_api_opts = {}
json_api_opts[is_collection: true]
json_api_opts[:meta] = {total: cupcakes.length }
serializer = CupcakeSerializer.new(cupcakes, json_api_opts)
message = serializer.serialized_json
ActiveJob::Base.execute message
ack!
end
end
|
# == Schema Information
#
# Table name: attendings
#
# id :integer not null, primary key
# course_id :integer
# user_id :integer
# created_at :datetime
# updated_at :datetime
# last_visit :datetime
# role :integer default("0")
#
class Attending < ActiveRecord::Base
enum role: [:member, :admin, :owner]
belongs_to :course
belongs_to :user
validates :course, presence: true
validates :user, presence: true
validates :user_id, uniqueness: { scope: [:course_id] }
before_create :set_last_visit
def update_last_visit
update_attribute(:last_visit, Time.now.in_time_zone)
end
private
def set_last_visit
self.last_visit = Time.now.in_time_zone
end
end
|
# Protected Planet Monthly WDPA Release Import
The new Protected Planet website is designed to make importing and displaying
the WDPA monthly releases as easy and fast as possible.
## What you have to do
The import process is detailed [here](https://github.com/unepwcmc/wiki/wiki/WDPA-Release)
|
/* eslint-disable */
import { testExamples, render, waitFor, fireEvent, act } from '@test/utils';
import React, { useState } from 'react';
import { Select } from 'tdesign-react';
const { Option, OptionGroup } = Select;
// 测试组件代码 Example 快照
testExamples(__dirname);
describe('Select 组件测试', () => {
const selectSelector = '.t-select';
const popupSelector = '.t-popup';
const options = [
{
label: 'Apple',
value: 'apple',
},
{
label: 'Banana',
value: 'banana',
},
{
label: 'Orange',
value: 'orange',
},
];
const RemoteSearchSelect = ({ multiple }: { multiple?: boolean }) => {
const defaultOptions = [
{
label: 'Apple',
value: 'apple',
},
{
label: 'Banana',
value: 'banana',
},
{
label: 'Orange',
value: 'orange',
},
];
const [value, setValue] = useState();
const [loading, setLoading] = useState(false);
const [options, setOptions] = useState(defaultOptions);
const onChange = (value) => {
setValue(value);
};
const handleRemoteSearch = (search) => {
setLoading(true);
setTimeout(() => {
setLoading(false);
let options = [];
if (search) {
options = [
{
value: `${search}_test1`,
label: `${search}_test1`,
},
{
value: `${search}_test2`,
label: `${search}_test2`,
},
{
value: `${search}_test3`,
label: `${search}_test3`,
},
];
} else {
options = defaultOptions;
}
setOptions(options);
}, 300);
};
return (
<Select
filterable
multiple={multiple}
value={value}
onChange={onChange}
loading={loading}
onSearch={handleRemoteSearch}
>
{options.map((item) => (
<Option key={item.value} label={item.label} value={item.value} />
))}
</Select>
);
};
test('单选测试', async () => {
await act(async () => {
const SingleSelect = () => {
const [value, setValue] = useState('apple');
const onChange = (value) => {
setValue(value);
};
return (
<Select value={value} onChange={onChange} style={{ width: '40%' }}>
<Option key="apple" label="Apple" value="apple" />
<Option key="orange" label="Orange" value="orange" />
<Option key="banana" label="Banana" value="banana" />
</Select>
);
};
const { getByDisplayValue, getByText } = render(<SingleSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 鼠标点击input,popup出现,且展示options
fireEvent.click(getByDisplayValue('Apple'));
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
// 点击Banana选项,input展示该选项,且popup消失
fireEvent.click(getByText('Banana'));
const selectElement = await waitFor(() => document.querySelector('.t-input__inner'));
expect(selectElement).toHaveValue('Banana');
setTimeout(async () => {
const popupElement3 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement3).not.toBeNull();
expect(popupElement3).toHaveStyle({
display: 'none',
});
}, 0);
});
});
test('多选测试', async () => {
await act(async () => {
const MultipleSelect = () => {
const [value, setValue] = useState([{ label: 'Apple', value: 'apple' }]);
const onChange = (value) => {
setValue(value);
};
return (
<Select value={value} onChange={onChange} multiple style={{ width: '40%' }} valueType="object">
<Option key="apple" label="Apple" value="apple" />
<Option key="orange" label="Orange" value="orange" />
<Option key="banana" label="Banana" value="banana" />
</Select>
);
};
const { getByText } = render(<MultipleSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 鼠标点击input,popup出现,且展示options
fireEvent.click(getByText('Apple'));
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
// 点击Banana和Orange选项,input展示Apple、Banana、Orange选项,popup依然展示
fireEvent.click(getByText('Banana'));
// @fix: This could be because the text is broken up by multiple elements.
fireEvent.click(getByText('Orange'));
const selectElement = await waitFor(() => document.querySelector(selectSelector));
expect(selectElement).toHaveTextContent('Apple');
expect(selectElement).toHaveTextContent('Banana');
expect(selectElement).toHaveTextContent('Orange');
const popupElement3 = await waitFor(() => document.querySelector(selectSelector));
expect(popupElement3).not.toBeNull();
expect(popupElement3).toHaveStyle({
display: 'block',
});
});
});
test('分组选择器测试', async () => {
const OptionGroupSelect = () => {
const [value, setValue] = useState('apple');
const onChange = (value) => {
setValue(value);
};
return (
<Select value={value} onChange={onChange} style={{ width: '40%' }}>
<OptionGroup label="Fruit">
{options.map((item, index) => (
<Option label={item.label} value={item.value} key={index} />
))}
</OptionGroup>
</Select>
);
};
await act(async () => {
const { getByText, getByDisplayValue } = render(<OptionGroupSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 鼠标点击input,popup出现,且展示options
const selectElement = await waitFor(() => document.querySelector(selectSelector));
fireEvent.click(getByDisplayValue('Apple'));
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Fruit');
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
// 点击Banana选项,input展示该选项,且popup消失
fireEvent.click(getByText('Banana'));
expect(document.querySelector('.t-input__inner')).toHaveValue('Banana');
setTimeout(async () => {
const popupElement3 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement3).not.toBeNull();
expect(popupElement3).toHaveStyle({
display: 'none',
});
}, 0);
});
});
test('可过滤选择器测试', async () => {
await act(async () => {
const FilterableSelect = () => {
const [value, setValue] = useState();
const onChange = (value) => {
setValue(value);
};
return (
<Select filterable value={value} onChange={onChange}>
{options.map((item, index) => (
<Option key={index} label={item.label} value={item.value} />
))}
</Select>
);
};
render(<FilterableSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 输入“an”, input展示“an”,popup展示Banana和Orange选项
const input = await waitFor(() => document.querySelector('input'));
fireEvent.change(input, { target: { value: 'an' } });
setTimeout(async () => {
expect(input).toHaveTextContent('an');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
}, 0);
// 输入“an1”, input展示“an1”,popup展示“无数据”
const input1 = await waitFor(() => document.querySelector('input'));
fireEvent.change(input1, { target: { value: 'an1' } });
setTimeout(async () => {
expect(input).toHaveTextContent('an1');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('无数据');
}, 0);
});
});
test('远程搜索测试', async () => {
await act(async () => {
render(<RemoteSearchSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 输入“123”, input展示“123”,popup展示123_test1、123_test2、123_test3
const input = await waitFor(() => document.querySelector('input'));
fireEvent.change(input, { target: { value: '123' } });
setTimeout(async () => {
expect(input).toHaveTextContent('123');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('123_test1');
expect(popupElement2).toHaveTextContent('123_test2');
expect(popupElement2).toHaveTextContent('123_test3');
}, 0);
// 清空input,popup展示Apple、Orange、Banana
fireEvent.change(input, { target: { value: '' } });
setTimeout(async () => {
expect(input).toHaveTextContent('');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
}, 0);
});
});
test('远程搜索多选测试', async () => {
await act(async () => {
const { getByText } = render(<RemoteSearchSelect multiple />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 输入“123”, input展示“123”,popup展示123_test1、123_test2、123_test3
const input = await waitFor(() => document.querySelector('input'));
fireEvent.change(input, { target: { value: '123' } });
setTimeout(async () => {
expect(input).toHaveTextContent('123');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).toHaveTextContent('123_test1');
expect(popupElement2).toHaveTextContent('123_test2');
expect(popupElement2).toHaveTextContent('123_test3');
// 选择123_test1,展示对应tag
fireEvent.click(getByText('123_test1'));
const selectElement = await waitFor(() => document.querySelector(selectSelector));
expect(selectElement).toHaveTextContent('123_test1');
}, 0);
// 清空input,popup展示Apple、Orange、Banana
fireEvent.change(input, { target: { value: '' } });
setTimeout(async () => {
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
fireEvent.click(getByText('Apple'));
// 已选的123_test1仍然保留
const selectElement = await waitFor(() => document.querySelector(selectSelector));
expect(selectElement).toHaveTextContent('123_test1');
expect(selectElement).toHaveTextContent('Apple');
}, 0);
});
});
});
|
export const SYMBOLS = {
r_init_vm: {
parameters: [],
result: "void",
},
r_release_vm: {
parameters: [],
result: "void",
},
r_load: {
parameters: ["pointer"],
result: "void",
},
r_call: {
parameters: ["pointer", "pointer"],
result: "void",
},
r_c: {
parameters: ["i32", "pointer"],
result: "pointer",
},
Rf_ScalarInteger: {
parameters: ["i32"],
result: "pointer",
},
Rf_allocVector: {
parameters: ["i32", "i32"],
result: "pointer",
},
Rf_allocList: {
parameters: ["i32"],
result: "pointer",
},
R_PreserveObject: {
parameters: ["pointer"],
result: "pointer",
},
SET_VECTOR_ELT: {
parameters: ["pointer", "i32", "pointer"],
result: "pointer",
},
SET_INTEGER_ELT: {
parameters: ["pointer", "i32", "i32"],
result: "void",
},
SET_STRING_ELT: {
parameters: ["pointer", "i32", "pointer"],
result: "void",
},
Rf_protect: {
parameters: ["pointer"],
result: "pointer",
},
Rf_mkCharLen: {
parameters: ["pointer", "u32"],
result: "pointer",
},
} as const;
|
package com.ims.coursedetails;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@Entity
@Table(name = "coursedescription")
@NoArgsConstructor
@ToString
public class CourseDescription {
public CourseDescription(int id, String keyfeature, String duration, int imgid) {
super();
this.descriptionid = id;
this.keyfeature = keyfeature;
this.duration = duration;
this.imgid = imgid;
}
@Id
@Column(name = "descriptionid")
@GeneratedValue
private Integer descriptionid;
@Column(name = "keyfeature")
private String keyfeature;
@Column(name = "duration")
private String duration;
@Column(name = "imgid")
private Integer imgid;
}
|
import "bootstrap/dist/css/bootstrap.css";
import notification from "./components/notification.vue";
import "./pusher.min.js"
var app = new Vue({
el: "#app",
components: {
"notification": notification,
},
data:{
"broadcast": null
},
template:'{{ broadcast }}'
})
Pusher.logToConsole = true;
var pusher = new Pusher('408cd422417d5833d90d', {
cluster: 'ap3',
encrypted: true
});
// app.broadcast = null;
var channel = pusher.subscribe('article-channel' + $('#userId').val());
channel.bind('App\\Events\\SendMessage', function(data) {
app.broadcast = data.broadcast;
});
|
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
sub IsOpen {
my $char = shift;
return 1 if ($char eq 'b' or $char eq 'c' or $char eq 'd' or $char eq 'e' or $char eq 'f');
return 0;
}
my $inputfile = shift;
if (!defined($inputfile)) {
$inputfile = 'sample1.txt';
}
open(my $fh, '<', $inputfile) or die "Couldn't open $inputfile: $!";
my $code = <$fh>;
close($fh);
$code =~ s/\R//g;
my @paths = ();
my @states = ([0, 0, '']);
while (0 < scalar(@states)) {
my ($x, $y, $pathSoFar) = @{shift(@states)};
if ($x == 3 and $y == 3) {
push(@paths, $pathSoFar);
next;
}
my $digest = md5_hex($code . $pathSoFar);
my @chars = split(//, $digest);
# Up
if ($y > 0 && IsOpen($chars[0])) {
push(@states, [$x, $y - 1, $pathSoFar . 'U']);
}
# Down
if ($y < 3 && IsOpen($chars[1])) {
push(@states, [$x, $y + 1, $pathSoFar . 'D']);
}
# Left
if ($x > 0 && IsOpen($chars[2])) {
push(@states, [$x - 1, $y, $pathSoFar . 'L']);
}
# Right
if ($x < 3 && IsOpen($chars[3])) {
push(@states, [$x + 1, $y, $pathSoFar . 'R']);
}
}
my @sortedPaths = sort { length($b) <=> length($a) } @paths;
my $shortestLength = length($sortedPaths[-1]);
print "Shortest path length: $shortestLength ($sortedPaths[-1])\n";
my $longestLength = length($sortedPaths[0]);
print "Longest path length: $longestLength ($sortedPaths[0])\n";
|
// deno run --allow-all scrape.ts <UqZBpD3n> <jlinksessionidx> <quarter>
import { join as joinPath } from 'https://deno.land/std@0.125.0/path/mod.ts'
import { ExamCodes, InstructionCodes } from './meeting-types.ts'
import { Period, Time } from './util/time.ts'
export type RawSearchLoadSubjectResult = {
LONG_DESC: string
SUBJECT_CODE: string
}
export type RawSearchLoadDepartmentResult = {
DEP_CODE: string
DEP_DESC: string
}
export type RawSearchByAllResult = {
UNIT_TO: number
SUBJ_CODE: string
UNIT_INC: number
CRSE_TITLE: string
UNIT_FROM: number
CRSE_CODE: string
}
type CommonRawSectionResult = {
END_MM_TIME: number
LONG_DESC: string
BEGIN_HH_TIME: number
PRIMARY_INSTR_FLAG: 'Y' | ' '
ROOM_CODE: string
END_HH_TIME: number
START_DATE: string
DAY_CODE: string
BEGIN_MM_TIME: number
PERSON_FULL_NAME: string
FK_SPM_SPCL_MTG_CD: ' ' | 'TBA' | ExamCodes
BLDG_CODE: string
FK_CDI_INSTR_TYPE: InstructionCodes
SECT_CODE: string
}
export interface RawSearchLoadGroupDataResult extends CommonRawSectionResult {
SCTN_CPCTY_QTY: number
SCTN_ENRLT_QTY: number
SECTION_NUMBER: string
SECTION_START_DATE: string
STP_ENRLT_FLAG: 'Y' | 'N'
SECTION_END_DATE: string
COUNT_ON_WAITLIST: number
BEFORE_DESC: ' ' | 'AC' | 'NC'
PRINT_FLAG: ' ' | 'N' | 'Y' | '5'
FK_SST_SCTN_STATCD: 'AC' | 'NC' | 'CA'
AVAIL_SEAT: number
}
export interface RawGetClassResult extends CommonRawSectionResult {
TERM_CODE: string
SECT_CREDIT_HRS: number
SECTION_NUMBER: number
SUBJ_CODE: string
GRADE_OPTN_CD_PLUS: ' ' | '+'
WT_POS: string
FK_PCH_INTRL_REFID: number
CRSE_TITLE: string
GRADE_OPTION: 'L' | 'P' | 'P/NP' | 'S' | 'S/U' | 'H' | ' '
CRSE_CODE: string
NEED_HEADROW: boolean
PERSON_ID: string
SECT_CREDIT_HRS_PL: ' ' | '+'
SECTION_HEAD: number
ENROLL_STATUS: 'EN' | 'WT' | 'PL'
FK_SEC_SCTN_NUM: number
}
type ScraperOptions = {
/** The `jlinksessionidx` cookie */
jlinksessionidx?: string
/** The `UqZBpD3n` cookie */
UqZBpD3n?: string
/** The path to cache WebReg response data in */
cachePath?: string | null
}
/** Scrapes courses and sections from WebReg. */
export class Scraper {
#term: string
#sessionIndex?: string
#uqz?: string
#cachePath: string | null
constructor (
term: string,
{ jlinksessionidx, UqZBpD3n, cachePath = null }: ScraperOptions = {}
) {
this.#term = term
this.#sessionIndex = jlinksessionidx
this.#uqz = UqZBpD3n
this.#cachePath = cachePath
}
async get (path: string, query: Record<string, string>) {
const fileName =
query.subjcode?.length > 0
? `${path}_${query.subjcode.trim()}_${query.crsecode.trim()}`
: path
if (this.#cachePath !== null) {
const json = await Deno.readTextFile(
joinPath(this.#cachePath, `${fileName}.json`)
)
.then(JSON.parse)
.catch((error: unknown) =>
error instanceof Deno.errors.NotFound ? null : Promise.reject(error)
)
if (json !== null) {
return json
}
}
const json = await fetch(
`https://act.ucsd.edu/webreg2/svc/wradapter/secure/${path}?${new URLSearchParams(
query
)}`,
{
headers: {
Cookie: `jlinksessionidx=${this.#sessionIndex}; UqZBpD3n=${this.#uqz}`
}
}
).then(response =>
response.ok
? response.json()
: Promise.reject(`HTTP ${response.status} error from ${response.url}`)
)
if (json?.[0]?.VERIFY === 'FAIL') {
throw new Error(
'WebReg returned VERIFY: FAIL. Was the quarter selected on WebReg?'
)
}
if (this.#cachePath !== null) {
await Deno.writeTextFile(
joinPath(this.#cachePath, `${fileName}.json`),
JSON.stringify(json, null, '\t') + '\n'
)
}
return json
}
/**
* Lists all subjects.
*/
subjects (): Promise<RawSearchLoadSubjectResult[]> {
return this.get('search-load-subject', { termcode: this.#term })
}
/**
* Lists all departments.
*/
departments (): Promise<RawSearchLoadDepartmentResult[]> {
return this.get('search-load-department', { termcode: this.#term })
}
/**
* Lists all courses.
*/
courses ({
subjcode = '',
crsecode = '',
department = '',
professor = '',
title = '',
levels = '',
days = '',
timestr = '',
opensection = false,
isbasic = true,
basicsearchvalue = ''
} = {}): Promise<RawSearchByAllResult[]> {
return this.get('search-by-all', {
subjcode,
crsecode,
department,
professor,
title,
levels,
days,
timestr,
opensection: opensection.toString(),
isbasic: isbasic.toString(),
basicsearchvalue,
termcode: this.#term
})
}
/**
* Lists all sections for a course.
*
* @param subject and
* @param course should be padded strings, such as from
* `RawSearchByAllResult`'s `SUBJ_CODE` and `CRSE_CODE` properties.
*/
sections (
subject: string,
course: string
): Promise<RawSearchLoadGroupDataResult[]> {
return this.get('search-load-group-data', {
subjcode: subject.padEnd(4, ' '),
crsecode: course.padEnd(5, ' '),
termcode: this.#term
})
}
/**
* Gets a `Course` object.
*
* @param subject The subject code; can be trimmed.
* @param course The course code; can be trimmed.
* @param rawCourses A list of raw courses from `courses()`. If omitted, it'll
* call the `courses()` method for you.
*/
async getCourse (
subject: string,
course: string,
rawCourses?: RawSearchByAllResult[]
): Promise<Course> {
rawCourses ??= await this.courses()
const rawCourse = rawCourses.find(
rawCourse =>
rawCourse.SUBJ_CODE.trim() === subject &&
rawCourse.CRSE_CODE.trim() === course
)
if (!rawCourse) {
throw new ReferenceError(`Could not find course ${subject} ${course}.`)
}
return new Course(
rawCourse,
await this.sections(rawCourse.SUBJ_CODE, rawCourse.CRSE_CODE)
)
}
/**
* Same as `allCourses` except it also yields a number from 0 to 1 with the
* estimated progress.
*/
async * allCoursesWithProgress () {
const courses = await this.courses()
for (const [i, course] of courses.entries()) {
const groups = await this.sections(course.SUBJ_CODE, course.CRSE_CODE)
yield {
course: new Course(course, groups),
progress: (i + 1) / courses.length
}
}
}
/**
* Gets all the course and section data from WebReg. Yields a `Course` as
* sections are loaded for each course.
*/
async * allCourses () {
for await (const { course } of this.allCoursesWithProgress()) {
yield course
}
}
/**
* Gest the user's schedule.
*/
schedule (
scheduleName = 'My Schedule',
{ final = '', sectnum = '' } = {}
): Promise<RawGetClassResult[]> {
return this.get('get-class', {
schedname: scheduleName,
final,
sectnum,
termcode: this.#term
})
}
/**
* Gets the user's schedule with the given name. Defaults to `My Schedule`.
* Unlike `schedule`, this method processes the raw schedule sections as
* `ScheduleSection`s.
*/
getSchedule (name?: string) {
return this.schedule(name).then(sections =>
sections.map(section => new ScheduleSection(section))
)
}
}
/**
* An instructor.
*/
export class Instructor {
/** Includes the middle initial. */
firstName: string
surname: string
pid: string
constructor (name: string, pid: string) {
;[this.surname, this.firstName] = name.split(', ').map(part => part.trim())
this.pid = pid
}
get firstLast () {
return `${this.firstName} ${this.surname}`
}
get lastFirst () {
return `${this.surname}, ${this.firstName}`
}
}
class BaseGroup<Raw extends CommonRawSectionResult> {
/** The section code, such as "A07." */
code: string
/**
* The start and end time and days of the week of the meeting, or null if
* TBA.
*
* Also contains the building and room number because if the time is TBA, so is the room number.
*/
time: {
start: Time
end: Time
/** The days of the week on which the meeting meets. */
days: number[]
/**
* The location of the meeting, or null if TBA.
*/
location: {
building: string
room: string
} | null
} | null
/**
* List of instructors. If empty, then the section is taught by "Staff."
*/
instructors: Instructor[]
/**
* Distinguishes between midterms and finals. `null` if not an exam (i.e. a
* normal, regular meeting). Refer to [this
* table](https://registrar.ucsd.edu/StudentLink/instr_codes.html) for a key.
*/
examType: ExamCodes | null
/**
* Distinguishes between lectures and discussions. Refer to [this
* table](https://registrar.ucsd.edu/StudentLink/instr_codes.html) for a key.
*/
instructionType: InstructionCodes
raw: Raw
constructor (rawGroup: Raw) {
const {
SECT_CODE,
BLDG_CODE,
ROOM_CODE,
PERSON_FULL_NAME,
FK_SPM_SPCL_MTG_CD,
FK_CDI_INSTR_TYPE,
BEGIN_HH_TIME,
BEGIN_MM_TIME,
END_HH_TIME,
END_MM_TIME,
DAY_CODE
} = rawGroup
// Unused: { LONG_DESC, PRIMARY_INSTR_FLAG, START_DATE }
this.code = SECT_CODE
this.time =
DAY_CODE === ' '
? null
: {
start: new Time(BEGIN_HH_TIME, BEGIN_MM_TIME),
end: new Time(END_HH_TIME, END_MM_TIME),
days: DAY_CODE.split('').map(day => +day),
location:
BLDG_CODE === 'TBA' && ROOM_CODE === 'TBA'
? null
: {
building: BLDG_CODE.trim(),
room: ROOM_CODE.trim()
}
}
this.instructors =
PERSON_FULL_NAME === 'Staff; '
? []
: PERSON_FULL_NAME.split(':').map(instructor => {
const [name, pid] = instructor.split(';')
return new Instructor(name, pid)
})
this.examType =
FK_SPM_SPCL_MTG_CD === ' ' || FK_SPM_SPCL_MTG_CD === 'TBA'
? null
: FK_SPM_SPCL_MTG_CD
this.instructionType = FK_CDI_INSTR_TYPE
this.raw = rawGroup
}
/**
* Whether the meeting is special and only happens on scheduled days rather
* than regularly, such as a midterm or final.
*/
isExam (): boolean {
return this.examType !== null
}
/**
* Returns the letter of the section code (e.g. the `A` in `A00`), or null if
* the section is a three-digit number. You can use this to determine whether
* the section code is numerical.
*/
codeLetter (): string | null {
return this.code.match(/^[A-Z]/)?.[0] ?? null
}
/**
* Gets the time ranges during which the section meets. Returns null if TBA.
*/
times (): Period[] | null {
const time = this.time
if (!time) {
return null
}
return time.days.map(day => new Period(day, time.start, time.end))
}
/**
* Determines whether this meeting conflicts with other meetings or times.
*
* TBA times are not considered a conflict.
*/
intersects (
targetTimes: BaseGroup<any> | (BaseGroup<any> | Period)[] | Period | null
) {
const meetingTimes = this.times()
if (meetingTimes === null || targetTimes === null) {
// TBA times are not considered a conflict
return false
}
// Normalize input to an array of Periods
const times = (
Array.isArray(targetTimes) ? targetTimes : [targetTimes]
).flatMap(meetingOrPeriod =>
meetingOrPeriod instanceof Period
? [meetingOrPeriod]
: meetingOrPeriod.times() ?? []
)
// Return whether any of `meetingTimes` intersects with any of `times`
return meetingTimes.some(meetingTime =>
times.some(time => meetingTime.intersects(time))
)
}
/**
* Returns the exam type (e.g. final vs midterm) if the meeting is an exam;
* otherwise, the normal meeting type (e.g. discussion vs lecture).
*/
get type (): ExamCodes | InstructionCodes {
return this.examType || this.instructionType
}
}
export class Group extends BaseGroup<RawSearchLoadGroupDataResult> {
/** The maximum number of seats. May be Infinity for no limit. */
capacity: number
/** The number of people enrolled. */
enrolled: number
/** The number of people on the waitlist. */
waitlist: number
/**
* Whether enrolment has been stopped. This isn't the only determiner of
* whether a course can be enrolled rather than waitlisted.
*/
stopEnrolment: boolean
/** Whether the section has been cancelled. */
cancelled: boolean
/**
* Whether the section can be planned. The difference between this and `full`
* is that some sections, such as lectures or finals, aren't selectable as
* plannable/enrollable/waitlistable sections. This should reflect whether the
* "Plan" and "Enroll"/"Waitlist" buttons are shown in the section's row on
* WebReg.
*/
plannable: boolean
/**
* Whether the section can be enrolled directly. This should reflect whether
* the button says "Enroll" (true) or "Waitlist" (false) on WebReg. False if
* `plannable` is false.
*/
enrollable: boolean
constructor (rawGroup: RawSearchLoadGroupDataResult) {
super(rawGroup)
const {
SCTN_CPCTY_QTY,
SCTN_ENRLT_QTY,
COUNT_ON_WAITLIST,
STP_ENRLT_FLAG,
FK_SST_SCTN_STATCD
} = rawGroup
// Unused: {
// AVAIL_SEAT,
// BEFORE_DESC,
// PRINT_FLAG,
// SECTION_END_DATE,
// SECTION_NUMBER,
// SECTION_START_DATE
// }
this.capacity = SCTN_CPCTY_QTY === 9999 ? Infinity : SCTN_CPCTY_QTY
this.enrolled = SCTN_ENRLT_QTY
this.waitlist = COUNT_ON_WAITLIST
this.stopEnrolment = STP_ENRLT_FLAG === 'Y'
this.cancelled = FK_SST_SCTN_STATCD === 'CA'
this.plannable = FK_SST_SCTN_STATCD === 'AC' && !this.isExam()
this.enrollable =
this.plannable && this.enrolled < this.capacity && !this.stopEnrolment
}
}
export type LetterGroup = {
/** Plannable sections */
plannables: Group[]
/** Other meetings */
otherMeetings: Group[]
/** Mapping of the exam type to the exam meeting */
exams: Partial<Record<ExamCodes, Group>>
}
export type CourseUnit = {
from: number
to: number
step: number
}
export class Course {
/** The subject code, such as "CSE." */
subject: string
/** The course code, such as "8B." */
course: string
/** The name of the course. */
title: string
/** The unit range that one can take the course for. */
unit: CourseUnit
/** List of meetings, including discussions and finals. */
groups: Group[]
raw: RawSearchByAllResult
constructor (
rawCourse: RawSearchByAllResult,
rawGroups: RawSearchLoadGroupDataResult[]
) {
this.subject = rawCourse.SUBJ_CODE.trim()
this.course = rawCourse.CRSE_CODE.trim()
this.title = rawCourse.CRSE_TITLE.trim()
this.unit = {
from: rawCourse.UNIT_FROM,
to: rawCourse.UNIT_TO,
step: rawCourse.UNIT_INC
}
this.groups = rawGroups.map(group => new Group(group))
this.raw = rawCourse
}
/**
* Display `<SUBJ> <CRSE>`, e.g. `CSE 11`.
*/
get code () {
return `${this.subject} ${this.course}`
}
/**
* A list of sections grouped by letter (e.g. the A in A01), separated by
* plannable sections (of which you would only choose one) and all the other
* meetings associated with the letter.
*/
letters (): LetterGroup[] {
/**
* Mapping of a letter (e.g. the A in A01) to a list of sections associated
* with the letter.
*/
const letterGroups: Record<string, LetterGroup> = {}
for (const meeting of this.groups) {
if (meeting.isExam()) {
continue
}
// Numerical section codes are individual
const letter = meeting.codeLetter() ?? meeting.code
letterGroups[letter] ??= {
plannables: [],
otherMeetings: [],
exams: {}
}
if (meeting.examType !== null) {
letterGroups[letter].exams[meeting.examType] = meeting
} else if (meeting.plannable) {
letterGroups[letter].plannables.push(meeting)
} else {
letterGroups[letter].otherMeetings.push(meeting)
}
}
return Object.values(letterGroups)
}
}
const gradeScaleKey = {
L: 'L',
P: 'P/NP',
'P/NP': 'P/NP',
S: 'S/U',
'S/U': 'S/U',
H: 'H',
' ': null
} as const
export class ScheduleSection extends BaseGroup<RawGetClassResult> {
course: {
subject: string
course: string
title: string
unit: number
canChangeUnit: boolean
gradeScale: typeof gradeScaleKey[keyof typeof gradeScaleKey]
canChangeGradeScale: boolean
}
state:
| { type: 'enrolled' }
| { type: 'waitlisted'; position: number }
| { type: 'planned' }
constructor (rawClass: RawGetClassResult) {
super(rawClass)
const {
SUBJ_CODE,
CRSE_CODE,
CRSE_TITLE,
SECT_CREDIT_HRS,
SECT_CREDIT_HRS_PL,
GRADE_OPTION,
GRADE_OPTN_CD_PLUS,
ENROLL_STATUS,
WT_POS
} = rawClass
// Unused: {
// FK_PCH_INTRL_REFID,
// FK_SEC_SCTN_NUM,
// NEED_HEADROW,
// PERSON_ID,
// SECTION_HEAD,
// SECTION_NUMBER,
// TERM_CODE
// }
this.course = {
subject: SUBJ_CODE.trim(),
course: CRSE_CODE.trim(),
title: CRSE_TITLE.trim(),
unit: SECT_CREDIT_HRS,
canChangeUnit: SECT_CREDIT_HRS_PL === '+',
gradeScale: gradeScaleKey[GRADE_OPTION],
canChangeGradeScale: GRADE_OPTN_CD_PLUS === '+'
}
this.state =
ENROLL_STATUS === 'WT'
? { type: 'waitlisted', position: +WT_POS }
: { type: ENROLL_STATUS === 'EN' ? 'enrolled' : 'planned' }
}
}
if (import.meta.main) {
const [UqZBpD3n, jlinksessionidx, quarter] = Deno.args
const getter = new Scraper(quarter, {
jlinksessionidx,
UqZBpD3n,
cachePath: 'cache-' + quarter.toLowerCase()
})
const courses = []
const freq: Record<number, number> = {}
let count = 0
for await (const course of getter.allCourses()) {
courses.push(course)
for (const group of course.groups) {
freq[group.raw.DAY_CODE.length] ??= 0
freq[group.raw.DAY_CODE.length]++
if (!group.isExam() && group.time?.location?.building === '') {
// console.log(`${course.code} ${group.code} ${group.time.location.room}`)
}
if (!group.isExam() && group.time?.location?.building !== 'RCLAS') {
count++
}
}
}
console.log(freq, count)
// idk
}
|
<?php
use Validator\Collection;
it('can add array using __construct', function () {
$collection = new Collection(['key' => 'value']);
expect($collection)->key->toEqual('value');
});
it('can add array using make', function () {
expect(Collection::make(['key' => 'value']))->key->toEqual('value');
});
it('can add array using replace', function () {
$collection = new Collection();
expect($collection)
->replace(['key' => 'value'])
->key->toEqual('value');
});
it('can add array using set', function () {
$collection = new Collection();
expect($collection)
->set('key', 'value')
->key->toEqual('value');
});
it('can edit exist array using set', function () {
$collection = new Collection(['key' => 'value']);
expect($collection)
->set('key', 'new value')
->key->toEqual('new value');
});
it('can add array using __set', function () {
$collection = new Collection();
$collection->key = 'value';
expect($collection)
->key->toEqual('value');
});
it('can edit exist array using __set', function () {
$collection = new Collection(['key' => 'value']);
$collection->key = 'new value';
expect($collection)
->key->toEqual('new value');
});
|
import { ErrorReponse } from "./models";
export class APIError extends Error {
constructor(private _res: Response, private _body?: ErrorReponse) {
super(_body?.error ?? "unknown");
}
get response() {
return this._res;
}
get status() {
return this._res.status;
}
get code() {
return this._body?.code ?? 0;
}
}
|
# start_dev.sh
export FLASK_APP=wsgi.py
export FLASK_DEBUG=1
export FLASK_ENV=development
flask run --host='0.0.0.0'
|
package com.example;
public class App {
private final String message;
public App() {
this.message = "Hello World!";
}
public String getMessage() {
for(int i = 0; i < 10; i++) {
System.out.println("");
}
return this.message;
}
public static void main(String[] args) {
System.out.println(new App().getMessage());
}
}
|
#!/bin/bash
if [ -z $1 ];
then
echo 'Input named volume'
exit 0
fi
docker volume ls -q | grep -x $1
if [ $? -ne 0 ];
then
echo -e "\033[00;31m ERROR! Volume $1 not found \033[0m"
echo "List of docker volumes: "
docker volume ls -q | grep $1i
exot 0
fi
# exit 0
VOLUME_NAME=$1
CURRENT_DATETIME=$(date '+%Y-%m-%d_%H-%M-%S')
EXPORT_DIR="${VOLUME_NAME}-${CURRENT_DATETIME}"
mkdir ${EXPORT_DIR}
docker run --rm -it -v $(readlink -f ${EXPORT_DIR}):/tmp/export/data \
-v ${VOLUME_NAME}:/tmp/export/volume ubuntu \
/bin/bash -c "cd /tmp/export/volume \
&& tar -czvf /tmp/export/data/data.tar.gz . "
|
// Copyright (c) 2018-present, GM Cruise LLC
//
// This source code is licensed under the Apache License, Version 2.0,
// found in the LICENSE file in the root directory of this source tree.
// You may not use this file except in compliance with the License.
import { useAnimationFrame } from "@cruise-automation/hooks";
import { quat, vec3 } from "gl-matrix";
import last from "lodash/last";
import remove from "lodash/remove";
import sample from "lodash/sample";
import polygonGenerator from "polygon-generator";
import React, { useRef, useState, useCallback, useEffect } from "react";
import Worldview, {
Command,
Arrows,
Cones,
Cubes,
Cylinders,
Grid,
Lines,
Points,
Spheres,
Triangles,
Axes,
FilledPolygons,
DrawPolygons,
PolygonBuilder,
Overlay,
Text,
GLText,
GLTFScene,
DEFAULT_CAMERA_STATE,
withPose,
getCSSColor,
intToRGB,
cameraStateSelectors,
getRayFromClick,
} from "regl-worldview";
import seedrandom from "seedrandom";
import styled from "styled-components";
import { getHashUrlByComponentName } from "../../routes";
import CameraStateInfo from "./CameraStateInfo";
import cesiumManModel from "./CesiumMan.glb";
import CodeEditor from "./CodeEditor";
import { inScreenshotTests } from "./codeSandboxUtils";
import InputNumber from "./InputNumber";
import LineControls from "./LineControls";
import LinesWithClickableInterior from "./LinesWithClickableInterior";
import useRange from "./useRange";
import duckModel from "common/fixtures/Duck.glb"; // Webpack magic: we actually import a URL pointing to a .glb file
// Add required packages and files for all examples to run
const CODE_SANDBOX_CONFIG = {
dependencies: {
react: "latest",
"react-dom": "latest",
"regl-worldview": "latest",
"@cruise-automation/hooks": "latest",
seedrandom: "latest",
"polygon-generator": "latest",
"styled-components": "latest",
},
files: {
"common/fixtures/Duck.glb": {
content: "https://uploads.codesandbox.io/uploads/user/dfcf1de7-30d4-4c5b-9675-546a91ea8afb/Zb-T-Duck.glb",
isBinary: true,
},
"utils/codeSandboxStyleFix.css": {
content: require("!!raw-loader!./codeSandboxStyleFix.css"),
},
"utils/CameraStateInfo.js": {
content: require("!!raw-loader!./CameraStateInfo.js"),
},
"utils/CesiumMan.glb": {
content: "https://uploads.codesandbox.io/uploads/user/dfcf1de7-30d4-4c5b-9675-546a91ea8afb/04aB-CesiumMan.glb",
isBinary: true,
},
"utils/LinesWithClickableInterior.js": {
content: require("!!raw-loader!./LinesWithClickableInterior.js"),
},
"utils/useRange.js": {
content: require("!!raw-loader!./useRange.js"),
},
"utils/InputNumber.js": {
content: require("!!raw-loader!./InputNumber.js"),
},
"utils/Switch.js": {
content: require("!!raw-loader!./Switch.js"),
},
"utils/codeSandboxUtils.js": {
content: require("!!raw-loader!./codeSandboxUtils.js"),
},
"utils/theme.js": {
content: require("!!raw-loader!./theme.js"),
},
"utils/LineControls.js": {
content: require("!!raw-loader!./LineControls.js"),
},
},
};
export const scope = {
quat,
vec3,
intToRGB,
cameraStateSelectors,
getCSSColor,
useRange,
useAnimationFrame,
useCallback,
useRef,
useState,
useEffect,
Worldview,
seedrandom,
last,
remove,
sample,
inScreenshotTests,
polygonGenerator,
styled,
DEFAULT_CAMERA_STATE,
CameraStateInfo,
LineControls,
LinesWithClickableInterior,
InputNumber,
Command,
Arrows,
Cones,
Cubes,
Cylinders,
Grid,
Lines,
Points,
Spheres,
Triangles,
Axes,
FilledPolygons,
DrawPolygons,
PolygonBuilder,
Overlay,
Text,
GLText,
GLTFScene,
withPose,
getRayFromClick,
duckModel,
cesiumManModel,
};
export default function WorldviewCodeEditor({
scope: customScope = {},
componentName,
code,
nonEditableCode = "",
insertCodeSandboxStyle,
noInline,
...rest
}) {
const hashUrl = getHashUrlByComponentName(componentName);
const docUrl = `https://cruise-automation.github.io/webviz/worldview/#${hashUrl}`;
const copyCode = `${nonEditableCode}
${code}
`;
const render = noInline
? ""
: `
render(
<div className="App" style={{ width: "100vw", height: "100vh" }}>
<Example />
</div>
);
`;
const codeSandboxCode = `
// regl-worldview example: ${componentName}
// docs: ${docUrl}
${insertCodeSandboxStyle ? 'import "./utils/codeSandboxStyleFix.css"; // #CODE_SANDBOX_ONLY' : ""}
import ReactDOM from "react-dom";
${nonEditableCode}
function render(content) {
ReactDOM.render(content, document.getElementById("root"));
}
${code}
${render}
`;
return (
<CodeEditor
scope={{ ...customScope, ...scope }}
{...rest}
noInline={noInline}
codeSandboxConfig={CODE_SANDBOX_CONFIG}
codeSandboxCode={codeSandboxCode}
code={code}
copyCode={copyCode}
nonEditableCode={nonEditableCode}
/>
);
}
|
import os
import jax
import jax.numpy as jnp
from jax import jit
import haiku as hk
import optax
import jmp
import time
from funlib.learn.jax.models import UNet, ConvPass
from typing import Tuple, Any, NamedTuple, Dict
'''To test model with some dummy input and output, run with command
`CUDA_VISIBLE_DEVICES=0 python unet_example.py`
for single device training, or
`CUDA_VISIBLE_DEVICES=0,1,2,3 python unet_example.py`
for multi-device training
'''
# PARAMETERS
mp_training = True # mixed-precision training using `jmp`
learning_rate = 0.5e-4
class Params(NamedTuple):
weight: jnp.ndarray
opt_state: jnp.ndarray
loss_scale: jmp.LossScale
# should be the same as gunpowder.jax.GenericJaxModel
# replicated here to reduce dependency
class GenericJaxModel():
def __init__(self):
pass
def initialize(self, rng_key, inputs, is_training):
raise RuntimeError("Unimplemented")
def forward(self, inputs):
raise RuntimeError("Unimplemented")
def train_step(self, inputs, pmapped):
raise RuntimeError("Unimplemented")
class Model(GenericJaxModel):
def __init__(self):
super().__init__()
# we encapsulate the UNet and the ConvPass in one hk.Module
# to make assigning precision policy easier
class MyModel(hk.Module):
def __init__(self, name=None):
super().__init__(name=name)
self.unet = UNet(
num_fmaps=24,
fmap_inc_factor=3,
downsample_factors=[[2,2,2],[2,2,2],[2,2,2]],
)
self.conv = ConvPass(
kernel_sizes=[[1,1,1]],
out_channels=3,
activation='sigmoid',
)
def __call__(self, x):
return self.conv(self.unet(x))
def _forward(x):
net = MyModel()
return net(x)
if mp_training:
policy = jmp.get_policy('p=f32,c=f16,o=f32')
else:
policy = jmp.get_policy('p=f32,c=f32,o=f32')
hk.mixed_precision.set_policy(MyModel, policy)
self.model = hk.without_apply_rng(hk.transform(_forward))
self.opt = optax.adam(learning_rate)
@jit
def _forward(params, inputs):
return {'affs': self.model.apply(params.weight, inputs['raw'])}
self.forward = _forward
@jit
def _loss_fn(weight, raw, gt, mask, loss_scale):
pred_affs = self.model.apply(weight, x=raw)
loss = optax.l2_loss(predictions=pred_affs, targets=gt)
loss = loss*2*mask # optax divides loss by 2 so we mult it back
loss_mean = loss.mean(where=mask)
return loss_scale.scale(loss_mean), (pred_affs, loss, loss_mean)
@jit
def _apply_optimizer(params, grads):
updates, new_opt_state = self.opt.update(grads, params.opt_state)
new_weight = optax.apply_updates(params.weight, updates)
return new_weight, new_opt_state
def _train_step(params, inputs, pmapped=False) -> Tuple[Params, Dict[str, jnp.ndarray], Any]:
raw, gt, mask = inputs['raw'], inputs['gt'], inputs['mask']
grads, (pred_affs, loss, loss_mean) = jax.grad(
_loss_fn, has_aux=True)(params.weight, raw, gt, mask,
params.loss_scale)
if pmapped:
# sync grads, casting to compute precision (f16) for efficiency
grads = policy.cast_to_compute(grads)
grads = jax.lax.pmean(grads, axis_name='num_devices')
grads = policy.cast_to_param(grads)
# dynamic mixed precision loss scaling
grads = params.loss_scale.unscale(grads)
new_weight, new_opt_state = _apply_optimizer(params, grads)
# if any update is non-finite, skip updates
grads_finite = jmp.all_finite(grads)
new_loss_scale = params.loss_scale.adjust(grads_finite)
new_weight, new_opt_state = jmp.select_tree(
grads_finite,
(new_weight, new_opt_state),
(params.weight, params.opt_state))
new_params = Params(new_weight, new_opt_state, new_loss_scale)
outputs = {'affs': pred_affs, 'grad': loss}
return new_params, outputs, loss_mean
self.train_step = _train_step
def initialize(self, rng_key, inputs, is_training=True):
weight = self.model.init(rng_key, inputs['raw'])
opt_state = self.opt.init(weight)
if mp_training:
loss_scale = jmp.DynamicLossScale(jmp.half_dtype()(2 ** 15))
else:
loss_scale = jmp.NoOpLossScale()
return Params(weight, opt_state, loss_scale)
def split(arr, n_devices):
"""Splits the first axis of `arr` evenly across the number of devices."""
return arr.reshape(n_devices, arr.shape[0] // n_devices, *arr.shape[1:])
def create_network():
# returns a model that Gunpowder `Predict` and `Train` node can use
return Model()
if __name__ == "__main__":
my_model = Model()
n_devices = jax.local_device_count()
batch_size = 4*n_devices
raw = jnp.ones([batch_size, 1, 132, 132, 132])
gt = jnp.zeros([batch_size, 3, 40, 40, 40])
mask = jnp.ones([batch_size, 3, 40, 40, 40])
inputs = {
'raw': raw,
'gt': gt,
'mask': mask,
}
rng = jax.random.PRNGKey(42)
# init model
if n_devices > 1:
# split input for pmap
raw = split(raw, n_devices)
gt = split(gt, n_devices)
mask = split(mask, n_devices)
single_device_inputs = {
'raw': raw,
'gt': gt,
'mask': mask,
}
rng = jnp.broadcast_to(rng, (n_devices,) + rng.shape)
model_params = jax.pmap(my_model.initialize)(rng, single_device_inputs)
else:
model_params = my_model.initialize(rng, inputs, is_training=True)
# test forward
y = jit(my_model.forward)(model_params, {'raw': raw})
assert y['affs'].shape == (batch_size, 3, 40, 40, 40)
# test train loop
for _ in range(10):
t0 = time.time()
if n_devices > 1:
model_params, outputs, loss = jax.pmap(
my_model.train_step,
axis_name='num_devices',
donate_argnums=(0,),
static_broadcasted_argnums=(2,))(
model_params, inputs, True)
else:
model_params, outputs, loss = jax.jit(
my_model.train_step,
donate_argnums=(0,),
static_argnums=(2,))(
model_params, inputs, False)
print(f'Loss: {loss}, took {time.time()-t0}s')
|
# frozen_string_literal: true
module JSONFactory
class JSONBuilder
BUILDER_VARIABLE_NAME = :json
TOKEN_LEFT_SQUARE_BRACKET = '['
TOKEN_RIGHT_SQUARE_BRACKET = ']'
TOKEN_LEFT_CURLY_BRACKET = '{'
TOKEN_RIGHT_CURLY_BRACKET = '}'
TOKEN_COLON = ':'
TOKEN_COMMA = ','
def initialize(io, type = :value)
@stack = [State.new(io, type)]
@cache = Cache.instance
@template_store = TemplateStore.instance
end
def value(value = nil)
raise TypeNotAllowedError, 'Can only add value as a value' unless type == :value
raise TypeNotAllowedError, 'Cannot add multiple values' unless count.zero?
add_value(value)
increment_count
end
def array
raise TypeNotAllowedError, 'Can only add array as a value' unless type == :value
raise TypeNotAllowedError, 'Cannot add multiple values' unless count.zero?
io << TOKEN_LEFT_SQUARE_BRACKET
push_type(:array) { yield } if block_given?
io << TOKEN_RIGHT_SQUARE_BRACKET
increment_count
end
def element(value = nil)
raise TypeNotAllowedError, 'Can only add an element within an array' unless type == :array
add_separator
if block_given?
push_type(:value) { yield }
else
add_value(value)
end
increment_count
end
def object
raise TypeNotAllowedError, 'Can only add object as a value' unless type == :value
raise TypeNotAllowedError, 'Cannot add multiple values' unless count.zero?
io << TOKEN_LEFT_CURLY_BRACKET
push_type(:object) { yield } if block_given?
io << TOKEN_RIGHT_CURLY_BRACKET
increment_count
end
def member(key, value = nil)
raise TypeNotAllowedError, 'Can only add a member within an object' unless type == :object
add_separator
io << Converter.json_key(key)
io << TOKEN_COLON
if block_given?
push_type(:value) { yield }
else
add_value(value)
end
increment_count
end
def cache(key)
value = @cache.fetch(key) do
cache_io = StringIO.new
push_io(cache_io) { yield }
cache_io.string
end
raise EmptyValueError if value.empty?
add_separator
io << value
increment_count
end
def evaluate(string, local_variables, filename)
dsl = DSL.new(self)
binding = jfactory(dsl)
local_variables.each_pair do |key, value|
binding.local_variable_set(key, value)
end
binding.local_variable_set(BUILDER_VARIABLE_NAME, dsl)
eval(string, binding, filename.to_s) # rubocop:disable Security/Eval
end
def render_template(filename, local_variables)
template = @template_store.get(filename)
evaluate(template, local_variables, filename)
end
alias partial render_template
def render_string(string, local_variables)
evaluate(string, local_variables, '(inline)')
end
private
def add_value(value)
io << Converter.json_value(value)
end
def add_separator
io << TOKEN_COMMA unless count.zero?
end
def io
@stack.last.io
end
def type
@stack.last.type
end
def count
@stack.last.count
end
def increment_count
@stack.last.count += 1
end
def push_io(io)
@stack.push(State.new(io, type))
yield
@stack.pop
end
def push_type(type)
@stack.push(State.new(io, type))
yield
raise EmptyValueError if type == :value && count.zero?
@stack.pop
end
end
end
JSONFactory::JSONBuilder.class_eval do
# Returns an empty evaluation context, similar to Ruby's main object.
def jfactory(__dsl__)
Object.allocate.instance_eval do
class << self
JSONFactory.configure.helpers.each { |mod| include mod }
def to_s
'jfactory'
end
alias inspect to_s
end
define_singleton_method(:__dsl__) do
__dsl__
end
def method_missing(method_name, *args, &block)
if __dsl__.respond_to?(method_name)
__dsl__.send(method_name, *args, &block)
else
super
end
end
return binding
end
end
private :jfactory
end
|
FactoryBot.define do
factory :expense do
amount { Faker::Commerce.price }
date { Faker::Date.backward(14) }
description { Faker::Lorem.words(rand(2..10)).join(' ') }
currency { 'HRK' }
expense_category
user
end
end
|
package io.flutter.plugins.batteryexample
import dev.flutter.plugins.e2e.E2EPlugin
import io.flutter.app.FlutterActivity
import io.flutter.plugins.battery.BatteryPlugin
class EmbeddingV1Activity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
}
}
|
import { EntityRepository, Repository } from 'typeorm';
import { City } from '../entity/city.entity';
@EntityRepository(City)
export class CityRepository extends Repository<City> {
async list(){
return this.createQueryBuilder("city")
.getMany()
}
}
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payement extends Model
{
protected $table = 'payements';
public $timestamps = false;
protected $fillable = array('montant', 'encaisseMois', 'numCheque','adherent_id','moyensPayement_id');
public function moyensPayement()
{
return $this->belongsTo('App\MoyenPayement', 'moyenPayement_id');
}
public function adherent()
{
return $this->belongsTo('App\Adherent', 'adherent_id');
}
}
|
# frozen_string_literal: true
module Resolvers
class AdminDailyStatisticConnectionResolver < AdminBaseResolver
argument :start_date, String, required: false
argument :end_date, String, required: false
argument :after, String, required: false
type Types::DailyStatisticType.connection_type, null: false
def resolve(**params)
if params[:start_date].present? && params[:end_date].present?
DailyStatistic.where(datetime: DateTime.parse(params[:start_date])...DateTime.parse(params[:end_date]))
else
DailyStatistic.all
end
end
end
end
|
[section .text]
global _start:
_start:
mov ah ,0fh
mov al ,'K'
mov [gs:((80*1+40)*2)] ,ax
jmp $
|
package io.kblog.service.impl
import io.kblog.domain.Base
import io.kblog.domain.Role
import io.kblog.domain.User
import io.kblog.repository.RoleDao
import io.kblog.service.RoleService
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
/**
* @author hsdllcw on 2020/3/24.
* @version 1.0.0
*/
@Service
@Transactional(readOnly = true)
class RoleServiceImpl : RoleService, BaseServiceImpl<Role,Base.RoleVo>() {
@Autowired
private val roleDao: RoleDao? = null
override fun getAuthorityByUser(user: User): Set<String> {
val roles = user.roles
val set: MutableSet<String> = mutableSetOf()
if (user.type == User.UserType.ROOT) {
// root用户,拥有所有权限,直接返回
set.add("*")
return set
}
for (role in roles) {
if (role.allAuthority) {
// 拥有所有权限,直接返回
set.add("*")
return set
}
}
for (role in roles) {
val authority = role.authority
if (StringUtils.isNotBlank(authority)) {
for (perm in StringUtils.split(authority, ',')) {
set.add(perm)
}
}
}
return set
}
}
|
import React from 'react'
import { ChakraProvider, theme, Button } from '@chakra-ui/react'
import { render, screen, act, fireEvent, waitFor } from '@testing-library/react'
import Navbar from './'
describe('Navbar', () => {
it('Renders initial and expands', async () => {
render(
<ChakraProvider theme={theme}>
<Navbar branding="MVR">
<Button data-testid="test.hidden">Dashboard</Button>
</Navbar>
</ChakraProvider>
)
expect(screen.getByTestId('protochakra.navbar.branding').textContent).toContain('MVR')
act(() => {
fireEvent.click(screen.getByTestId('protochakra.navbar.toggle'))
})
await waitFor(() => {
expect(screen.queryByTestId('test.hidden')).toBeInTheDocument()
})
})
})
|
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require 'spec_helper'
module AWS
class SimpleDB
describe AttributeCollection do
let(:config) { stub_config }
let(:client) { config.simple_db_client }
let(:domain) { Domain.new('domain-name', :config => config) }
let(:item) { Item.new(domain, 'item-name') }
let(:attributes) { AttributeCollection.new(item) }
it_behaves_like 'a sdb model object', 'item'
it_behaves_like 'enumerable'
context '#initialize' do
it 'requires an item' do
lambda { AttributeCollection.new }.should raise_error(ArgumentError)
end
it 'accepts an item' do
lambda { AttributeCollection.new(item) }.should_not raise_error
end
end
context '#item' do
it 'returns the item passed to #initialize' do
attributes.item.should == item
end
end
context '#to_h' do
let(:response) {
double('response', :attributes => [
double('attr1', :name => 'foo', :value => 'abc'),
double('attr1', :name => 'foo', :value => 'xyz'),
double('attr1', :name => 'bar', :value => '123'),
])
}
it 'hasherishes each of the values' do
client.should_receive(:get_attributes).and_return(response)
attributes.to_h.should == { 'foo' => %w(abc xyz), 'bar' => %w(123) }
end
it_behaves_like('accepts :consistent_read option', lambda{}) do
let(:object) { attributes }
let(:method) { :to_h }
let(:client_method) { :get_attributes }
end
end
context '#[]' do
it 'returns an attribute' do
attributes['color'].should be_an(Attribute)
end
it 'returns an attribute with the correct item' do
attributes['color'].item.should == item
end
it 'returns an attribute with the correct name' do
attributes['color'].name.should == 'color'
end
it 'returns an attribute with the correct config' do
attributes['color'].config.should == config
end
it 'stringifies the name' do
attributes[:color].name.should == 'color'
end
end
context '#[]=' do
it 'calls set on the attribute named' do
client.should_receive(:put_attributes).
with(hash_including(
:domain_name => domain.name,
:item_name => item.name,
:attributes => [
{ :name => 'colors', :value => 'red', :replace => true },
{ :name => 'colors', :value => 'green', :replace => true },
]))
attributes['colors'] = 'red', 'green'
end
end
context "#each_value" do
let(:response) { double('response', :attributes => []) }
it 'calls get_attributes' do
client.should_receive(:get_attributes).
with(hash_including(
:domain_name => domain.name,
:item_name => item.name)).
and_return(response)
attributes.each_value{|attr_name, attr_value|}
end
it 'yields once for each attribute value' do
response.stub(:attributes).and_return([
double('attr1', :name => 'foo', :value => 'bar1'),
double('attr1', :name => 'foo', :value => 'bar2'),
double('attr1', :name => 'abc', :value => 'xyz'),
])
client.should_receive(:get_attributes).and_return(response)
yielded = []
attributes.each_value do |attr_name, attr_value|
yielded << [attr_name, attr_value]
end
yielded.should == [
['foo', 'bar1'],
['foo', 'bar2'],
['abc', 'xyz'],
]
end
end
context '#each' do
let(:response) { double('response', :attributes => []) }
it_behaves_like('accepts :consistent_read option', lambda{|attr|}) do
let(:object) { attributes }
let(:method) { :each }
let(:client_method) { :get_attributes }
end
it 'calls get_attributes' do
client.should_receive(:get_attributes).
with(hash_including(
:domain_name => domain.name,
:item_name => item.name)).
and_return(response)
attributes.each{|attribute|}
end
it 'yields attribute objects' do
response.stub(:attributes).and_return([
double('attr1', :name => 'foo', :value => 'bar1'),
double('attr1', :name => 'foo', :value => 'bar2'),
double('attr1', :name => 'abc', :value => 'xyz'),
])
client.should_receive(:get_attributes).and_return(response)
yielded_names = []
attributes.each do |attribute|
yielded_names << attribute.name
end
yielded_names.should == %w(foo abc)
end
end
context '#put' do
context 'empty hash' do
it 'does nothing' do
client.should_not_receive(:put_attributes)
attributes.put({})
end
end
it 'calls put_attributes' do
client.should_receive(:put_attributes).with do |hash|
attr = hash[:attributes]
attr.length.should == 3
attr.should include({ :value => "4", :name => "wheels", :replace => true })
attr.should include({ :value => "red", :name => "colors", :replace => false })
attr.should include({ :value => "blue", :name => "colors", :replace => false })
end
attributes.put(
:add => { 'colors' => ['red', 'blue'] },
:replace => { 'wheels' => '4' }
)
end
it_should_behave_like "sdb expect conditions" do
def should_expect(conditions)
client.should_receive(:put_attributes).with do |hash|
attr = hash[:attributes]
attr.length.should == 3
attr.should include({ :value => "4", :name => "wheels", :replace => true })
attr.should include({ :value => "red", :name => "colors", :replace => false })
attr.should include({ :value => "blue", :name => "colors", :replace => false })
hash[:expected].should == conditions
end
end
def do_with_condition(condition)
attributes.put({
:add => { 'colors' => ['red', 'blue'] },
:replace => { 'wheels' => '4' }
}.merge(condition))
end
end
end
context '#set' do
it 'is an alias for replace' do
attributes.method(:set).should == attributes.method(:replace)
end
end
context '#replace' do
context 'empty hash' do
it 'does nothing' do
client.should_not_receive(:put_attributes)
attributes.replace({})
end
end
it 'calls put_attributes' do
client.should_receive(:put_attributes).with do |hash|
attr = hash[:attributes]
attr.length.should == 3
attr.should include({ :value => "4", :name => "wheels", :replace => true })
attr.should include({ :value => "red", :name => "colors", :replace => true })
attr.should include({ :value => "blue", :name => "colors", :replace => true })
end
attributes.replace('colors' => ['red', 'blue'], 'wheels' => '4')
end
it 'handles string values with newlines' do
client.should_receive(:put_attributes).with do |opts|
opts[:attributes].map { |att| att[:value] }.
should include("red\r\nblue")
end
attributes.replace('colors' => "red\r\nblue", 'wheels' => '4')
end
it_should_behave_like "sdb expect conditions" do
def should_expect(conditions)
client.should_receive(:put_attributes).with do |hash|
attr = hash[:attributes]
attr.length.should == 3
attr.should include({ :value => "4",
:name => "wheels",
:replace => true })
attr.should include({ :value => "red",
:name => "colors",
:replace => true })
attr.should include({ :value => "blue",
:name => "colors",
:replace => true })
hash[:expected].should == conditions
end
end
def do_with_condition(condition)
attributes.set({
'colors' => ['red', 'blue'],
'wheels' => '4'
}.merge(condition))
end
end
end
context '#add' do
context 'empty hash' do
it 'does nothing' do
client.should_not_receive(:put_attributes)
attributes.add({})
end
end
it 'calls put_attributes' do
client.should_receive(:put_attributes).with do |hash|
attr = hash[:attributes]
attr.length.should == 3
attr.should include({ :value => "4", :name => "wheels", :replace => false })
attr.should include({ :value => "red", :name => "colors", :replace => false })
attr.should include({ :value => "blue", :name => "colors", :replace => false })
end
attributes.add('colors' => ['red', 'blue'], 'wheels' => '4')
end
it_should_behave_like "sdb expect conditions" do
def should_expect(conditions)
client.should_receive(:put_attributes).with do |hash|
attr = hash[:attributes]
attr.length.should == 3
attr.should include({ :value => "4",
:name => "wheels",
:replace => false })
attr.should include({ :value => "red",
:name => "colors",
:replace => false })
attr.should include({ :value => "blue",
:name => "colors",
:replace => false })
hash[:expected].should == conditions
end
end
def do_with_condition(condition)
attributes.add({
'colors' => ['red', 'blue'],
'wheels' => '4'
}.merge(condition))
end
end
end
context '#delete' do
def should_delete(opts)
client.should_receive(:delete_attributes).
with({
:domain_name => "domain-name",
:item_name => "item-name"
}.merge(opts))
end
it 'returns nil' do
attributes.delete.should == nil
end
context 'no arguments' do
it 'does nothing' do
client.should_not_receive(:delete_attributes)
attributes.delete
end
end
context 'attribute names' do
it 'calls delete_attributes' do
should_delete(:attributes => [{ :name => 'colors' }])
attributes.delete('colors')
end
it 'accepts symbol attribute names' do
should_delete(:attributes => [{ :name => 'colors' }])
attributes.delete(:colors)
end
it 'accepts a list of names' do
should_delete(:attributes => [{ :name => 'colors' },
{ :name => 'size' }])
attributes.delete('colors', 'size')
end
it 'accepts an array of names' do
should_delete(:attributes => [{ :name => 'colors' },
{ :name => 'size' }])
attributes.delete(['colors', 'size'])
end
it_should_behave_like "sdb expect conditions" do
def should_expect(conditions)
should_delete({
:attributes => [{ :name => 'colors' }]
}.merge(:expected => conditions))
end
def do_with_condition(condition)
attributes.delete(:colors, condition)
end
end
end
context 'attribute values' do
it 'calls delete_attributes' do
should_delete(:attributes => [{ :name => 'colors',
:value => 'red' }])
attributes.delete('colors' => 'red')
end
it 'accepts symbol keys' do
should_delete(:attributes => [{ :name => 'colors',
:value => 'red' }])
attributes.delete(:colors => 'red')
end
it 'accepts multiple values' do
should_delete(:attributes => [{ :name => 'colors',
:value => 'red' },
{ :name => 'colors',
:value => 'blue' }])
attributes.delete(:colors => ['red', 'blue'])
end
it 'ignores empty lists of values' do
should_delete(:attributes => [{ :name => 'colors',
:value => 'blue' }])
attributes.delete(:colors => 'blue',
:ignored => [])
end
it 'accepts the special value :all' do
should_delete(:attributes => [{ :name => 'colors' }])
attributes.delete(:colors => :all)
end
it_should_behave_like "sdb expect conditions" do
def should_expect(conditions)
should_delete({
:attributes => [{ :name => 'colors',
:value => 'red' }]
}.merge(:expected => conditions))
end
def do_with_condition(condition)
attributes.delete({
:colors => 'red'
}.merge(condition))
end
end
end
end
end
end
end
|
#!/usr/bin/env bash
#
# Create application bundles for Windows systems.
# Copyright 2015-2021 OpenIndex.de
#
# 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.
#
# ----------------------------------------------------------------------------
# NOTICE: This script requires an ".env" file in the same folder. If it is not
# available, create a copy of ".env.example" and place your settings inside.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# You can find further information at:
# https://github.com/OpenIndex/RemoteSupportTool/wiki/Development#create-application-bundles
# ----------------------------------------------------------------------------
WINE="$(which "wine")"
WINEPATH="$(which "winepath")"
SEVENZIP="$(which "7z")"
SEVENZIP_OPTIONS="-mx=9"
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
TARGET_DIR="${DIR}/target"
FOUND="0"
set -e
STAFF_TOOL=""
CUSTOMER_TOOL=""
VERSION=""
if [[ -f "${DIR}/.env" ]]; then
source "${DIR}/.env"
fi
CUSTOMER_SFX="${DIR}/src/windows/7zSD.sfx"
STAFF_SFX="${DIR}/src/windows/7zSD.sfx"
if [[ -x "${WINE}" ]]; then
echo ""
printf "\e[1m\e[92m=======================================================================\e[0m\n"
printf "\e[1m\e[92m Creating custom 7zip sfx files...\e[0m\n"
printf "\e[1m\e[92m=======================================================================\e[0m\n"
echo ""
echo "Preparing build..."
SEVENZIP_DIR="${TARGET_DIR}/7zip"
SEVENZIP_DIR_WIN="$("${WINEPATH}" -w "${SEVENZIP_DIR}")"
rm -Rf "${SEVENZIP_DIR}"
mkdir -p "${SEVENZIP_DIR}"
cd "${DIR}/src/windows"
cp "7zSD.sfx" "${SEVENZIP_DIR}"
"${WINE}" "ResourceHacker.exe" -open "manifest.rc" -save "${SEVENZIP_DIR_WIN}\manifest.res" -action compile
echo "Creating Customer.sfx..."
cp "${DIR}/src/windows/Customer.script" "${SEVENZIP_DIR}"
if [[ -f "${DIR}/src/windows/Customer.ico" ]]; then
cp "${DIR}/src/windows/Customer.ico" "${SEVENZIP_DIR}"
else
cp "${DIR}/src/icons/desktopshare.ico" "${SEVENZIP_DIR}/Customer.ico"
fi
"${WINE}" "ResourceHacker.exe" -open "Customer.rc" -save "${SEVENZIP_DIR_WIN}\Customer.res" -action compile
"${WINE}" "ResourceHacker.exe" -script "${SEVENZIP_DIR_WIN}\Customer.script"
if [[ -f "${SEVENZIP_DIR}/Customer.sfx" ]]; then
CUSTOMER_SFX="${SEVENZIP_DIR}/Customer.sfx"
else
echo "WARNING: Customer.sfx was not created!"
echo "Using default 7zSD.sfx instead."
fi
echo "Creating Staff.sfx..."
cp "${DIR}/src/windows/Staff.script" "${SEVENZIP_DIR}"
if [[ -f "${DIR}/src/windows/Staff.ico" ]]; then
cp "${DIR}/src/windows/Staff.ico" "${SEVENZIP_DIR}"
else
cp "${DIR}/src/icons/help.ico" "${SEVENZIP_DIR}/Staff.ico"
fi
"${WINE}" "ResourceHacker.exe" -open "Staff.rc" -save "${SEVENZIP_DIR_WIN}\Staff.res" -action compile
"${WINE}" "ResourceHacker.exe" -script "${SEVENZIP_DIR_WIN}\Staff.script"
if [[ -f "${SEVENZIP_DIR}/Staff.sfx" ]]; then
STAFF_SFX="${SEVENZIP_DIR}/Staff.sfx"
else
echo "WARNING: Staff.sfx was not created!"
echo "Using default 7zSD.sfx instead."
fi
fi
if [[ -d "${TARGET_DIR}/Staff/windows-x86" ]]; then
FOUND="1"
echo ""
printf "\e[1m\e[92m=======================================================================\e[0m\n"
printf "\e[1m\e[92m Creating %s.windows-x86.exe...\e[0m\n" "${STAFF_TOOL}-${VERSION}"
printf "\e[1m\e[92m=======================================================================\e[0m\n"
rm -f "${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86.exe"
cd "${TARGET_DIR}/Staff/windows-x86"
"$SEVENZIP" a "$SEVENZIP_OPTIONS" \
"${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86.7z" .
cat "${STAFF_SFX}" >"${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86.exe"
cat "${DIR}/src/windows/Staff.txt" >>"${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86.exe"
cat "${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86.7z" >>"${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86.exe"
rm "${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86.7z"
fi
if [[ -d "${TARGET_DIR}/Staff/windows-x86-64" ]]; then
FOUND="1"
echo ""
printf "\e[1m\e[92m=======================================================================\e[0m\n"
printf "\e[1m\e[92m Creating %s.windows-x86-64.exe...\e[0m\n" "${STAFF_TOOL}-${VERSION}"
printf "\e[1m\e[92m=======================================================================\e[0m\n"
rm -f "${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86-64.exe"
cd "${TARGET_DIR}/Staff/windows-x86-64"
"$SEVENZIP" a "$SEVENZIP_OPTIONS" \
"${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86-64.7z" .
cat "${STAFF_SFX}" >"${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86-64.exe"
cat "${DIR}/src/windows/Staff.txt" >>"${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86-64.exe"
cat "${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86-64.7z" >>"${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86-64.exe"
rm "${TARGET_DIR}/${STAFF_TOOL}-${VERSION}.windows-x86-64.7z"
fi
if [[ -d "${TARGET_DIR}/Customer/windows-x86" ]]; then
FOUND="1"
echo ""
printf "\e[1m\e[92m=======================================================================\e[0m\n"
printf "\e[1m\e[92m Creating %s.windows-x86.exe...\e[0m\n" "${CUSTOMER_TOOL}-${VERSION}"
printf "\e[1m\e[92m=======================================================================\e[0m\n"
rm -f "${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86.exe"
cd "${TARGET_DIR}/Customer/windows-x86"
"$SEVENZIP" a "$SEVENZIP_OPTIONS" \
"${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86.7z" .
cat "${CUSTOMER_SFX}" >"${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86.exe"
cat "${DIR}/src/windows/Customer.txt" >>"${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86.exe"
cat "${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86.7z" >>"${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86.exe"
rm "${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86.7z"
fi
if [[ -d "${TARGET_DIR}/Customer/windows-x86-64" ]]; then
FOUND="1"
echo ""
printf "\e[1m\e[92m=======================================================================\e[0m\n"
printf "\e[1m\e[92m Creating %s.windows-x86-64.exe...\e[0m\n" "${CUSTOMER_TOOL}-${VERSION}"
printf "\e[1m\e[92m=======================================================================\e[0m\n"
rm -f "${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86-64.exe"
cd "${TARGET_DIR}/Customer/windows-x86-64"
"$SEVENZIP" a "$SEVENZIP_OPTIONS" \
"${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86-64.7z" .
cat "${CUSTOMER_SFX}" >"${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86-64.exe"
cat "${DIR}/src/windows/Customer.txt" >>"${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86-64.exe"
cat "${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86-64.7z" >>"${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86-64.exe"
rm "${TARGET_DIR}/${CUSTOMER_TOOL}-${VERSION}.windows-x86-64.7z"
fi
if [[ "${FOUND}" == "0" ]]; then
echo "ERROR: No Windows packages were found at:"
echo "${TARGET_DIR}"
fi
|
"""
A standalone partial implementation of sbt
https://www.solutionsbytext.com/api-support/api-documentation/
"""
from .resources import RequireVBT, RequestVBT, Carrier, SendTemplateMessage, GetMessageStatus
__all__ = [
'RequireVBT', 'SendTemplateMessage', 'Carrier', 'GetMessageStatus', 'RequestVBT'
]
__version__ = '0.0.1'
|
package com.shijc.wanandroidkotlin.ui.account
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.shijc.wanandroidkotlin.R
import com.shijc.wanandroidkotlin.common.mvp.BaseActivity
class RegisterActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
}
}
|
#!/usr/bin/env bash
set -e
echo "$TRAVIS_JOB has been received"
if [[ $TRAVIS_JOB = "docker" ]]; then
echo "Docker connection Checks"
curl --fail ${BIOBLEND_GALAXY_URL}/api/version
date > $HOME/date.txt && curl --fail -T $HOME/date.txt ftp://localhost:21 --user $GALAXY_USER:$GALAXY_USER_PASSWD
sudo -E su $GALAXY_TRAVIS_USER -c "export PATH=$GALAXY_HOME/.local/bin/:$PATH &&
cd $GALAXY_HOME &&
bioblend-galaxy-tests -v $GALAXY_HOME/.local/lib/python2.7/site-packages/bioblend/_tests/TestGalaxy*.py"
fi
if [[ $TRAVIS_JOB = "ansible" ]]; then
echo "Bioblend Testing"
curl --fail ${BIOBLEND_GALAXY_URL}/api/version
date > $HOME/date.txt && curl --fail -T $HOME/date.txt ftp://localhost:21 --user $GALAXY_USER:$GALAXY_USER_PASSWD
sudo -E su $GALAXY_TRAVIS_USER -c "export PATH=$GALAXY_HOME/.local/bin/:$PATH &&
cd $GALAXY_HOME &&
bioblend-galaxy-tests -v $GALAXY_HOME/.local/lib/python2.7/site-packages/bioblend/_tests/TestGalaxy*.py"
fi
|
#!/bin/bash
##
## Jenkins 部署脚本
##
## Started on 2019/10/28 Leo <xinlichao2016@gmail.com>
## Last update 2019/10/28 Leo <xinlichao2016@gmail.com>
##
set -e
version="1.0.0"
# Colours
red="\033[91m"
green="\033[92m"
yellow="\033[93m"
magenta="\033[95m"
cyan="\033[96m"
none="\033[0m"
# 项目ID
project_id=""
# 环境:development, testing, production
profile_name=""
# 构建版本:1.0.0
project_version="1.0.0"
# 模块相对项目根路径
modules_path=(
all
smart-apm/smart-admin
smart-tx-manager
smart-gateway
smart-auth
smart-server/smart-server-job
smart-server/smart-server-generator
smart-server/smart-server-system
)
# 镜像仓库名
register_names=(
all
smart-admin
smart-tx-manager
smart-gateway
smart-auth
smart-server-job
smart-server-generator
smart-server-system
)
# 镜像版本由 init 生成,如:smart-auth-server:1.0.0-SNAPSHOT
image_tags=(
all
)
# 定义环境和镜像 tag 后缀映射
declare -A image_tag_suffix_map=(["development"]="DEV" ["testing"]="SNAPSHOT" ["production"]="RELEASE")
# declare -A maven_profile_map=(["development"]="dev" ["testing"]="test" ["production"]="prod")
# 暂时处理,选择开发环境使用测试环境构建
declare -A maven_profile_map=(["development"]="test" ["testing"]="test" ["production"]="prod")
# 脚本执行工作路径
work_path=$(
cd "$(dirname "$0")";
pwd
)
# 项目根目录
project_root_path=$(
cd $work_path;
cd ..;
pwd
)
# docker 镜像仓库地址
docker_registry_uri="registry-vpc.cn-beijing.aliyuncs.com/leo"
#docker_registry_uri="registry.cn-beijing.aliyuncs.com/leo"
docker_file_path="${work_path}/Dockerfile"
init() {
# 截取字符 10:aid-abc -> 10
project_id=${project_id%%:*}
# 映射 maven 环境
maven_profile="${maven_profile_map[$profile_name]}"
# 根据环境映射镜像tag
for ((i = 1; i < ${#register_names[@]}; i++)); do
ImageTag=${project_version}
image_tags[$i]="${ImageTag}-${image_tag_suffix_map[$profile_name]}"
done
}
error() {
echo -e "\n$red 输入错误!$none\n"
exit 1
}
pause() {
read -rsp "$(echo -e "按${green} Enter 回车键 ${none}继续...或按${red} Ctrl + C ${none}取消.")" -d $'\n'
echo
}
show_projects() {
for ((i = 1; i <= ${#register_names[*]}; i++)); do
Item="${register_names[$i - 1]}"
if [[ "$i" -le 9 ]]; then
# echo
echo -e "$yellow $i. $none${Item}"
else
# echo
echo -e "$yellow $i. $none${Item}"
fi
done
}
show_deploy_projects() {
for ((i = 1; i <= ${#image_tags[*]} - 1; i++)); do
ItemTag="${image_tags[$i]}"
ItemName="${register_names[$i]}"
echo -e "$cyan ${docker_registry_uri}/${ItemName}:${ItemTag}$none"
done
}
show_confirm_deploy() {
echo "=============================="
echo -e "$yellow 即将部署 $none"
echo
if test $project_id -eq 1; then
show_deploy_projects
else
echo -e "$cyan ${docker_registry_uri}/${register_names[project_id - 1]}:${image_tags[$project_id - 1]}$none"
fi
echo
echo "=============================="
# # 提示
# pause
#
# 部署
deploy
}
deploy() {
# 部署所有项目
if test $project_id -eq 1; then
# 构建所有模块
# mvn clean install -Dmaven.test.skip=true -P${maven_profile}
mvn clean install -Dmaven.test.skip=true
for ((i = 1; i <= ${#image_tags[*]} - 1; i++)); do
ItemTag="${image_tags[$i]}"
ItemName="${register_names[$i]}"
RegisterName="${register_names[$i]}"
ProjectPath=${project_root_path}/${modules_path[$i]}
# 构建 docker 镜像并推送到镜像仓库
docker build -t "${docker_registry_uri}/${RegisterName}:${ItemTag}" -f ${docker_file_path} ${ProjectPath}
docker push "${docker_registry_uri}/${RegisterName}:${ItemTag}"
done
else
# 部署选择的项目
ItemTag="${image_tags[$project_id - 1]}"
ItemName="${register_names[project_id - 1]}"
RegisterName="${register_names[project_id - 1]}"
ProjectPath=${project_root_path}/${modules_path[project_id - 1]}
# 构建指定模块
# mvn clean install -Dmaven.test.skip=true -pl :${RegisterName} -am -P${maven_profile}
mvn clean install -Dmaven.test.skip=true -pl :${RegisterName} -am
# 构建 docker 镜像并推送到镜像仓库
docker build -t "${docker_registry_uri}/${RegisterName}:${ItemTag}" -f ${docker_file_path} ${ProjectPath}
docker push "${docker_registry_uri}/${RegisterName}:${ItemTag}"
fi
echo
echo -e "${green}===============部署成功===============${none}"
echo
}
run() {
# clear
echo
while :; do
echo -e "请选择要部署的项目 [${magenta}1-${#register_names[*]}$none]"
echo
# 显示所有项目
show_projects
# 读取用户输入
# read -p "$(echo -e "(默认: ${cyan}all$none)"):" project_id
pwd
# project_id=1
case $project_id in
[1-9]|1[0-9])
echo
echo -e "$yellow 已选择 $cyan${register_names[$project_id - 1]}$none"
break
;;
*)
error
;;
esac
done
# 显示确认部署信息
show_confirm_deploy
}
usage() {
echo -e "$red Usage:`basename $0` -p [Project ID] -e [development | testing | production] -v [Build Version]$none"
echo -e "$red `basename $0` -p 1:xxx -e testing -v 1.0.0 $none"
show_projects
exit 1
}
# 获取输入参数
while getopts "hp:e:v:" opt; do
case $opt in
h)
usage
;;
p)
project_id=$OPTARG
;;
e)
profile_name=$OPTARG
;;
v)
project_version=$OPTARG
;;
?)
usage
;;
esac
done
# 检查输入参数
echo $*
if [ $# == 0 ]; then
usage
fi
if [[ -z $project_id || -z $profile_name ]]; then
usage
fi
# 进入工作目录
cd $work_path
# 初始化
init
# 开始执行
run
|
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/test';
var insertDocs, findDocs, updateDocs, removeDocs, indexCollection,
createCapped, closeDb, createValidated;
insertDocs = function(db, callback){
var collection = db.collection('documents');
collection.insertMany([
{a: 'gloria'},
{a: 'tommy'},
{a: 'jax'}
], function(err, result){
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log('Inserted 3 documents into the collection');
callback(result);
});
};
findDocs = function(db, callback){
var collection = db.collection('documents');
collection.find({}).toArray(function(err,docs){
assert.equal(err, null);
console.log("Found the following records:");
console.log(docs);
callback(docs);
});
};
updateDocs = function(db, callback){
var collection = db.collection('documents');
collection.updateOne({a: 2},
{ $set: {b: 1} },
function(err, result){
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log('Updated the document with the field a equal to 2.');
callback(result);
}
);
};
removeDocs = function(db, callback){
var collection = db.collection('documents');
collection.deleteOne({a: 'jax'},function(err, result){
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log('Removed the document with the field a equal to 3.');
callback(result);
});
};
indexCollection = function(db, callback){
db.collection('documents').createIndex(
{'a': 'gloria'},
null,
function(err, results){
console.log('results:',results);
callback();
}
);
};
createCapped = function(db, callback){
db.createCollection('myCollection', {
"capped": true, "size": 10000, "max": 5000
}, function(err, results){
console.log('collection created.');
callback();
});
};
closeDb = function(db){
return function(){
db.close();
};
};
createValidated = function(db, callback){
db.createCollection("contacts",{
'validator': {
'$or': [
{ 'phone': {'$type': 'string'} },
{ 'email': {'$regex': /@mongodb\.com$/} },
{ 'status': {'$in': ['Unknown', 'Incomplete']} }
]
}
}, function(err, results){
console.log('Collection created.');
callback();
});
};
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
console.log('ERRRRR:', err);
assert.equal(null, err);
console.log("Connected successfully to server");
// insertDocs(db, function(){
// });
// findDocs (db, function(){
// db.close();
// });
// createCapped(db, closeDb(db));
//
createValidated(db, function(db){
findDocs(db, closeDb(db));
});
});
|
package pw.vhome.ticketsystem.controller;
import pw.vhome.ticketsystem.data.InquiryProducer;
import pw.vhome.ticketsystem.data.UserProducer;
import pw.vhome.ticketsystem.model.Inquiry;
import pw.vhome.ticketsystem.model.User;
import pw.vhome.ticketsystem.util.Events;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
/**
* Created by vitz on 14.06.17.
*/
@Named
@SessionScoped
public class ListUsersController implements Serializable{
public static final long serialVersionUID = 98760987L;
@Inject
UserProducer userProducer;
public String doListInquiries(){
return Pages.LIST_INQUIRIES;
}
public String doEditUser(User user){
userProducer.prepareEditUser(user);
return Pages.EDIT_USER;
}
}
|
include("./imports.jl")
using ReTest
FluxTraining.runtests()
module FluxTrainingTests
include("./imports.jl")
include("./metrics.jl")
include("./protected.jl")
include("./training.jl")
include("./callbacks/stoponnanloss.jl")
include("./callbacks/conditional.jl")
include("./callbacks/logging.jl")
include("./callbacks/recorder.jl")
include("./callbacks/scheduler.jl")
include("./callbacks/checkpointer.jl")
include("./callbacks/garbagecollect.jl")
include("./callbacks/sanitycheck.jl")
include("./callbacks/earlystopping.jl")
include("./callbackutils.jl")
end
FluxTrainingTests.runtests()
|
// -----------------------------------------------------------------------
// <copyright file="IReceiverContext.cs" company="Asynkron AB">
// Copyright (C) 2015-2022 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
// ReSharper disable once CheckNamespace
namespace Proto;
public interface IContextStore
{
/// <summary>
/// Gets a value from the actor context
/// </summary>
/// <typeparam name="T">The Type key of the value</typeparam>
/// <returns>The value</returns>
T? Get<T>();
/// <summary>
/// Sets a value from the actor context
/// </summary>
/// <param name="obj">The value to set</param>
/// <typeparam name="T">The Type key of the value</typeparam>
void Set<T>(T obj) => Set<T, T>(obj);
/// <summary>
/// Sets a value from the actor context
/// </summary>
/// <param name="obj">The value to set</param>
/// <typeparam name="T">The Type key of the value</typeparam>
/// <typeparam name="TI">Type of the value, if different from the Type key</typeparam>
void Set<T, TI>(TI obj) where TI : T;
/// <summary>
/// Removes a value from the actor context
/// </summary>
/// <typeparam name="T">The Type key of the value</typeparam>
void Remove<T>();
}
|
import java.util.*
plugins {
`maven-publish`
id("com.jfrog.bintray") version Constants.BuildLibVersions.bintray
kotlin("multiplatform") version Constants.BuildLibVersions.kotlin
}
group = "de.nidomiro"
version = "0.3.0"
repositories {
mavenCentral()
jcenter()
}
@Suppress("UNUSED_VARIABLE")
kotlin {
//Targets
jvm {
val javaVersion = "1.8"
val main by compilations.getting {
kotlinOptions {
jvmTarget = javaVersion
}
}
val test by compilations.getting {
kotlinOptions {
jvmTarget = javaVersion
}
}
}
js {
nodejs {
}
//browser { }
val main by compilations.getting {
kotlinOptions {
sourceMap = true
moduleKind = "umd"
}
}
val test by compilations.getting {
kotlinOptions {
sourceMap = true
moduleKind = "umd"
}
}
}
@Suppress("UNUSED_VARIABLE")
sourceSets {
val coroutinesVersion = "1.3.9"
val assertkVersion = "0.22"
val junitVersion = "5.6.2"
val commonMain by getting {
dependencies {
implementation(kotlin("stdlib-common"))
implementation(kotlin("reflect"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion")
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
implementation("com.willowtreeapps.assertk:assertk:$assertkVersion")
}
}
val jvmMain by getting {
dependencies {
implementation(kotlin("stdlib-jdk8"))
}
}
val jvmTest by getting {
dependencies {
implementation(kotlin("test-junit5"))
implementation("org.junit.jupiter:junit-jupiter:$junitVersion")
}
}
val jsMain by getting {
dependencies {
implementation(kotlin("stdlib-js"))
}
}
val jsTest by getting {
dependencies {
implementation(kotlin("test-js"))
}
}
}
}
tasks.named<Test>("jvmTest") {
useJUnitPlatform()
}
apply(from = rootProject.file("gradle/publish.gradle.kts"))
// Bintray stuff (doesn't work in a separate file right now)
bintray {
user = if (project.hasProperty("bintray_user")) project.property("bintray_user") as String else ""
key = if (project.hasProperty("bintray_key")) project.property("bintray_key") as String else ""
//publish = true
override = true
pkg.apply {
repo = "maven"
name = project.name
setLicenses("MIT")
setLabels("kotlin", "Kotlin", "Multiplatform", "DataLoader", "GraphQL")
vcsUrl = Constants.ProjectInfo.vcsUrl
websiteUrl = Constants.ProjectInfo.websiteUrl
issueTrackerUrl = "${Constants.ProjectInfo.websiteUrl}/issues"
version.apply {
name = project.version.toString()
vcsTag = project.version.toString()
released = Date().toString()
}
}
}
tasks.named("bintrayUpload") {
dependsOn(":publishToMavenLocal")
}
tasks.withType<com.jfrog.bintray.gradle.tasks.BintrayUploadTask> {
doFirst {
project.publishing.publications
.filterIsInstance<MavenPublication>()
.forEach { publication ->
val moduleFile = buildDir.resolve("publications/${publication.name}/module.json")
if (moduleFile.exists()) {
publication.artifact(object :
org.gradle.api.publish.maven.internal.artifact.FileBasedMavenArtifact(moduleFile) {
override fun getDefaultExtension() = "module"
})
}
}
}
}
apply(from = rootProject.file("gradle/groovyTasks.gradle"))
|
#include <iostream>
#include <functional>
#include <vector>
#include <queue>
#include <tuple>
using namespace std;
#define MAX 102
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
const int INF = 1e9+7;
typedef tuple<int, int, int> ti;
int n, m;
int map[MAX][MAX], height[MAX][MAX];
bool visit[MAX][MAX];
int main()
{
ios_base::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
cin >> n >> m;
for (int i=1; i<=n; ++i)
for (int j=1; j<=m; ++j)
cin >> map[i][j];
n += 2;
m += 2;
for (int i=0; i<n; ++i)
for (int j=0; j<m; ++j)
height[i][j] = INF;
priority_queue<ti, vector<ti>, greater<ti>> que;
que.push({0, 0, 0});
height[0][0] = 0;
while (!que.empty()) {
auto [d, x, y] = que.top();
que.pop();
if (visit[x][y])
continue;
visit[x][y] = 1;
for (int i=0; i<4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= n || ny < 0 || ny >= m)
continue;
int nd = max(height[x][y], map[nx][ny]);
if (height[nx][ny] > nd) {
height[nx][ny] = nd;
que.push({nd, nx, ny});
}
}
}
int ans = 0;
for (int i=0; i<n; ++i)
for (int j=0; j<m; ++j)
ans += height[i][j] - map[i][j];
cout << ans << '\n';
return 0;
}
|
package yafmi
import scalaz.{Monad, ~>}
sealed trait Arrow[A, F[_], B] {
final def thenArrow[C](arrow: Arrow[B, F, C]): Arrow[A, F, C] = Arrow.Sequence(this, arrow)
protected def prepared: Arrow[A, F, B]
def run(fa: F[A])(implicit F: Monad[F]): F[B]
def transform[G[_]](nt: F ~> G): Arrow[A, G, B]
}
object Arrow {
final case class Identity[F[_], A]() extends Arrow[A, F, A] {
override def prepared: Arrow[A, F, A] = this
override def run(fa: F[A])(implicit F: Monad[F]): F[A] = fa
override def transform[G[_]](nt: F ~> G): Arrow[A, G, A] = Identity()
}
final case class Apply[A, F[_], B](f: Free[F, A => B]) extends Arrow[A, F, B] {
override def prepared: Arrow[A, F, B] = this
override def run(fa: F[A])(implicit F: Monad[F]): F[B] = f match {
case Free.Pure(ff) => F.map(fa)(ff)
case Free.Impure(fi, arrow) => F.ap(fa)(arrow.run(fi))
}
override def transform[G[_]](nt: F ~> G): Arrow[A, G, B] = Apply(f.transform(nt))
}
final case class Bind[A, F[_], B](f: A => Free[F, B]) extends Arrow[A, F, B] {
override def prepared: Arrow[A, F, B] = this
override def run(fa: F[A])(implicit F: Monad[F]): F[B] =
F.bind(fa)(f.andThen(_.run))
override def transform[G[_]](nt: F ~> G): Arrow[A, G, B] = BindThenTransform(f, nt)
}
final case class BindThenTransform[A, F[_], G[_], B](f: A => Free[F, B], nt: F ~> G) extends Arrow[A, G, B] {
override protected def prepared: Arrow[A, G, B] = ???
override def run(fa: G[A])(implicit F: Monad[G]): G[B] =
F.bind(fa)(f.andThen(free => free.runAs(nt)))
override def transform[H[_]](nt2: G ~> H): Arrow[A, H, B] = BindThenTransform(f, nt.andThen(nt2))
}
final case class Sequence[A, X, F[_], B](first: Arrow[A, F, X], last: Arrow[X, F, B]) extends Arrow[A, F, B] {
override def prepared: Arrow[A, F, B] = {
@scala.annotation.tailrec
def f[P, Q, R, S](sequence: Sequence[P, Q, F, R], arrow: Arrow[R, F, S]): Arrow[P, F, S] = {
sequence.first match {
case sq: Sequence[P, _, F, Q] =>
f(sq, sequence.last.thenArrow(arrow))
case _ => Sequence(sequence.first, sequence.last.thenArrow(arrow))
}
}
first match {
case sequence: Sequence[A, _, F, X] =>
f(sequence, last)
case _ => this
}
}
override def run(fa: F[A])(implicit F: Monad[F]): F[B] = {
@scala.annotation.tailrec
def f[P, Q, R](fp: F[P], a1: Arrow[P, F, Q], a2: Arrow[Q, F, R]): F[R] = a1 match {
case Sequence(fa, fl) => f(fp, fa.prepared, fl.thenArrow(a2))
case _ => a2.prepared match {
case Sequence(fa, fl) =>
f(a1.run(fp), fa, fl)
case _ => a2.run(a1.run(fp))
}
}
f(fa, first.prepared, last.prepared)
}
override def transform[G[_]](nt: F ~> G): Arrow[A, G, B] = {
@scala.annotation.tailrec
def f[P, Q, R, S](a1: Arrow[Q, F, R], a2: Arrow[R, F, S], acc: Arrow[P, G, Q]): Arrow[P, G, S] = a1 match {
case Sequence(s1, s2) => f(s1, s2.thenArrow(a2), acc)
case _ => a2 match {
case Sequence(s1, s2) =>
val x = a1.transform(nt)
val y = acc.thenArrow(x)
f(s1, s2, y)
case _ =>
acc.thenArrow(a1.transform(nt)).thenArrow(a2.transform(nt))
}
}
first.prepared match {
case Sequence(s1, s2) => f(s2, last, s1.transform(nt))
case _ => last.prepared match {
case Sequence(s1, s2) => f(s1, s2, first.transform(nt))
case _ => first.transform(nt).thenArrow(last.transform(nt))
}
}
}
}
def applied[A, F[_], B](f: Free[F, A => B]): Arrow[A, F, B] = Apply(f)
def bind[A, F[_], B](f: A => Free[F, B]): Arrow[A, F, B] = Bind(f)
def identity[F[_], A]: Arrow[A, F, A] = Identity()
}
|
# == Schema Information
#
# Table name: tool_members
#
# tool_type :string
# tool_id :integer
# role :integer
# user_id :integer not null
# invited_at :datetime
# reminded_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# response_id :integer
# id :integer not null, primary key
# roles :integer default([]), is an Array
#
FactoryGirl.define do
factory :tool_member do
association :user
trait :as_analysis_member do
association :tool, factory: :analysis
end
trait :as_inventory_member do
association :tool, factory: :inventory
end
trait :as_assessment_member do
association :tool, factory: :assessment
end
trait :as_facilitator do
roles [ToolMember.member_roles[:facilitator]]
end
trait :as_participant do
roles [ToolMember.member_roles[:participant]]
end
trait :as_facilitator_and_participant do
roles [ToolMember.member_roles[:facilitator], ToolMember.member_roles[:participant]]
end
end
end
|
const AbstractClubRepository = require('../abstractClubRepository');
const AbstractClubRepositoryError = require('../error/abstractClubRepositoryError');
test('No se puede instanciar un repositorio abstracto', () => {
let repoInstance;
try {
repoInstance = new AbstractClubRepository();
} catch (e) {
expect(e).toBeInstanceOf(AbstractClubRepositoryError);
} finally {
expect(repoInstance).toBeUndefined();
}
});
test('Se puede instanciar un repositorio concreto que herede del repositorio abstracto', () => {
const ConcreteRepository = class extends AbstractClubRepository {};
const respositoryInstance = new ConcreteRepository();
expect(respositoryInstance).toBeInstanceOf(ConcreteRepository);
expect(respositoryInstance).toBeInstanceOf(AbstractClubRepository);
});
|
package com.kotato.context.ecommerce.modules.order.domain.view
import com.kotato.context.ecommerce.modules.cart.domain.CartId
import com.kotato.context.ecommerce.modules.order.domain.OrderId
import com.kotato.context.ecommerce.modules.payment.domain.PaymentId
interface OrderViewRepository {
fun save(view: OrderView)
fun search(id: OrderId): OrderView?
fun searchByCartId(id: CartId): OrderView?
fun searchByPaymentId(id: PaymentId): OrderView?
}
|
using ERPXTpl.Enum;
using System.Collections.Generic;
namespace ERPXTpl.Model
{
public interface IInvoice
{
long Id { get; set; }
string OSSProcedureCountryCode { get; set; }
bool IsOSSProcedure { get; set; }
long? PurchasingPartyId { get; set; }
long? ReceivingPartyId { get; set; }
long? PaymentTypeId { get; set; }
long? BankAccountId { get; set; }
InvoiceType InvoiceType { get; set; }
string Description { get; set; }
string IssueDate { get; set; }
string Number { get; set; }
DocumentStatus Status { get; set; }
List<Item> Items { get; set; }
}
}
|
using System;
namespace DaisyFx.Events.Source
{
public class SourceExceptionEvent : IDaisyEventAsync
{
public SourceExceptionEvent(string chainName,
string sourceName,
int sourceIndex,
Guid sourceExecutionId,
Exception exception)
{
ChainName = chainName;
SourceName = sourceName;
SourceIndex = sourceIndex;
Exception = exception;
SourceExecutionId = sourceExecutionId;
}
public string ChainName { get; }
public string SourceName { get; }
public int SourceIndex { get; }
public Guid SourceExecutionId { get; }
public Exception Exception { get; }
}
}
|
fun main() {
val input = generateSequence(::readLine){readLine()}.joinToString("")
val lines = input.split("\n")
val count = lines.count()
println("$count lines")
val day24 = Day24(lines)
val result1 = day24.solvePart1()
println("Result #1 is $result1")
val result2 = day24.solvePart2(100)
println("Result #2 is $result2")
}
|
---
title: xlWindowView enumeration (Excel)
ms.prod: excel
api_name:
- Excel.XlWindowView
ms.assetid: b60b88f9-af0b-e06e-d4dc-8524e3118e4c
ms.date: 06/08/2017
---
# xlWindowView enumeration (Excel)
Specifies the view showing in the window.
|Name|Value|Description|
|:-----|:-----|:-----|
| **xlNormalView**|1|Normal.|
| **xlPageBreakPreview**|2|Page break preview.|
| **xlPageLayoutView**|3|Page layout view.|
|
DROP TABLE DASHBOARD_RESOURCE;
CREATE TABLE IF NOT EXISTS DASHBOARD_RESOURCE (
ID INTEGER NOT NULL AUTO_INCREMENT,
URL VARCHAR(100) NOT NULL,
OWNER VARCHAR(100) NOT NULL,
NAME VARCHAR(256) NOT NULL,
DESCRIPTION VARCHAR(1000),
PARENT_ID INTEGER NOT NULL,
LANDING_PAGE VARCHAR(100),
CONTENT LONGBLOB,
CONSTRAINT PK_DASHBOARD_RESOURCE PRIMARY KEY (URL,OWNER)
);
DROP TABLE WIDGET_RESOURCE;
CREATE TABLE IF NOT EXISTS WIDGET_RESOURCE (
WIDGET_ID VARCHAR(255) NOT NULL,
WIDGET_NAME VARCHAR(255) NOT NULL,
WIDGET_CONFIGS LONGBLOB,
CONSTRAINT PK_WIDGET_RESOURCE PRIMARY KEY (WIDGET_ID, WIDGET_NAME),
UNIQUE (WIDGET_NAME, WIDGET_NAME)
);
|
#pragma warning disable CS1591
using Newtonsoft.Json;
namespace Discord.API.Rest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
internal class DeleteMessagesParams
{
[JsonProperty("messages")]
public ulong[] MessageIds { get; }
public DeleteMessagesParams(ulong[] messageIds)
{
MessageIds = messageIds;
}
}
}
|
URLs, Schemes, and Resources
============================
这是最重要的 Redox 选择设计选择之一。这三个基本概念都非常纠结。
“一切都在一个URL”是什么意思?
--------------------------------------
“一切都是一个URL” 是 “一切是一个文件”的推广,允许更广泛地使用这种统一的界面方。
这些可用于在 “non-patchworky" 方式有效调节系统。
这个词是相当具误导性,因为 URLs 是方案和资源描述的仅仅是标识。因此,在这个意义上说“一切都是 Schemes,以 URLs 标识”更准确,但也不是很吸引人的。
那么,它是如何从文件中有什么不同?
----------------------------------
你能想到的 URLs 和隔离虚拟文件系统,它可以任意地结构化的(它们不必须是树状)和由程序任意定义。此外, "files" 不必表现 file-like! 更多关于这一点。
它开辟了很多可能性。
> [... TODO]
虚拟文件系统的想法是不是一个新的。如果你是一个Linux的计算机上,你应该尝试`cd`为`/ proc`,看看在那里发生了什么事情。
Redox 扩展了这一理念,更强大。
> TODO
|
# podstawy_cybernetyki
Pliki powstałe podczas zajęć z Podstaw Cybernetyki w Politechnice Gdańskiej.
Files created during basics of cybernetics lessons on Universitet of Technology in Gdansk.
|
require 'spec_helper'
require 'ostruct'
describe User do
let(:user) { create :user }
it { should have_many(:pull_requests) }
it { should have_many(:skills) }
it { should accept_nested_attributes_for(:skills) }
describe 'callbacks' do
describe 'before_save' do
describe '.check_email_changed' do
subject { build :user }
it 'is called if email changed' do
subject.should_receive(:check_email_changed)
subject.save
end
context 'email is present' do
it 'generates a confirmation token' do
subject.should_receive(:generate_confirmation_token)
subject.save
end
it 'sends a confirmation email' do
ConfirmationMailer.should_receive(:confirmation).and_return double("ConfirmationMailer", deliver: true)
subject.save
end
end
context 'email is blank' do
before do
subject.save
subject.email = nil
end
it 'doesnt generate a confirmation token' do
subject.should_not_receive(:generate_confirmation_token)
subject.save
end
it 'doesnt send a confirmation email' do
ConfirmationMailer.should_not_receive(:confirmation)
subject.save
end
end
end
end
end
%w[daily weekly].each do |frequency|
context "when user has subscribed to #{frequency} emails" do
before do
subject.email_frequency = frequency
end
it { should validate_presence_of(:email) }
end
end
describe '#collaborators' do
let!(:user) { create :user, :nickname => 'foobar' }
before do
3.times { create :user }
Rails.configuration.stub(:collaborators).and_return([ Hashie::Mash.new(:login => 'foobar') ])
end
subject { described_class.collaborators }
it { should eq [user] }
end
describe '.confirmed?' do
subject { user }
context 'email unconfirmed' do
it 'returns false' do
expect(subject).to_not be_confirmed
end
end
context 'email confirmed' do
before do
subject.confirm!
end
it 'returns true' do
expect(subject).to be_confirmed
end
end
end
describe '.confirm!' do
subject { user }
context 'no email configured' do
before do
subject.email = nil
end
it 'returns false' do
expect(subject.confirm!).to be_false
end
it 'adds an error to the user email field' do
subject.confirm!
expect(subject.errors.messages[:email]).to include 'Email is required for confirmation'
end
end
context 'email unconfirmed' do
it 'returns true' do
expect(subject.confirm!).to be_true
end
it 'sets the confirmed_at field' do
subject.confirm!
expect(subject.confirmed_at).to_not be_nil
end
it 'clears the confirmation_token field' do
subject.confirm!
expect(subject.confirmation_token).to be_nil
end
end
context 'email already confirmed' do
before do
subject.confirm!
end
it 'returns false' do
expect(subject.confirm!).to be_false
end
it 'adds an error to the user email field' do
subject.confirm!
expect(subject.errors.messages[:email]).to include 'Email is already confirmed'
end
end
end
describe '.generate_confirmation_token' do
subject { user }
before do
subject.update_attribute(:confirmation_token, nil)
end
it 'generates a confirmation token' do
subject.generate_confirmation_token
expect(subject.confirmation_token).to_not be_nil
end
end
describe '.check_email_changed' do
subject { user }
before do
subject.confirm!
end
let!(:old_token) { subject.confirmation_token }
context 'email didnt change' do
before do
subject.save
end
it 'doesnt reset the confirmed_at field' do
expect(subject.confirmed_at).to_not be_nil
end
it 'doesnt send an email' do
ConfirmationMailer.should_not_receive(:confirmation)
subject.save
end
end
context 'email did change' do
before do
subject.update_attribute(:email, 'another@email.addr')
end
it 'resets the confirmed_at field' do
expect(subject.confirmed_at).to be_nil
end
it 'generates a new token' do
expect(subject.confirmation_token).to_not eq old_token
end
it 'sends a confirmation email' do
stub_mailer = double(ConfirmationMailer)
stub_mailer.stub(:deliver)
ConfirmationMailer.should_receive(:confirmation).and_return(stub_mailer)
subject.update_attribute(:email, 'different@email.addr')
end
end
end
describe '.send_notification_mail' do
subject { user }
before do
subject.update_attribute(:email_frequency, 'daily')
end
context 'email unconfirmed' do
it 'doesnt send the notification email' do
ReminderMailer.should_not_receive(:daily)
subject.send_notification_email
end
end
context 'email confirmed' do
it 'sends the notification email' do
stub_mailer = double(ReminderMailer)
stub_mailer.stub(:deliver)
ReminderMailer.should_receive(:daily).and_return(stub_mailer)
subject.confirm!
subject.send_notification_email
end
end
end
describe '.estimate_skills' do
ENV['GITHUB_KEY'] = 'foobar'
let(:github_client) { double('github client') }
let(:repos) { Project::LANGUAGES.sample(3).map { |l| Hashie::Mash.new(:language => l) } }
before do
User.any_instance.unstub(:estimate_skills)
User.any_instance.stub(:github_client).and_return(github_client)
github_client.should_receive(:repos).and_return(repos)
end
subject { user }
its(:skills) { should have(3).skills }
end
describe '.languages' do
subject { user.languages }
context 'when the user has no skillz' do
it { should eq Project::LANGUAGES }
end
context 'when the user has skillz' do
before do
create :skill, :language => 'JavaScript', :user => user
end
it { should eq ['JavaScript'] }
end
end
describe '.download_pull_requests' do
let(:downloader) { double('downloader') }
let(:pull_request) { mock_pull_request }
before do
downloader.should_receive(:pull_requests).and_return([pull_request])
user.stub(:pull_request_downloader).and_return(downloader)
user.download_pull_requests
end
subject { user.pull_requests }
context 'when the pull request does not already exist' do
its(:length) { should eq 1 }
end
context 'when the pull request already exists' do
it { should_receive(:create).never }
its(:length) { should eq 1 }
end
end
describe '.pull_requests_count' do
subject { user.pull_requests_count }
context 'by default' do
it { should eq 0}
end
context 'when a pull request is added' do
before do
create :pull_request, :user => user
user.reload
end
it { should eq 1 }
end
end
describe '.to_param' do
subject { user.to_param }
it { should eq user.nickname }
end
describe "gifting" do
it "creates new gifts that belong to itself" do
user.new_gift.user.should == user
end
it "forwards attributes to newly created gifts" do
gift_factory = ->(attrs) { OpenStruct.new(attrs) }
user.gift_factory = gift_factory
user.new_gift(:foo => 'bar').foo.should == 'bar'
end
end
describe '.is_collaborator?' do
let(:collaborator) { create :user, nickname: "akira" }
let(:non_collaborator) { create :user }
before do
User.should_receive(:collaborators).and_return([collaborator])
end
it 'identifies if a user is a collaborator' do
collaborator.is_collaborator?.should eq(true)
end
it 'identifies if a user is not a collaborator' do
non_collaborator.is_collaborator?.should eq(false)
end
end
context "#scopes" do
let!(:haskell_users) { 2.times.map { create(:skill, language: "Haskell").user } }
it "by_language" do
User.by_language("haskell").should eq(haskell_users)
User.by_language("ruby").should eq([])
end
end
end
|
@using DD4T.Mvc.Html;
@model DD4T.ContentModel.Page
<h2>Home</h2>
Page title: @Model.Title<br />
Page id: @Model.Id<br />
Page version: @Model.Version<br />
View name: @Model.PageTemplate.MetadataFields["view"].Value<br />
Staging Url: @Model.MetadataFields["StagingUrl"].Value<br />
<div style="background-color:aqua">
@Html.RenderComponentPresentations()
</div>
|
$(function() {
var SERVER_URL = null;
var video_active = false;
var demo_running = false;
var NUM_TO_SHOW = 20;
var IMAGE_DISPLAY_WIDTH = 800;
var BOX_LINE_WIDTH = 6;
var FONT_SIZE = 48;
var TEXT_BOX_PAD = 5;
var PAD = 10;
// A nice set of colors
var WAD_COLORS = [
"rgb(173, 35, 35)", // Red
"rgb(42, 75, 215)", // Blue
"rgb(87, 87, 87)", // Dark Gray
"rgb(29, 105, 20)", // Green
"rgb(129, 74, 25)", // Brown
"rgb(129, 38, 192)", // Purple
"rgb(160, 160, 160)", // Lt Gray
"rgb(129, 197, 122)", // Lt green
"rgb(157, 175, 255)", // Lt blue
"rgb(41, 208, 208)", // Cyan
"rgb(255, 146, 51)", // Orange
"rgb(255, 238, 51)", // Yellow
"rgb(233, 222, 187)", // Tan
"rgb(255, 205, 243)", // Pink
// "rgb(255, 255, 255)", // White
"rgb(0, 0, 0)", // Black
];
// Overall, the client-side program flow works like this:
// First, we request a meadia stream object to access the webcam; once we have
// it we bind it to a hidden <video> element and play the video. Now we can
// talk to the server. To grab a frame, we write the video to a hidden canvas
// and get json-encoded pixel data from the canvas as a DataURL. We pass this
// to the server, which responds with annotations; we draw the image and
// annotations to a second (visible) canvas, and repeat. Note that the client
// does not include any sleeping; it should show frames as fast as the server
// can process them. Also, to make the whole thing dummy-proof, we read the
// server URL from a URL parameter. This should theoretically run on Android
// but I haven't tested it; unfortunately it won't work on iOS.
function get_url_param(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
if (results === null) return '';
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Draw image and annotations to the main canvas.
function draw_image(image_url, data) {
var pos = {
x: 0,
y: 0,
w: IMAGE_DISPLAY_WIDTH,
h: IMAGE_DISPLAY_WIDTH / data.width * data.height,
};
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// We need to make a deep copy of pos since we don't use it right away
pos = JSON.parse(JSON.stringify(pos));
var img = new Image();
img.onload = function() {
var ori_height = img.height;
var ori_width = img.width;
// First draw a white rectangle over everything
ctx.save();
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fill();
ctx.restore();
ctx.drawImage(img, pos.x, pos.y, pos.w, pos.h);
for (var i = 0; i < NUM_TO_SHOW && i < data.boxes.length; i++) {
var box = data.boxes[i];
var x = box[0], y = box[1],
w = box[2], h = box[3];
// We need to convert the box from the image-space coordinate system
// to the coordinate system of the canvas where we are drawing it.
// Also the input boxes are 1-indexed, and we want 0-indexed here.
x = x * (pos.w / img.width) + pos.x;
y = y * (pos.h / img.height) + pos.y;
w = w * (pos.w / img.width);
h = h * (pos.h / img.height);
// Draw the box
ctx.save();
ctx.lineWidth = BOX_LINE_WIDTH;
// ctx.strokeStyle = colors.foreground[i];
ctx.strokeStyle = WAD_COLORS[i % WAD_COLORS.length];
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.stroke();
ctx.restore();
// Now draw the text
ctx.save();
ctx.font = '18px sans-serif';
ctx.textBaseline = 'top';
var text_width = ctx.measureText(data.captions[i]).width;
ctx.save();
ctx.globalAlpha = 0.5;
ctx.fillStyle = WAD_COLORS[i % WAD_COLORS.length];
ctx.fillRect(x, y, text_width, 20);
ctx.restore();
ctx.fillText(data.captions[i], x, y);
ctx.restore();
}
}
img.src = image_url;
}
// Grab an image from the webcam, send it to the server, and draw the results.
function captureImage() {
// Make sure that the video is active.
if (!video_active) return;
// By this point the webcam is streaming to the video object.
// To get a frame, we draw the video to a canvas and then pull a data URL
// from the canvas that has encoded pixel data.
var video = document.getElementById('video');
var img_canvas = document.getElementById('img-canvas');
img_canvas.width = video.videoWidth;
img_canvas.height = video.videoHeight;
var ctx = img_canvas.getContext('2d');
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
// TODO: jpeg might not be supported on all browsers;
// detect this somehow and fall back to png
var img_url = img_canvas.toDataURL('image/jpeg');
// Send the frame to the server
var request = new XMLHttpRequest();
request.open('POST', SERVER_URL, true);
request.setRequestHeader('Content-Type', 'application/upload');
request.onload = function(e) {
// Once we have the response, render it and loop.
var annotations = JSON.parse(request.responseText);
draw_image(img_url, annotations);
if (demo_running) captureImage();
}
request.send('img=' + img_url);
}
function success(stream) {
var video = document.getElementById('video');
video.addEventListener('canplay', function() {
// Once the video is ready, set a flag and enable all buttons.
video_active = true;
var btn_ids = [
'#btn-less', '#btn-more',
'#btn-start', '#btn-stop',
'#btn-smaller', '#btn-bigger',
];
for (var i = 0; i < btn_ids.length; i++) {
$(btn_ids[i]).attr('disabled', false);
}
});
// Bind the webcam stream to the video object in the DOM.
var vendorURL = window.URL || window.webkitURL;
video.src = vendorURL.createObjectURL(stream);
video.play();
}
function errorCallback(error) {
console.log('ERROR: ', error);
}
// TODO: If these don't exist then show some sort of error message?
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var constraints = {
audio: false,
video: true,
};
navigator.getUserMedia(constraints, success, errorCallback);
// Add logic to buttons.
$('#btn-start').click(function() {
SERVER_URL = get_url_param('server_url');
console.log(SERVER_URL);
demo_running = true;
captureImage();
});
$('#btn-stop').click(function() { demo_running = false; });
$('#btn-less').click(function() { NUM_TO_SHOW--; });
$('#btn-more').click(function() { NUM_TO_SHOW++; });
$('#btn-smaller').click(function() { IMAGE_DISPLAY_WIDTH -= 100; });
$('#btn-bigger').click(function() { IMAGE_DISPLAY_WIDTH += 100; });
});
|
<?php
use siav\Lib\Database;
use siav\Lib\FrontController;
use siav\Lib\AbstractModel;
use siav\Models\OptionsModel;
ob_start();
/**
* Database setup
* Configuration de la base de données
*/
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'blogy-mvc');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
/**
* DTTC!
* (Don't Touch That Code!)
* (Ne touchez pas à ce code!)
*/
ini_set('display_errors', 1);
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('APP_PATH') ? null : define('APP_PATH', realpath(dirname(__file__)) .DS);
defined('HOST_NAME') ? null : define('HOST_NAME', '//' . $_SERVER['HTTP_HOST'] . '/');
define('LIB_PATH', APP_PATH . 'lib' .DS);
define('MODELS_PATH', APP_PATH . 'models' .DS);
define('VIEWS_PATH', APP_PATH . 'views' .DS);
define('CONTROLLERS_PATH', APP_PATH . 'controllers' .DS);
define('TEMPLATE_PATH', VIEWS_PATH . '_template' .DS);
defined('CSS_DIR') ? null : define('CSS_DIR', HOST_NAME . 'css/');
defined('VENDOR_DIR') ? null : define('VENDOR_DIR', HOST_NAME . 'vendor/');
defined('JS_DIR') ? null : define('JS_DIR', HOST_NAME . 'js/');
define('IMAGES_DIR', HOST_NAME . 'img/');
if (file_exists(APP_PATH . DS . 'lib' . DS . 'autoload.php')) {
require_once APP_PATH . DS . 'lib' . DS . 'autoload.php';
}
session_start();
$db = Database::getconnection();
AbstractModel::$db = $db;
define('TITLE', htmlspecialchars(OptionsModel::getTitle()));
$FrontController = new FrontController;
ob_flush();
|
/**
* @param {number[][]} buildings
* @return {number[][]}
*/
function getSkyline(buildings) {
function getSections(buildings) {
let pointSet = new Set();
buildings.forEach((building) => {
pointSet.add(building[0]);
pointSet.add(building[1]);
});
let pointArray = [];
pointSet.forEach((point) => {
pointArray.push(point);
});
pointArray = pointArray.sort((a, b) => a - b);
let sections = [];
for (let i = 0; i < pointArray.length - 1; i++) {
const section = [pointArray[i], pointArray[i + 1]];
sections[i] = section;
}
return sections;
}
function getHeights(sections) {
let newBuildings = [];
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
let height = 0;
for (let j = 0; j < buildings.length; j++) {
const building = buildings[j];
if (building[0] <= section[0] && building[1] >= section[1]) {
height = Math.max(height, building[2]);
}
}
newBuildings.push([...section, height]);
}
return newBuildings;
}
function merge(buildings) {
const newBuildings = [buildings[0]];
for (let i = 1; i < buildings.length; i++) {
const building1 = newBuildings[newBuildings.length - 1];
const building2 = buildings[i];
if (building1[2] === building2[2] && building1[1] === building2[0]) {
building1[1] = building2[1];
} else {
newBuildings.push(building2);
}
}
return newBuildings;
}
const sections = getSections(buildings);
const heightSections = getHeights(sections);
const mergedSections = merge(heightSections);
const skyline = [];
for (let i = 0; i < mergedSections.length; i++) {
const section = mergedSections[i];
skyline.push([section[0], section[2]]);
}
skyline.push([mergedSections[mergedSections.length - 1][1], 0]);
return skyline;
}
|
import io.ktor.application.ApplicationCallPipeline
import io.ktor.application.call
import io.ktor.http.content.defaultResource
import io.ktor.http.content.resources
import io.ktor.http.content.static
import io.ktor.http.content.staticBasePackage
import io.ktor.request.path
import io.ktor.response.respondRedirect
import io.ktor.routing.Route
fun Route.apiDoc() {
static("swagger") {
intercept(ApplicationCallPipeline.Call) {
call.request.path().takeUnless { it.endsWith("/") }?.also {
call.respondRedirect("$it/", true)
finish()
}
}
static("api") {
resources("swagger/api")
staticBasePackage = "swagger.api"
}
resources("swagger")
staticBasePackage = "swagger"
defaultResource("index.html")
}
}
|
<?php
$conecta = mysqli_connect("localhost", "root","" ,"Unip");
mysqli_set_charset($conecta,"utf8");
if( mysqli_connect_errno() ){
die("falha na conexão: " . mysqli_connect_errno());
}
?>
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Buildersoft.Andy.X.Storage.Data.Model.Enums
{
public enum DataStorageStatus
{
// TODO... Kqyre me mire qete pjese, mendoj statuset me ndryshe pasi qe jane server.
Active = 1,
Inactive= 2,
Blocked=3
}
}
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ppapi/shared_impl/audio_impl.h"
#include "base/logging.h"
namespace pp {
namespace shared_impl {
AudioImpl::AudioImpl()
: playing_(false),
shared_memory_size_(0),
callback_(NULL),
user_data_(NULL) {
}
AudioImpl::~AudioImpl() {
// Closing the socket causes the thread to exit - wait for it.
socket_->Close();
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
}
void AudioImpl::SetCallback(PPB_Audio_Callback callback, void* user_data) {
callback_ = callback;
user_data_ = user_data;
}
void AudioImpl::SetStartPlaybackState() {
DCHECK(!playing_);
DCHECK(!audio_thread_.get());
// If the socket doesn't exist, that means that the plugin has started before
// the browser has had a chance to create all the shared memory info and
// notify us. This is a common case. In this case, we just set the playing_
// flag and the playback will automatically start when that data is available
// in SetStreamInfo.
if (callback_ && socket_.get())
StartThread();
playing_ = true;
}
void AudioImpl::SetStopPlaybackState() {
DCHECK(playing_);
if (audio_thread_.get()) {
audio_thread_->Join();
audio_thread_.reset();
}
playing_ = false;
}
void AudioImpl::SetStreamInfo(base::SharedMemoryHandle shared_memory_handle,
size_t shared_memory_size,
base::SyncSocket::Handle socket_handle) {
socket_.reset(new base::SyncSocket(socket_handle));
shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));
shared_memory_size_ = shared_memory_size;
if (callback_) {
shared_memory_->Map(shared_memory_size_);
// In common case StartPlayback() was called before StreamCreated().
if (playing_)
StartThread();
}
}
void AudioImpl::StartThread() {
DCHECK(callback_);
DCHECK(!audio_thread_.get());
audio_thread_.reset(new base::DelegateSimpleThread(
this, "plugin_audio_thread"));
audio_thread_->Start();
}
void AudioImpl::Run() {
int pending_data;
void* buffer = shared_memory_->memory();
while (sizeof(pending_data) ==
socket_->Receive(&pending_data, sizeof(pending_data)) &&
pending_data >= 0) {
// Exit the thread on pause.
if (pending_data < 0)
return;
callback_(buffer, shared_memory_size_, user_data_);
}
}
} // namespace shared_impl
} // namespace pp
|
--------------------
-- Select
--------------------
-- SELECT * FROM aluno;
-- SELECT * FROM professor;
-- SELECT cpf, materia FROM professor;
---------------
-- Operadores
---------------
-- SELECT * FROM aluno WHERE matricula = 1;
-- SELECT * FROM aluno WHERE nome like "j%";
-- SELECT * FROM aluno where matricula > 1;
-- SELECT * FROM aluno where matricula < 3;
-- SELECT * FROM aluno where matricula >= 3;
-- SELECT * FROM aluno where matricula <= 3;
-- SELECT * FROM aluno WHERE matricula <> 1;
-- SELECT * FROM aluno WHERE matricula != 3;
--------------------------
-- Operadores Matematicos
--------------------------
-- SELECT * FROM aluno WHERE matricula = 1+1;
-- SELECT * FROM aluno WHERE matricula = 3 - 1;
-- SELECT * FROM aluno WHERE matricula = 2 * 1;
-- SELECT * FROM aluno WHERE matricula = 2 / 2;
--------------------------
-- Operadores lógicos
--------------------------
-- SELECT * FROM aluno WHERE matricula = 1 AND nome like "j%";
-- SELECT * FROM aluno WHERE matricula < 2 OR matricula = 1;
-- SELECT * FROM aluno WHERE matricula BETWEEN 1 and 3;
-- SELECT * FROM aluno WHERE matricula NOT BETWEEN 1 and 2;
-- SELECT * FROM aluno WHERE matricula IN (1, 2);
-- SELECT * FROM aluno WHERE matricula NOT IN (1, 2);
----------
-- Insert
----------
-- INSERT INTO aluno(nome, cpf, responsavel) VALUES("joão vitor", 1234567, "não Tem");
----------
-- Update
----------
-- UPDATE aluno SET nome="Caio Oof" WHERE matricula = 4;
----------
-- Delete
----------
-- DELETE FROM aluno WHERE matricula = 4;
---------------------
-- Comandos Avançados
---------------------
-- SELECT * FROM professor ORDER BY nome;
-- SELECT * FROM aluno ORDER BY matricula;
-- SELECT * FROM professor ORDER BY nome DESC;
-- SELECT * FROM aluno LIMIT 2;
-- SELECT * FROM aluno LIMIT 2 OFFSET 2;
-- SELECT COUNT(nome) FROM aluno;
-- SELECT count(matricula) FROM aluno GROUP BY matricula;
---------------------
-- Table
---------------------
--CREATE TABLE alunos(
-- matricula INTEGER PRIMARY KEY AUTOINCREMENT,
-- nome TEXT,
-- cpf INTEGER UNIQUE,
-- responsavel TXT
--);
-- SELECT * FROM alunos;
-- DROP TABLE alunos;
|
import React, { useState, useRef, useEffect } from 'react';
import { Card, config as defaultConfig } from 'ygo-card';
import { Card as CardInterface } from '@/utils/interface';
import { getCardData, getCardImageUrl } from '@/utils/api';
import './style.less';
interface cardBoxProps {
data?: object;
id?: string;
size?: number | number[];
config?: object;
onCreated?: Function;
onLoaded?: Function;
}
const CardBox: React.FC<cardBoxProps> = (props: cardBoxProps) => {
let { data, id, size = [813, 1185], config = defaultConfig, onCreated, onLoaded } = props;
const [cardData, setCardData] = useState(data);
const [card, setCard] = useState<CardInterface>();
const canvas = useRef(null);
const renderCard = (localData: any) => {
if (!localData) {
return;
}
const newCard = new Card({
data: localData,
config: config,
size: Array.isArray(size) ? size : [size, size / 813 * 1185],
canvas: canvas.current,
moldPath: '/mold',
fontsLoaded: onLoaded,
getPic: getCardImageUrl,
});
newCard.render();
setCard(newCard);
if (onCreated instanceof Function) {
onCreated(newCard);
}
};
useEffect(() => {
renderCard(data);
}, [canvas]);
useEffect(() => {
if (card) {
card.changeConfig(config);
}
}, [config]);
useEffect(() => {
if (!id) {
return;
}
getCardData(id).then(newData => {
setCardData(newData);
});
}, [id]);
useEffect(() => setCardData(data), [data])
useEffect(() => {
if (!card) {
// renderCard(cardData);
} else {
card.feedData(cardData);
}
}, [cardData]);
return (
<canvas ref={canvas} />
);
}
export default CardBox;
|
#!/usr/bin/env bash
OPENBLAS="$(brew --prefix openblas)" pip install numpy
|
import React, { ComponentType, FC } from 'react';
import { css } from '@emotion/core';
import { Link } from 'react-router-dom';
import { ListItem, ListItemText, ListItemIcon, Theme } from '@material-ui/core';
interface Props {
onClick?: () => void;
path?: string;
Icon: ComponentType;
className?: string;
name: string;
}
export const colorClass = (theme: Theme) => css`
color: ${theme.palette.secondary.light};
`;
const navItem = (theme: Theme) => css`
${colorClass(theme)};
border-left: 3px solid transparent;
cursor: pointer;
&:hover {
border-left: 3px solid ${theme.palette.primary.main};
}
`;
const SideNavEntry: FC<Props> = ({ onClick, path, Icon, name, className }) => {
const item = (
<ListItem css={theme => [navItem(theme), className]} onClick={onClick}>
<ListItemIcon css={colorClass}>
<Icon />
</ListItemIcon>
<ListItemText css={colorClass} disableTypography primary={name} />
</ListItem>
);
if (path) {
return <Link to={path}>{item}</Link>;
}
return item;
};
export default SideNavEntry;
|
import React, { Component } from 'react';
import propTypes from 'prop-types';
import { Icon, Card, Row, Col, Modal } from 'antd';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../../ducks/admin';
import NotFound from '../../components/NotFound';
import BasicInfo from './basic-info';
import CodingInfo from './coding-info';
import ResponsesInfo from './responses-info';
const tabTitles = [
{
key: 'basic',
tab: 'Basic Info'
},
{
key: 'coding',
tab: 'Coding Experience'
},
{
key: 'responses',
tab: 'Free Responses'
}
];
class ApplicantProfile extends Component {
constructor(props) {
super(props);
this.state = {
titleKey: 'basic',
loading: true,
timer: null,
adminModalShowing: false,
deleteModalShowing: false
};
this.onTabChange = this.onTabChange.bind(this);
this.stopLoading = this.stopLoading.bind(this);
this.showAdminModal = this.showAdminModal.bind(this);
this.handleAdminModalOk = this.handleAdminModalOk.bind(this);
this.handleAdminModalCancel = this.handleAdminModalCancel.bind(this);
this.showDeleteModal = this.showDeleteModal.bind(this);
this.handleDeleteModalOk = this.handleDeleteModalOk.bind(this);
this.handleDeleteModalCancel = this.handleDeleteModalCancel.bind(this);
}
componentWillMount() {
const timer = setTimeout(this.stopLoading, 500);
this.setState({ timer });
}
componentWillUnmount() {
clearTimeout(this.state.timer);
}
showAdminModal() {
this.setState({ adminModalShowing: true });
}
handleAdminModalOk() {
this.props.makeAdmin(this.props.data._id);
this.setState({ adminModalShowing: false });
}
handleAdminModalCancel() {
this.setState({ adminModalShowing: false });
}
showDeleteModal() {
this.setState({ deleteModalShowing: true });
}
handleDeleteModalOk() {
this.props.deleteApplicant(this.props.data._id);
this.setState({ deleteModalShowing: false });
}
handleDeleteModalCancel() {
this.setState({ deleteModalShowing: false });
}
stopLoading() {
this.setState({ loading: false });
}
onTabChange(titleKey) {
this.setState({ titleKey });
}
render() {
return !this.props.data || this.state.loading ? (
<NotFound />
) : (
<div>
<Row gutter={16}>
<Col span={8}>
<Modal
title="Confirm User Role Change"
visible={this.state.adminModalShowing}
onOk={this.handleAdminModalOk}
okText={'Make Admin'}
onCancel={this.handleAdminModalCancel}
>
<p>Are you sure you want to promote this user to an Admin?</p>
<p>This can only be reversed manually in the Database.</p>
</Modal>
<Modal
title="Confirm User Delete"
visible={this.state.deleteModalShowing}
onOk={this.handleDeleteModalOk}
okText={'Delete'}
okType={'danger'}
onCancel={this.handleDeleteModalCancel}
>
<p>Are you sure you want to Delete this user?</p>
<p>This action cannot be undone </p>
</Modal>
<Card
cover={
<img alt="example" src={this.props.data.github.avatar_url} />
}
actions={[
<Icon type="edit" onClick={() => alert('clicked edit user')} />,
<Icon type="delete" onClick={this.showDeleteModal} />,
<Icon type="usergroup-add" onClick={this.showAdminModal} />
]}
>
<Card.Meta
title={this.props.data.name}
description={
<div>
<p>
Application Status:{` ${this.props.data.application_status.toUpperCase()}`}
</p>
<a
target="_blank"
href={this.props.data.github.profile_url}
>
{this.props.data.github.profile_url}
</a>
</div>
}
/>
</Card>
</Col>
<Col span={16}>
<Card
style={{ width: '100%' }}
tabList={tabTitles}
onTabChange={key => this.onTabChange(key)}
>
{this.state.titleKey === 'basic' && (
<BasicInfo data={this.props.data} />
)}
{this.state.titleKey === 'coding' && (
<CodingInfo data={this.props.data} />
)}
{this.state.titleKey === 'responses' && (
<ResponsesInfo data={this.props.data} />
)}
</Card>
</Col>
</Row>
</div>
);
}
}
ApplicantProfile.propTypes = {
data: propTypes.object,
makeAdmin: propTypes.func,
deleteApplicant: propTypes.func
};
function mapStateToProps(state) {
return {
data: state.admin.currentApplicant
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(actions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(ApplicantProfile);
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AdminLogController extends Controller
{
public function index()
{
$logs = DB::table('logs')
->select('*')
->orderBy('created_at','desc')
->paginate(6);
return view('admin/logactivity',compact('logs'));
}
public function delog()
{
DB::table('logs')
->delete();
return redirect()->route('logaktifitas.index');
}
}
|
import 'package:json_annotation/json_annotation.dart';
import 'package:financialinvest/network/model/request/actions.dart';
import 'package:financialinvest/network/model/base_request.dart';
part 'accounts_balances_request.g.dart';
@JsonSerializable()
class AccountsBalancesRequest extends BaseRequest {
@JsonKey(name:'action')
String action;
@JsonKey(name:'accounts')
List<String> accounts;
AccountsBalancesRequest({List<String> accounts}) {
this.action = Actions.ACCOUNTS_BALANCES;
this.accounts = accounts ?? [];
}
factory AccountsBalancesRequest.fromJson(Map<String, dynamic> json) => _$AccountsBalancesRequestFromJson(json);
Map<String, dynamic> toJson() => _$AccountsBalancesRequestToJson(this);
}
|
package it.polimi.genomics.compiler
import scala.util.parsing.input.Positional
/**
* Created by pietro on 12/09/15.
*/
case class ParsedOperatorToken(operator_type : String) extends Positional{
}
|
package org.testmonkeys.maui.core.browser.popups;
import org.openqa.selenium.Alert;
/**
* JsAlert is the representation of a simple Alert box
*/
public class JsAlert {
protected Alert alert;
public JsAlert(Alert alert) {
this.alert = alert;
}
/**
* Gets the text displayed in the pop-up
*
* @return text displayed in pop-up
*/
public String getText() {
return alert.getText();
}
/**
* Accepts the pop-up, usually would press OK button, but depending on web page
* could be Confirm, Accept.
*/
public void accept() {
alert.accept();
}
}
|
<?php
namespace Tests\PHPCensor\Helper;
use PHPCensor\Helper\BuildInterpolator;
class BuildInterpolatorTest extends \PHPUnit\Framework\TestCase
{
/**
* @var BuildInterpolator
*/
protected $testedInterpolator;
protected function setUp()
{
parent::setup();
$this->testedInterpolator = new BuildInterpolator();
}
public function testInterpolate_LeavesStringsUnchangedByDefault()
{
$string = "Hello World";
$expectedOutput = "Hello World";
$actualOutput = $this->testedInterpolator->interpolate($string);
self::assertEquals($expectedOutput, $actualOutput);
}
public function testInterpolate_LeavesStringsUnchangedWhenBuildIsSet()
{
$build = $this->prophesize('PHPCensor\\Model\\Build')->reveal();
$string = "Hello World";
$expectedOutput = "Hello World";
$this->testedInterpolator->setupInterpolationVars(
$build,
"/buildpath/",
"php-censor.local"
);
$actualOutput = $this->testedInterpolator->interpolate($string);
self::assertEquals($expectedOutput, $actualOutput);
}
}
|
# 播客软件
首先,你需要一个播客客户端。如果是苹果手机,随系统安装的 Podcasts 已经很好用了。

如果是 Android 手机,在「[全平台播客订阅及收听指南](https://sspai.com/post/57960)」里找个合适的。
登录 [Podcast Maker](https://pcmaker.club/) 首页,每个频道都有 RSS 按钮,点击,RSS 地址即拷贝到操作系统剪贴板。

下一步,选择自己喜欢的播客软件,将拷贝到的 RSS 地址,导入到播客软件中。后文列举了几个播客软件的使用方法。
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Customer extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('Customers');
}
public function index($permission)
{
$data['list'] = $this->Customers->Customers_List();
$data['permission'] = $permission;
$this->load->view('customers/list', $data);
}
public function getCustomer(){
$data['data'] = $this->Customers->getCustomer($this->input->post());
$response['html'] = $this->load->view('customers/view_', $data, true);
echo json_encode($response);
}
public function setCustomer(){
$data = $this->Customers->setCustomer($this->input->post());
if($data == false)
{
echo json_encode(false);
}
else
{
echo json_encode(true);
}
}
public function visits(){
$data = $this->Customers->visits($this->input->post());
if($data == false)
{
echo json_encode(false);
}
else
{
echo json_encode($data);
}
}
public function status(){
$data['data'] = $this->Customers->status($this->input->post());
$response['html'] = $this->load->view('calendar/status_', $data, true);
echo json_encode($response);
}
}
|
# frozen_string_literal: true
class NoMatchForm
include ActiveModel::Model
attr_accessor :try_again
validates :try_again, inclusion: { in: %w[true false] }
def try_again?
ActiveModel::Type::Boolean.new.cast(try_again)
end
end
|
#pragma once
#include <bits/stdc++.h>
#include "../dynamictrees/LinkCutTree.h"
using namespace std;
// Support offline queries on connected components, after edges have been
// added or removed, using a Link Cut Tree
// Constructor Arguments:
// V: the number of vertices in the graph
// Fields:
// ans: a vector of integers with the answer for
// each query (1 is true, 0 is false for boolean queries)
// Functions:
// addEdge(v, w): adds an edge between vertices v and w
// removeEdge(v, w): removes an edge between vertices v and w, assuming
// an edge exists
// addConnectedQuery(v, w): adds a query asking whether v and w are in the
// same connected component
// addCntQuery(): adds a query asking for the number of connected components
// solveQueries(): solves all queries asked so far
// In practice, has a moderate constant, slower than
// DynamicConnectivityDivAndConq, faster than
// DynamicConnectivityLevelStructure
// Time Complexity:
// constructor: O(1)
// addEdge, removeEdge, addConnectedQuery, addCntQuery: O(1)
// solveQueries: O(V + Q (log Q + log V))
// Memory Complexity: O(V + Q) for Q edge additions/removals and queries
// Tested:
// https://codeforces.com/gym/100551/problem/A
// https://codeforces.com/gym/100551/problem/E
struct DynamicConnectivityLCT {
struct Node {
using Data = pair<int, int>; using Lazy = Data;
static const bool RANGE_UPDATES = false, RANGE_QUERIES = true;
static const bool RANGE_REVERSALS = true, HAS_PAR = true;
bool rev; Node *l, *r, *p; Data val, sbtr;
Node(const Data &v)
: rev(false), l(nullptr), r(nullptr), p(nullptr), val(v), sbtr(v) {}
void update() {
sbtr = val;
if (l) { sbtr = min(l->sbtr, sbtr); }
if (r) { sbtr = min(sbtr, r->sbtr); }
}
void propagate() {
if (rev) {
swap(l, r); rev = false;
if (l) l->reverse();
if (r) r->reverse();
}
}
void reverse() { rev = !rev; }
static Data qdef() { return make_pair(INT_MAX, -1); }
};
int V; vector<tuple<int, int, int, int>> queries; vector<int> ans;
DynamicConnectivityLCT(int V) : V(V) {}
void addEdge(int v, int w) {
if (v > w) swap(v, w);
queries.emplace_back(0, v, w, -1);
}
void removeEdge(int v, int w) {
if (v > w) swap(v, w);
queries.emplace_back(1, v, w, -1);
}
void addConnectedQuery(int v, int w) {
queries.emplace_back(2, v, w, queries.size());
}
void addCntQuery() { queries.emplace_back(3, -1, -1, queries.size()); }
void solveQueries() {
vector<pair<int, int>> edges; int Q = queries.size(); edges.reserve(Q);
for (auto &&q : queries) if (get<0>(q) == 0)
edges.emplace_back(get<1>(q), get<2>(q));
sort(edges.begin(), edges.end()); vector<int> last(edges.size(), Q);
for (int i = 0; i < Q; i++) {
int t, v, w, _; tie(t, v, w, _) = queries[i]; if (t == 0) {
int j = lower_bound(edges.begin(), edges.end(), make_pair(v, w))
- edges.begin();
get<3>(queries[i]) = last[j]; last[j] = i;
} else if (t == 1) {
int j = lower_bound(edges.begin(), edges.end(), make_pair(v, w))
- edges.begin();
int temp = get<3>(queries[get<3>(queries[i]) = last[j]]);
get<3>(queries[last[j]]) = i; last[j] = temp;
}
}
vector<pair<int, int>> tmp(V + Q, make_pair(INT_MAX, -1));
for (int i = 0; i < Q; i++) tmp[V + i] = make_pair(get<3>(queries[i]), i);
LCT<Node> lct(tmp); ans.clear(); for (int i = 0, cnt = V; i < Q; i++) {
int t, v, w, o; tie(t, v, w, o) = queries[i]; if (t == 0) {
if (v == w) continue;
int z, j; tie(z, j) = lct.queryPath(v, w); if (j != -1) {
if (z >= o) continue;
lct.cut(get<1>(queries[j]), V + j);
lct.cut(get<2>(queries[j]), V + j); cnt++;
}
lct.link(v, V + i); lct.link(w, V + i); cnt--;
} else if (t == 1) {
if (v == w) continue;
if (lct.connected(v, V + o)) {
lct.cut(v, V + o); lct.cut(w, V + o); cnt++;
}
} else if (t == 2) ans.push_back(lct.connected(v, w));
else if (t == 3) ans.push_back(cnt);
}
}
};
|
package mouse
import (
"time"
"github.com/oakmound/oak/v2/physics"
"github.com/oakmound/shiny/gesture"
)
// A GestureEvent is a conversion of a shiny Gesture to our local type so we
// don't need to import shiny variables in more places.
// GestureEvents contain information about mouse events that are not single actions,
// like drags, holds, and double clicks.
// Todo: standardize events to also use vectors for their position
type GestureEvent struct {
Drag bool
LongPress bool
DoublePress bool
InitialPos physics.Vector
CurrentPos physics.Vector
Time time.Time
}
// FromShinyGesture converts a shiny gesture.Event to a GestureEvent
func FromShinyGesture(shinyGesture gesture.Event) GestureEvent {
return GestureEvent{
shinyGesture.Drag,
shinyGesture.LongPress,
shinyGesture.DoublePress,
physics.NewVector(float64(shinyGesture.InitialPos.X), float64(shinyGesture.InitialPos.Y)),
physics.NewVector(float64(shinyGesture.CurrentPos.X), float64(shinyGesture.CurrentPos.Y)),
shinyGesture.Time,
}
}
|
package com.applicaster.quickline.auth
import com.applicaster.storage.LocalStorage
import com.google.gson.Gson
// todo: move to SDK
fun LocalStorage.removeItem(
key: String,
namespace: String? = null
) {
when {
namespace.isNullOrEmpty() -> remove(key)
else -> remove(key, namespace)
}
}
fun LocalStorage.storeString(
key: String,
value: String?,
namespace: String? = null
) {
when {
namespace.isNullOrEmpty() -> set(key, value)
else -> set(key, value, namespace)
}
}
fun LocalStorage.restoreString(
key: String,
namespace: String? = null
): String? = when {
namespace.isNullOrEmpty() -> get(key)
else -> get(key, namespace)
}
fun LocalStorage.storeLong(
key: String,
value: Long,
namespace: String? = null
) = storeString(key, value.toString(), namespace)
fun LocalStorage.restoreLong(
key: String,
namespace: String? = null
): Long? = restoreString(key, namespace)?.toLong()
fun LocalStorage.storeObject(
key: String,
value: Any?,
namespace: String? = null
) {
if (null == value) {
removeItem(key, namespace)
} else {
val json = Gson().toJson(value)
storeString(key, json, namespace)
}
}
fun <T> LocalStorage.restoreObject(
key: String,
cls: Class<T>,
namespace: String? = null
): T? where T : Any? {
val value = restoreString(key, namespace) ?: return null
return Gson().fromJson(value, cls)
}
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Education;
use App\Models\Subject;
class Candidate extends Model
{
use HasFactory;
protected $table = 'candidates';
public function education()
{
return $this->belongsTo(Education::class);
}
public function subject()
{
return $this->belongsTo(Subject::class);
}
}
|
---
templateKey: portfolio-post
title: "JoyCus: An Illustration System"
date: 2017-05-01T14:04:10.000Z
description: >-
This illustration system is a way to enrich a Loycus's visual language and say
more nuanced things that a logo, color scheme, typeface, or even words cannot
convey alone.
company: Loycus
location: "Madrid, Spain"
featuredpost: false
featuredimage: /img/joycus-gabo-brown-ui-ux.png
steps:
row:
- description: >-
In early 2019, we started a pitch at Loycus where I had the chance to
develop - for the first time in my life - a style for the new
illustration system. This system was going to be used all over the
Loycus Platform. Crazy enough the style that I proposed ended up being
selected to define Loycus Illustration's new identity.
I called the new style “JoyCus”, a mix between the words Joy-ful and
Cus-tomer. My intention was creating characters where joyfulness was
part of the illustration core.
After a long process of hard work from the amazing Loycus team, we
agreed that my illustrations were going to be the starting point in
creating a style guide and a toolkit. This style defined the palettes,
forms, and animations.
name: Introduction
number: 1
- description: >-

- description: >-
Human figures are used to add warmth, they help build an emotional
connection and tell the story. Characters are stylized and not
anatomically precise. Composed of irregular shapes, characters are
designed for corporal expression rather than individual identity or a
face expression itself.
name: Human Figures
number: 2
- description: >-

- description: >-
At the essence of Product, Illustration is the clever use of simple
primary shapes. Landscapes, animals, and people are created by adding
and subtracting geometric shapes from one another.
name: Exaggerated Forms
number: 3
- description: >-

- description: >-
Illustrations can create inspiring content for the context of what is
being served. Exaggerated forms are used for their expressive nature and
ability to fit into tight compositions. This unique style is important
for achieving effective integration between product interactions and
product environment.
name: Visual Principles
number: 4
- description: >-

- description: >-
Be open to new projects. As a UI - UX Designer sometimes we tend to
forget other divisions of design, and turns out you can be really
talented in some other areas as illustration, data analysis, etc.
name: Project Lessons
number: 5
tags:
- Illustration System
---
|
using UnityEngine;
using Zenject;
namespace Zenject.Tests.Factories.BindFactoryOne
{
//[CreateAssetMenu(fileName = "Bar", menuName = "Installers/Bar")]
public class Bar : ScriptableObject
{
[Inject]
public void Init(string value)
{
Value = value;
}
public string Value
{
get;
private set;
}
public class Factory : PlaceholderFactory<string, Bar>
{
}
}
}
|
import path from 'path';
import EventEmitter from 'core/EventEmitter';
import RenderProcess from 'video/RenderProcess';
import AudioProcess from 'video/AudioProcess';
import MergeProcess from 'video/MergeProcess';
import { api, logger } from 'view/global';
import { uniqueId } from 'utils/crypto';
export default class VideoRenderer extends EventEmitter {
constructor(renderer) {
super();
const { FFMPEG_BINARY } = api.getEnvironment();
this.renderer = renderer;
this.renderProcess = new RenderProcess(FFMPEG_BINARY);
this.audioProcess = new AudioProcess(FFMPEG_BINARY);
this.mergeProcess = new MergeProcess(FFMPEG_BINARY);
this.renderProcess.on('output', data => {
logger.log(data);
// Start requesting frames
if (!this.started) {
setTimeout(() => {
this.started = true;
this.emit('ready');
}, 1000);
}
});
this.audioProcess.on('output', data => {
logger.log(data);
});
this.mergeProcess.on('output', data => {
logger.log(data);
});
}
init(properties) {
const { videoFile, audioFile, ...config } = properties;
this.videoFile = videoFile;
this.audioFile = audioFile;
this.config = config;
const { fps, timeStart, timeEnd } = config;
this.started = false;
this.finished = false;
this.currentProcess = null;
this.startTime = 0;
this.frames = fps * (timeEnd - timeStart);
this.currentFrame = fps * timeStart;
this.lastFrame = this.currentFrame + this.frames;
}
async start() {
try {
this.renderer.stop();
this.startTime = Date.now();
const id = uniqueId();
const { audioFile, videoFile, renderProcess, audioProcess, mergeProcess } = this;
const { fps, quality, timeStart, timeEnd, format } = this.config;
const { TEMP_PATH } = api.getEnvironment();
const tempVideoFile = path.join(TEMP_PATH, `${id}.video`);
const tempAudioFile = path.join(TEMP_PATH, `${id}.audio`);
logger.log('Starting video render', id);
this.on('ready', () => {
this.processFrame();
});
// Render video
this.emit('status', 'Rendering video');
this.currentProcess = renderProcess;
const outputVideoFile = await renderProcess.start(tempVideoFile, format, fps, quality);
// Render audio
this.emit('status', 'Rendering audio');
this.currentProcess = audioProcess;
const outputAudioFile = await audioProcess.start(
audioFile,
tempAudioFile,
format,
timeStart,
timeEnd,
);
// Merge audio and video
this.emit('status', 'Merging audio and video');
this.currentProcess = mergeProcess;
await mergeProcess.start(outputVideoFile, outputAudioFile, videoFile);
} catch (error) {
logger.error(error);
throw error;
} finally {
this.finished = true;
this.emit('status', 'Finished');
this.emit('finished');
this.off('ready');
this.renderer.start();
}
}
stop() {
if (!this.finished) {
this.currentProcess?.stop();
logger.log('Video rendering stopped.');
}
}
async processFrame() {
if (this.finished) return;
const {
renderProcess,
frames,
currentFrame,
lastFrame,
startTime,
config: { fps },
} = this;
const image = await this.renderer.renderFrame(this.currentFrame, fps);
try {
renderProcess.push(image);
if (currentFrame < lastFrame) {
this.currentFrame += 1;
this.emit('ready');
} else {
renderProcess.end();
}
this.emit('stats', { frames, currentFrame, lastFrame, startTime });
} catch (error) {
if (error.message.indexOf('write EPIPE') < 0) {
throw error;
}
}
}
}
|
class Jaf::Deserializer
attr_reader :document
def initialize(document)
@document = document.permit!.to_h.deep_transform_keys { |key| key.to_s.underscore.to_sym }
end
def deserialize
ActionController::Parameters.new(attributes.merge(relationships || {}))
end
def data
document[:data]
end
def attributes
data[:attributes] || {}
end
def relationships
data[:relationships]&.inject({}) do |hash, (key, value)|
data = value[:data]
if to_one_relation?(data) && !relation_with_attributes?(data)
hash["#{key}_id".to_sym] = data[:id]
next hash
end
attributes_key = "#{key}_attributes".to_sym
if to_one_relation?(data) && relation_with_attributes?(data)
hash[attributes_key] = deserialize_to_one_with_attributes(data)
next hash
end
if to_many_relation?(data)
hash[attributes_key] = deserialize_many_relation(data)
next hash
end
end
end
def deserialize_to_one_with_attributes(data)
hash = {}
hash = hash.merge(data[:attributes]) if data[:attributes]&.present?
hash = hash.merge(id: data[:id]) if data[:id]&.present?
hash
end
def deserialize_many_relation(data)
data.map do |record|
hash = record[:attributes] || {}
hash = hash.merge(id: record[:id]) if record[:id]&.present?
hash
end
end
def to_one_relation?(data)
data.is_a? Hash
end
def to_many_relation?(data)
data.is_a? Array
end
def relation_with_attributes?(data)
to_one_relation?(data) ? data.include?(:attributes) : true
end
end
|
package com.jwplayer.jwplatform.rest;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.jwplayer.jwplatform.exception.JWPlatformException;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.GetRequest;
import com.mashape.unirest.request.HttpRequestWithBody;
import com.mashape.unirest.request.body.RequestBodyEntity;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Unirest.class })
public class HttpCallsTest {
@Test
public void testGetRequest() throws JWPlatformException, UnirestException {
mockStatic(Unirest.class);
final GetRequest getRequest = PowerMockito.mock(GetRequest.class);
@SuppressWarnings("unchecked")
final HttpResponse<JsonNode> response = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
final JSONObject expectedResponse = new JSONObject();
expectedResponse.put("status", 200);
when(response.getBody()).thenReturn(jsonNode);
when(response.getStatus()).thenReturn(200);
when(jsonNode.getObject()).thenReturn(expectedResponse);
when(response.getBody()).thenReturn(new JsonNode("[\"Success\"]"));
when(Unirest.get(anyString())).thenReturn(getRequest);
when(Unirest.get(anyString()).headers(anyMap())).thenReturn(getRequest);
when(Unirest.get(anyString()).headers(anyMap()).asJson()).thenReturn(response);
HttpCalls.request("v2/media/", new HashMap<>(), false, "GET", new HashMap<>());
PowerMockito.verifyStatic(Unirest.class, Mockito.atLeastOnce());
Unirest.get(anyString());
}
@Test
public void testPostRequest() throws UnirestException, JWPlatformException {
mockStatic(Unirest.class);
final HttpRequestWithBody requestBody = PowerMockito.mock(HttpRequestWithBody.class);
@SuppressWarnings("unchecked")
final HttpResponse<JsonNode> response = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
final JSONObject expectedResponse = new JSONObject();
expectedResponse.put("status", 200);
when(response.getBody()).thenReturn(jsonNode);
when(response.getStatus()).thenReturn(200);
when(jsonNode.getObject()).thenReturn(expectedResponse);
when(response.getBody()).thenReturn(new JsonNode("[\"Success\"]"));
when(Unirest.post(anyString())).thenReturn(requestBody);
when(Unirest.post(anyString()).headers(anyMap())).thenReturn(requestBody);
when(Unirest.post(anyString()).headers(anyMap()).asJson()).thenReturn(response);
when(response.getStatus()).thenReturn(200);
Map<String, String> params = new HashMap<>();
params.put("key", "value");
HttpCalls.request("v2/media/", params, false, "POST", new HashMap<>());
PowerMockito.verifyStatic(Unirest.class, Mockito.times(3));
Unirest.post(anyString());
}
@Test
public void testPostRequestBodyParams() throws UnirestException, JWPlatformException {
mockStatic(Unirest.class);
final HttpRequestWithBody requestWithBody = PowerMockito.mock(HttpRequestWithBody.class);
mockStatic(Unirest.class);
when(Unirest.post(anyString())).thenReturn(requestWithBody);
when(requestWithBody.headers(anyMap())).thenReturn(requestWithBody);
RequestBodyEntity entity = PowerMockito.mock(RequestBodyEntity.class);
when(requestWithBody.body(any(JSONObject.class))).thenReturn(entity);
@SuppressWarnings("unchecked")
final HttpResponse<JsonNode> response = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
final JSONObject expectedResponse = new JSONObject();
expectedResponse.put("status", 200);
when(entity.asJson()).thenReturn(response);
when(response.getBody()).thenReturn(jsonNode);
when(response.getStatus()).thenReturn(200);
when(jsonNode.getObject()).thenReturn(expectedResponse);
Map<String, String> params = new HashMap<>();
params.put("key", "value");
HttpCalls.request("v2/media/", params, true, "POST", new HashMap<>());
PowerMockito.verifyStatic(Unirest.class, Mockito.atLeastOnce());
Unirest.post(anyString());
}
@Test
public void testDeleteRequest() throws UnirestException, JWPlatformException {
mockStatic(Unirest.class);
final HttpRequestWithBody request = PowerMockito.mock(HttpRequestWithBody.class);
@SuppressWarnings("unchecked")
final HttpResponse<JsonNode> response = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
final JSONObject expectedResponse = new JSONObject();
expectedResponse.put("status", 200);
when(response.getBody()).thenReturn(jsonNode);
when(response.getStatus()).thenReturn(200);
when(jsonNode.getObject()).thenReturn(expectedResponse);
when(response.getBody()).thenReturn(new JsonNode("[\"Success\"]"));
when(Unirest.delete(anyString())).thenReturn(request);
when(Unirest.delete(anyString()).headers(anyMap())).thenReturn(request);
when(Unirest.delete(anyString()).headers(anyMap()).asJson()).thenReturn(response);
HttpCalls.request("v2/media/", new HashMap<>(), false, "DELETE", new HashMap<>());
PowerMockito.verifyStatic(Unirest.class, Mockito.atLeastOnce());
Unirest.delete(anyString());
}
@Test(expected = JWPlatformException.class)
public void testMethodNotSupported() throws JWPlatformException {
HttpCalls.request("v2/media/", new HashMap<>(), false, "SOMETHING", new HashMap<>());
}
@Test(expected = JWPlatformException.class)
public void testBadResult() throws UnirestException, JWPlatformException {
mockStatic(Unirest.class);
final HttpRequestWithBody requestWithBody = PowerMockito.mock(HttpRequestWithBody.class);
mockStatic(Unirest.class);
when(Unirest.post(anyString())).thenReturn(requestWithBody);
when(requestWithBody.headers(anyMap())).thenReturn(requestWithBody);
RequestBodyEntity entity = PowerMockito.mock(RequestBodyEntity.class);
when(requestWithBody.body(any(JSONObject.class))).thenReturn(entity);
when(entity.asJson()).thenThrow(new UnirestException("some exception"));
HttpCalls.request("v2/media", new HashMap<>(), true, "POST", new HashMap<>());
}
@Test
public void testPatchRequestBodyParams() throws UnirestException, JWPlatformException {
mockStatic(Unirest.class);
final HttpRequestWithBody requestWithBody = PowerMockito.mock(HttpRequestWithBody.class);
mockStatic(Unirest.class);
when(Unirest.patch(anyString())).thenReturn(requestWithBody);
when(requestWithBody.headers(anyMap())).thenReturn(requestWithBody);
RequestBodyEntity entity = PowerMockito.mock(RequestBodyEntity.class);
when(requestWithBody.body(any(JSONObject.class))).thenReturn(entity);
@SuppressWarnings("unchecked")
final HttpResponse<JsonNode> response = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
final JSONObject expectedResponse = new JSONObject();
expectedResponse.put("status", 200);
when(entity.asJson()).thenReturn(response);
when(response.getBody()).thenReturn(jsonNode);
when(response.getStatus()).thenReturn(200);
when(jsonNode.getObject()).thenReturn(expectedResponse);
Map<String, String> params = new HashMap<>();
params.put("key", "value");
HttpCalls.request("v2/media/", params, true, "PATCH", new HashMap<>());
PowerMockito.verifyStatic(Unirest.class, Mockito.atLeastOnce());
Unirest.patch(anyString());
}
@Test
public void testPatchRequestNoBodyParams() throws UnirestException, JWPlatformException {
mockStatic(Unirest.class);
final HttpRequestWithBody requestBody = PowerMockito.mock(HttpRequestWithBody.class);
@SuppressWarnings("unchecked")
final HttpResponse<JsonNode> response = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
final JSONObject expectedResponse = new JSONObject();
expectedResponse.put("status", 200);
when(response.getBody()).thenReturn(jsonNode);
when(response.getStatus()).thenReturn(200);
when(jsonNode.getObject()).thenReturn(expectedResponse);
when(response.getBody()).thenReturn(new JsonNode("[\"Success\"]"));
when(Unirest.patch(anyString())).thenReturn(requestBody);
when(Unirest.patch(anyString()).headers(anyMap())).thenReturn(requestBody);
when(Unirest.patch(anyString()).headers(anyMap()).asJson()).thenReturn(response);
when(response.getStatus()).thenReturn(200);
Map<String, String> params = new HashMap<>();
params.put("key", "value");
HttpCalls.request("v2/media/", params, false, "PATCH", new HashMap<>());
PowerMockito.verifyStatic(Unirest.class, Mockito.times(3));
Unirest.patch(anyString());
}
@Test
public void testPutRequestBodyParams() throws UnirestException, JWPlatformException {
mockStatic(Unirest.class);
final HttpRequestWithBody requestWithBody = PowerMockito.mock(HttpRequestWithBody.class);
mockStatic(Unirest.class);
when(Unirest.put(anyString())).thenReturn(requestWithBody);
when(requestWithBody.headers(anyMap())).thenReturn(requestWithBody);
RequestBodyEntity entity = PowerMockito.mock(RequestBodyEntity.class);
when(requestWithBody.body(any(JSONObject.class))).thenReturn(entity);
@SuppressWarnings("unchecked")
final HttpResponse<JsonNode> response = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
final JSONObject expectedResponse = new JSONObject();
expectedResponse.put("status", 200);
when(entity.asJson()).thenReturn(response);
when(response.getBody()).thenReturn(jsonNode);
when(response.getStatus()).thenReturn(200);
when(jsonNode.getObject()).thenReturn(expectedResponse);
Map<String, String> params = new HashMap<>();
params.put("key", "value");
HttpCalls.request("v2/media/", params, true, "PUT", new HashMap<>());
PowerMockito.verifyStatic(Unirest.class, Mockito.atLeastOnce());
Unirest.put(anyString());
}
@Test
public void testPutRequestNoBodyParams() throws UnirestException, JWPlatformException {
mockStatic(Unirest.class);
final HttpRequestWithBody requestBody = PowerMockito.mock(HttpRequestWithBody.class);
@SuppressWarnings("unchecked")
final HttpResponse<JsonNode> response = PowerMockito.mock(HttpResponse.class);
final JsonNode jsonNode = PowerMockito.mock(JsonNode.class);
final JSONObject expectedResponse = new JSONObject();
expectedResponse.put("status", 200);
when(response.getBody()).thenReturn(jsonNode);
when(response.getStatus()).thenReturn(200);
when(jsonNode.getObject()).thenReturn(expectedResponse);
when(response.getBody()).thenReturn(new JsonNode("[\"Success\"]"));
when(Unirest.put(anyString())).thenReturn(requestBody);
when(Unirest.put(anyString()).headers(anyMap())).thenReturn(requestBody);
when(Unirest.put(anyString()).headers(anyMap()).asJson()).thenReturn(response);
when(response.getStatus()).thenReturn(200);
Map<String, String> params = new HashMap<>();
params.put("key", "value");
HttpCalls.request("v2/media/", params, false, "PUT", new HashMap<>());
PowerMockito.verifyStatic(Unirest.class, Mockito.times(3));
Unirest.put(anyString());
}
}
|
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file serializationTestHelpers.h
* @brief
* @author Alex Cunningham
* @author Richard Roberts
* @date Feb 7, 2012
*/
#pragma once
#include <iostream>
#include <sstream>
#include <string>
#include <gtsam/base/serialization.h>
#include <boost/serialization/serialization.hpp>
#include <boost/filesystem.hpp>
// whether to print the serialized text to stdout
const bool verbose = false;
namespace gtsam {
namespace serializationTestHelpers {
// templated default object creation so we only need to declare one friend (if applicable)
template<class T>
T create() {
return T();
}
// Creates or empties a folder in the build folder and returns the relative path
inline boost::filesystem::path resetFilesystem(
boost::filesystem::path folder = "actual") {
boost::filesystem::remove_all(folder);
boost::filesystem::create_directory(folder);
return folder;
}
// Templated round-trip serialization
template<class T>
void roundtrip(const T& input, T& output) {
std::string serialized = serialize(input);
if (verbose) std::cout << serialized << std::endl << std::endl;
deserialize(serialized, output);
}
// Templated round-trip serialization using a file
template<class T>
void roundtripFile(const T& input, T& output) {
boost::filesystem::path path = resetFilesystem()/"graph.dat";
serializeToFile(input, path.string());
deserializeFromFile(path.string(), output);
}
// This version requires equality operator and uses string and file round-trips
template<class T>
bool equality(const T& input = T()) {
T output = create<T>(), outputf = create<T>();
roundtrip<T>(input,output);
roundtripFile<T>(input,outputf);
return (input==output) && (input==outputf);
}
// This version requires Testable
template<class T>
bool equalsObj(const T& input = T()) {
T output = create<T>();
roundtrip<T>(input,output);
return assert_equal(input, output);
}
// De-referenced version for pointers, requires equals method
template<class T>
bool equalsDereferenced(const T& input) {
T output = create<T>();
roundtrip<T>(input,output);
return input->equals(*output);
}
// Templated round-trip serialization using XML
template<class T>
void roundtripXML(const T& input, T& output) {
std::string serialized = serializeXML<T>(input);
if (verbose) std::cout << serialized << std::endl << std::endl;
deserializeXML(serialized, output);
}
// Templated round-trip serialization using XML File
template<class T>
void roundtripXMLFile(const T& input, T& output) {
boost::filesystem::path path = resetFilesystem()/"graph.xml";
serializeToXMLFile(input, path.string());
deserializeFromXMLFile(path.string(), output);
}
// This version requires equality operator
template<class T>
bool equalityXML(const T& input = T()) {
T output = create<T>(), outputf = create<T>();
roundtripXML<T>(input,output);
roundtripXMLFile<T>(input,outputf);
return (input==output) && (input==outputf);
}
// This version requires Testable
template<class T>
bool equalsXML(const T& input = T()) {
T output = create<T>();
roundtripXML<T>(input,output);
return assert_equal(input, output);
}
// This version is for pointers, requires equals method
template<class T>
bool equalsDereferencedXML(const T& input = T()) {
T output = create<T>();
roundtripXML<T>(input,output);
return input->equals(*output);
}
// Templated round-trip serialization using XML
template<class T>
void roundtripBinary(const T& input, T& output) {
std::string serialized = serializeBinary<T>(input);
if (verbose) std::cout << serialized << std::endl << std::endl;
deserializeBinary(serialized, output);
}
// Templated round-trip serialization using Binary file
template<class T>
void roundtripBinaryFile(const T& input, T& output) {
boost::filesystem::path path = resetFilesystem()/"graph.bin";
serializeToBinaryFile(input, path.string());
deserializeFromBinaryFile(path.string(), output);
}
// This version requires equality operator
template<class T>
bool equalityBinary(const T& input = T()) {
T output = create<T>(), outputf = create<T>();
roundtripBinary<T>(input,output);
roundtripBinaryFile<T>(input,outputf);
return (input==output) && (input==outputf);
}
// This version requires Testable
template<class T>
bool equalsBinary(const T& input = T()) {
T output = create<T>();
roundtripBinary<T>(input,output);
return assert_equal(input, output);
}
// This version is for pointers, requires equals method
template<class T>
bool equalsDereferencedBinary(const T& input = T()) {
T output = create<T>();
roundtripBinary<T>(input,output);
return input->equals(*output);
}
} // \namespace serializationTestHelpers
} // \namespace gtsam
|
var searchData=
[
['swarm_5fserver_2eh',['swarm_server.h',['../swarm__server_8h.html',1,'']]]
];
|
using Box2D.XNA;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Microsoft.Xna.Framework
{
public static class Vector2Extensions
{
public static Vector2 Rotate(this Vector2 vec, float angle)
{
var temp = (DVector2)vec;
return (Vector2)temp.Rotate(angle);
}
public static Point ToPoint(this Vector2 vec)
{
return new Point((int)vec.X, (int)vec.Y);
}
public static bool EpsilonCompare(this Vector2 lhs, Vector2 rhs, float e = Settings.b2_epsilon)
{
return Math.Abs(lhs.X - rhs.X) <= e
&& Math.Abs(lhs.Y - rhs.Y) <= e;
}
public static int GetQuadrant(this Vector2 vec)
{
if (vec.X >= 0) // Right-hand side, i.e. 0 or 3
{
if (vec.Y >= 0) return 0;
else return 3;
}
else // Left-hand side, i.e. 1 or 2
{
if (vec.Y >= 0) return 1;
else return 2;
}
}
public static bool IsInSameQuadrant(this Vector2 lhs, Vector2 rhs)
{
return lhs.GetQuadrant() == rhs.GetQuadrant();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.