text
stringlengths 27
775k
|
|---|
use strict;
use warnings;
use Errno;
use IO::Socket;
use BSD::Socket::Splice qw(setsplice getsplice geterror);
use Test::More tests => 15;
my $sl = IO::Socket::INET->new(
Proto => "tcp",
Listen => 1,
LocalAddr => "127.0.0.1",
) or die "server listen failed: $!";
my $rc = IO::Socket::INET->new(
Proto => "tcp",
PeerAddr => $sl->sockhost(),
PeerPort => $sl->sockport(),
) or die "relay connect failed: $!";
my $rl = IO::Socket::INET->new(
Proto => "tcp",
Listen => 1,
LocalAddr => "127.0.0.1",
) or die "relay listen failed: $!";
my $cc = IO::Socket::INET->new(
Proto => "tcp",
PeerAddr => $rl->sockhost(),
PeerPort => $rl->sockport(),
) or die "client connect failed: $!";
my $ra = $rl->accept() or die "relay accept failed: $!";
my $sa = $sl->accept() or die "server accept failed: $!";
ok(defined(setsplice($ra, $rc)), "relay setsplice")
or diag "relay setsplice failed: $!";
$cc->print("foo\n") or die "client print failed: $!";
is($sa->getline(), "foo\n", "server getline");
is(getsplice($ra), 4, "relay getsplice");
is(geterror($ra), 0, "relay geterror");
ok(defined(setsplice($ra)), "relay unsplice")
or diag "relay unsplice failed: $!";
ok(defined(setsplice($ra, $rc, 4)), "relay setsplice max")
or diag "relay setsplice max failed: $!";
$cc->print("foo\nbar\n") or die "client print max failed: $!";
# XXX ignore the short splice problem
is($sa->getline(), "foo\n", "server getline max");
is(getsplice($ra), 4, "relay getsplice max");
is(geterror($ra), Errno::EFBIG, "relay max geterror");
is($ra->getline(), "bar\n", "relay getline max");
ok(defined(setsplice($ra, $rc, undef, .1)), "relay setsplice idle")
or diag "relay setsplice idle failed: $!";
$cc->print("foo\n") or die "client print before idle failed: $!";
sleep 1;
$cc->print("bar\n") or die "client print after idle failed: $!";
is($sa->getline(), "foo\n", "server getline idle");
is(getsplice($ra), 4, "relay getsplice idle");
is(geterror($ra), Errno::ETIMEDOUT, "relay idle geterror");
is($ra->getline(), "bar\n", "relay getline idle");
|
using System;
using System.Collections.Generic;
using Estudo01;
namespace Estudo01
{
// Classes e métodos selados.
public /*sealed*/ class Professor : Pessoa
{
public double Salario { get; set; }
public /*sealed*/ override void Apresentar()
{
Console.WriteLine($"Olá, Sou o professor {Nome} e meu salário é de R${Salario} mil Reais.");
}
}
}
|
package httpmethod
import (
"testing"
"github.com/mtojek/go-url-fuzzer/configuration"
"github.com/mtojek/go-url-fuzzer/flow/messages"
"github.com/stretchr/testify/assert"
)
func TestNewEntryProducer(t *testing.T) {
assert := assert.New(t)
// given
methods := []string{"method_a", "method_b"}
builder := configuration.NewBuilder()
configuration := builder.Methods(methods).Build()
// when
sut := NewEntryProducer(configuration)
// then
assert.Equal(sut.methods, methods, "HTTP Methods should be the same as defined by used")
}
func TestOnRelativeURLThreeMethods(t *testing.T) {
assert := assert.New(t)
// given
anURL := "an_url"
entries := make(chan messages.Entry, 3)
methods := []string{"method_a", "method_b", "method_c"}
builder := configuration.NewBuilder()
configuration := builder.Methods(methods).Build()
sut := NewEntryProducer(configuration)
sut.Entry = entries
// when
sut.OnRelativeURL(anURL)
// then
assert.Equal(<-entries, messages.NewEntry(anURL, "method_a"), "Entries are not equal")
assert.Equal(<-entries, messages.NewEntry(anURL, "method_b"), "Entries are not equal")
assert.Equal(<-entries, messages.NewEntry(anURL, "method_c"), "Entries are not equal")
assert.Len(entries, 0, "Entries channel should be empty now")
}
func TestOnRelativeURLOneMethod(t *testing.T) {
assert := assert.New(t)
// given
anURL := "an_url"
entries := make(chan messages.Entry, 3)
methods := []string{"method_a"}
builder := configuration.NewBuilder()
configuration := builder.Methods(methods).Build()
sut := NewEntryProducer(configuration)
sut.Entry = entries
// when
sut.OnRelativeURL(anURL)
// then
assert.Equal(<-entries, messages.NewEntry(anURL, "method_a"), "Entries are not equal")
assert.Len(entries, 0, "Entries channel should be empty now")
}
|
# How to Contribute
Welcome, and thanks for considering contributing! In order to make our
review/development process easier, we have some guidelines to help you figure
out how to contribute to Affiliates.
## Reporting Issues
We use [Bugzilla][] to track issues and bugs for Firefox Affiliates. Any issues
with the website should be filed under the Firefox Affiliates product.
[Bugzilla]: https://bugzilla.mozilla.org/describecomponents.cgi?product=Firefox%20Affiliates
## Terminology
<dl>
<dt>Mothership</dt>
<dd>
The main portion of the Affiliates website, accessible at
https://affiliates.mozilla.org.
</dd>
<dt>Social Integration / Facebook App</dt>
<dd>
Facebook app implemented in the `facebook` Django app that links with the
mothership for certain stats.
</dd>
<dt>Banner</dt>
<dd>
An image link, text link, or other type of link that users can generate
using Affiliates.
</dd>
</dl>
## Development Guidelines
* Servers pull code from `master`. Development should happen in feature branches
and pull requests should merge back to `master` except in special cases.
* Python code should be covered by unit tests. JavaScript code is covered by
either [end-to-end tests][] or by manual testing.
* Python code should follow Mozilla's [general Webdev guidelines](py-bootcamp).
The same goes for our [JavaScript guidelines](js-bootcamp) and
[CSS guidelines](css-bootcamp).
* As allowed by PEP8, we use 99-characters-per-line for Python code and
72-characters-per-line for documentation/comments. Feel free to break these
guidelines for readability if necessary.
* Affiliates is based on [Playdoh][]. The [Playdoh Documentation][] explain
the features of Playdoh and how to develop a site based on it.
[end-to-end tests]: https://github.com/mozilla/Affiliates-Tests
[py-bootcamp]: http://mozweb.readthedocs.org/en/latest/coding.html#python
[js-bootcamp]: http://mozweb.readthedocs.org/en/latest/js-style.html#js-style
[css-bootcamp]: http://mozweb.readthedocs.org/en/latest/css-style.html
[Playdoh]: https://github.com/mozilla/playdoh/
[Playdoh Documentation]: http://playdoh.readthedocs.org/en/latest/
## Adding a Library
Due to licensing and deployment constraints, adding a library to Affiliates
requires a few things:
1. Add the library to the requirements files in the `requirements` folder.
`prod.txt` is for libraries required in production, `dev.txt` is for
libraries required for local development or running tests, and
`compiled.txt` is for libraries that need to be compiled.
2. If the library isn't compiled, install it in `vendor-local` using the
following Pip command (assuming we want to install the `chocobo` library from
PyPI):
```sh
pip install --no-install --build=vendor-local/packages -I chocobo
```
3. Add the path to your newly installed package to `vendor-local/vendor.pth`.
For example, if it was installed in `vendor-local/packages/chocobo`, you'd
add the line `pacakages/chocobo` to `vendor.pth`.
**Note:** Keep the installation changes in a separate commit from the rest of
your work to make code review easier.
## Additional Resources
* IRC: #affiliates on [irc.mozilla.org](https://wiki.mozilla.org/IRC).
* Planning/roadmap/meetings: [Affiliates on MozillaWiki](https://wiki.mozilla.org/Websites/Affiliates)
* [What is deployed on Affiliates servers?](http://mzl.la/affiliates-deployed)
|
# Copyright (C) 2021 Clinton Garwood
# MIT Open Source Initiative Approved License
# hw_assignment_5_clinton.py
# CIS-135 Python
# Homework Assignment #5 - Integer Evaluation
# Code Summary:
# This application takes three numbers (integers) from a
# user, and evaluates the numbers to determine the highest
# and lowest of those numbers. The high and low numbers are
# finally printed to the screen.
# Variable Declaration Area:
number_1 = 0
number_2 = 0
number_3 = 0
lowest_number = 0
highest_number = 0
# Welcome the user to the program
print("\nWelcome User")
print("\nThis program requires you to enter three integers (whole numbers).")
print("The highest and lowest numbers are determined and printed.\n")
# Obtain Data from the User
# Prompt user for each integer
number_1 = int(input("\tPlease enter the first integer: "))
number_2 = int(input("\tPlease enter the second integer: "))
number_3 = int(input("\tPlease enter the third integer: "))
print("\tThank you for the data")
# Compute the highest and lowest numbers:
# Compare Values to Determine the Lowest
# Get a result that is the lowest_number
# Set Lowest Number to be the value of number_1
lowest_number = number_1
# Compare if lowest_number is less than number_2
if (lowest_number > number_2):
# if true: update lowest_number with number_2
lowest_number = number_2
# Compare if lowest_number is less than number_3
if (lowest_number > number_3):
# if true: update lowest_number with number_3
lowest_number = number_3
# Compare Values to Determine the Highest
# Get a result that is the highest_number
# Set Highest Number to be the value of number_1
highest_number = number_1
# Compare if lowest_number is less than number_2
if (highest_number < number_2):
# if true: update lowest_number with number_2
highest_number = number_2
# Compare if lowest_number is less than number_3
if (highest_number < number_3):
# if true: update lowest_number with number_3
highest_number = number_3
# Display the results to the screen (highest and lowest)
print("\n\tThe lowest number is: ", lowest_number)
print("\tThe highest number is:", highest_number)
# Thank the user
print("\nThank you for using the integer evaluation app.")
|
package org.thingsboard.server.actors.application;
import lombok.Getter;
import org.thingsboard.server.common.data.id.ComputationId;
public class ComputationDeleteMessage {
@Getter
private final ComputationId computationId;
public ComputationDeleteMessage(ComputationId computationId) {
this.computationId = computationId;
}
}
|
class MembershipCount
@queue = :metrics
extend MetricsHelper
extend CapsuleHelper
# Count current members, split by level
def self.perform
# Get all members
organisations = CapsuleCRM::Organisation.find_all(:tag => 'Membership')
# Group by level
grouped = organisations.group_by{|org| field(org, "Membership", "Level").text }
# Count sizes of groups
counts = grouped.map{ |level,orgs| {level => orgs.count} }.reduce(:merge)
# Store
data = {
total: organisations.count,
by_level: counts
}
store_metric("membership-count", DateTime.now, data)
end
end
|
import Product from '../models/Products.model'
export const createProduct = async (req, res) => {
const {name, category, price, imgURL} = req.body
const newProduct = new Product({
name,
category,
price,
imgURL
})
const product = await newProduct.save()
res.status(201).json(product)
}
export const getProducts = async (req, res) => {
const products = await Product.find()
res.status(200).json(products)
}
export const getProduct = async (req, res) => {
const productId = req.params.id
const product = await Product.findById(productId)
res.status(200).json(product)
}
export const deleteProduct = async (req, res) => {
const productId = req.params.id
const product = await Product.findByIdAndDelete(productId)
res.status(200).json(product)
}
export const updateProduct = async (req, res) => {
const productId = req.params.id
const {name, category, price, imgURL} = req.body
const newProduct = {
name,
category,
price,
imgURL
}
const product = await Product.findByIdAndUpdate(productId, newProduct, {
new: true
})
res.status(200).json(product)
}
|
using Application.Boundaries.CreateCustomer.Validators;
using Infrastructure.CommandHandlerBase.Contracts;
using Infrastructure.CommandHandlerBase.Implementations;
using Infrastructure.CommandHandlerBase.Messages;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Application.Boundaries.CreateCustomer
{
public class CreateCustomerCommand : Command
{
public CreateCustomerCommand(string name, Guid? id = null, IList<ContactInput> contacts = null)
: base()
{
Name = name;
Id = id ?? Guid.NewGuid();
Contacts = contacts;
}
public Guid Id { get; private set; }
public string Name { get; private set; }
public IList<ContactInput> Contacts { get; private set; }
public override IValidationResult Validate()
{
var validatorResult = new CreateCustomerCommandValidador().Validate(this);
if (validatorResult.IsValid)
return CreateValidationResultForSuccess();
return CreateValidationResultForFail(validatorResult.Errors.Select(f => f.ErrorMessage));
}
private IValidationResult CreateValidationResultForSuccess()
{
return new ValidationResult();
}
private IValidationResult CreateValidationResultForFail(IEnumerable<string> errors)
{
return new ValidationResult(errors.ToArray());
}
}
}
|
FactoryGirl.define do
sequence(:registered_name) { |n| "Financial Advice #{n} Ltd." }
factory :firm, aliases: [:publishable_firm, :onboarded_firm] do
fca_number
registered_name
website_address { Faker::Internet.url }
in_person_advice_methods { create_list(:in_person_advice_method, rand(1..3)) }
free_initial_meeting { [true, false].sample }
initial_meeting_duration { create(:initial_meeting_duration) }
initial_advice_fee_structures { create_list(:initial_advice_fee_structure, rand(1..3)) }
ongoing_advice_fee_structures { create_list(:ongoing_advice_fee_structure, rand(1..3)) }
allowed_payment_methods { create_list(:allowed_payment_method, rand(1..3)) }
investment_sizes { create_list(:investment_size, rand(5..10)) }
retirement_income_products_flag true
pension_transfer_flag true
long_term_care_flag true
equity_release_flag true
inheritance_tax_and_estate_planning_flag true
wills_and_probate_flag true
status :independent
transient do
offices_count 1
end
after(:create) do |firm, evaluator|
create_list(:office, evaluator.offices_count, firm: firm)
firm.reload
end
transient do
advisers_count 1
end
after(:create) do |firm, evaluator|
create_list(:adviser, evaluator.advisers_count, firm: firm)
end
factory :trading_name, aliases: [:subsidiary] do
parent factory: :firm
end
factory :firm_with_advisers, traits: [:with_advisers]
factory :firm_without_advisers, traits: [:without_advisers]
factory :firm_with_offices, traits: [:with_offices]
factory :firm_without_offices, traits: [:without_offices]
factory :firm_with_principal, traits: [:with_principal]
factory :firm_with_no_business_split, traits: [:with_no_business_split]
factory :firm_with_remote_advice, traits: [:with_remote_advice]
factory :firm_with_subsidiaries, traits: [:with_trading_names]
factory :firm_with_trading_names, traits: [:with_trading_names]
factory :invalid_firm, traits: [:invalid], aliases: [:not_onboarded_firm]
trait :invalid do
# Invalidate the marker field without referencing it directly
__registered false
end
trait :with_no_business_split do
retirement_income_products_flag false
pension_transfer_flag false
long_term_care_flag false
equity_release_flag false
inheritance_tax_and_estate_planning_flag false
wills_and_probate_flag false
end
trait :with_advisers do
advisers_count 3
end
trait :without_advisers do
advisers_count 0
end
trait :with_principal do
principal { create(:principal) }
end
trait :with_offices do
offices_count 3
end
trait :without_offices do
offices_count 0
end
trait :with_remote_advice do
other_advice_methods { create_list(:other_advice_method, rand(1..3)) }
in_person_advice_methods []
end
trait :with_trading_names do
subsidiaries { create_list(:trading_name, 3, fca_number: fca_number) }
end
end
end
|
# frozen_string_literal: true
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :types do
include_examples 'plugin_tests'
let(:args) { [] }
it 'runs' do
expect(plugin.run(args)).to match(/service/)
end
describe 'types' do
let(:input) do
'types'
end
it 'runs' do
debugger.handle_input(input)
expect(output.string).to match(/service/)
end
end
end
|
# https://leetcode.com/problems/department-top-three-salaries/
WITH CTE as (SELECT *,
dense_rank() OVER (Partition by DepartmentId ORDER BY Salary desc) as salRank
FROM Employee
)
SELECT
d.Name as Department, e.Name as Employee, e.Salary as Salary
FROM Department d JOIN CTE e ON d.Id = e.DepartmentId
WHERE row_num in (1,2,3)
;
|
-- LegalEntityCountryCode must contain a valid three character GENC country code. U.S. Territories and Freely
-- Associated States must be submitted with country code = USA and their state/territory code; they cannot be submitted
-- with their GENC country code.
SELECT
dafa.row_number,
dafa.legal_entity_country_code
FROM detached_award_financial_assistance AS dafa
WHERE submission_id={0}
AND NOT EXISTS (
SELECT 1
FROM country_code AS cc
WHERE UPPER(dafa.legal_entity_country_code) = UPPER(cc.country_code)
AND cc.territory_free_state IS FALSE
);
|
import { IWorktopListState } from './worktop-list.state';
import { IDecorboardListState } from './decorboard-list.state';
import { IFoilListState } from './foil-list.state';
import { IAccessoryListState } from './accessory-list.state';
import { IApplianceListState } from './appliance-list.state';
export interface IMaterialsFeatureState {
worktopList: IWorktopListState;
decorboardList: IDecorboardListState;
foilList: IFoilListState;
accessoryList: IAccessoryListState;
applianceList: IApplianceListState;
}
|
DESCRIPTION
Build images used for system tests.
USAGE
./build.sh <library_name> [--images <image_names>] [--weblog-variant <variant_name>]
<library_name> can be one of cpp, dotnet, golang, java, nodejs, php, python or ruby.
More info on https://github.com/DataDog/system-tests/blob/master/docs/CLI/build.md
|
new function () {
var a = 1;
b(this.constructor.arguments.c);
};
|
default['wpblog']['mysql']['instance_name'] = 'wpdb'
default['wpblog']['mysql']['port'] = '3306'
default['wpblog']['mysql']['version'] = '5.7'
default['wpblog']['mysql']['prefix'] = 'wp_'
default['wpblog']['mysql']['charset'] = 'utf8'
default['wpblog']['mysql']['collate'] = ''
default['wpblog']['mysql']['wpuser'] = 'wpuser'
default['wpblog']['mysql']['bind_address'] = '127.0.0.1'
default['wpblog']['mysql']['query_cache_type'] = 1
default['wpblog']['mysql']['query_cache_limit'] = '1M'
default['wpblog']['mysql']['query_cache_size'] = '16M'
default['wpblog']['mysql']['default_storage_engine'] = 'InnoDB'
default['wpblog']['mysql']['key_buffer_size'] = '32M'
default['wpblog']['mysql']['myisam_recover'] = 'FORCE,BACKUP'
default['wpblog']['mysql']['max_allowed_packet'] = '16M'
default['wpblog']['mysql']['max_connect_errors'] = 1000000
default['wpblog']['mysql']['log_bin'] = '/var/lib/mysql-wpdb/mysql-bin'
default['wpblog']['mysql']['expire_logs_days'] = 14
default['wpblog']['mysql']['sync_binlog'] = 1
default['wpblog']['mysql']['tmp_table_size'] = '32M'
default['wpblog']['mysql']['max_heap_table_size'] = '32M'
default['wpblog']['mysql']['max_connections'] = 500
default['wpblog']['mysql']['thread_cache_size'] = 50
default['wpblog']['mysql']['open_files_limit'] = 65535
default['wpblog']['mysql']['table_definition_cache'] = 1024
default['wpblog']['mysql']['table_open_cache'] = 2048
default['wpblog']['mysql']['innodb_flush_method'] = 'O_DIRECT'
default['wpblog']['mysql']['innodb_log_files_in_group'] = 2
default['wpblog']['mysql']['innodb_log_file_size'] = '64M'
default['wpblog']['mysql']['innodb_flush_log_at_trx_commit'] = 1
default['wpblog']['mysql']['innodb_file_per_table'] = 1
default['wpblog']['mysql']['innodb_buffer_pool_size'] = '160M'
default['wpblog']['mysql']['log_error'] = '/var/lib/mysql-wpdb/mysql-error.log'
default['wpblog']['mysql']['log_queries_not_using_indexes'] = 1
default['wpblog']['mysql']['slow_query_log'] = 1
default['wpblog']['mysql']['slow_query_log_file'] = '/var/lib/mysql-wpdb/mysql-slow.log'
default['wpblog']['dir'] = '/var/www/wordpress'
default['wpblog']['wp_config_options'] = {}
default['nginx']['default_site_enabled'] = false
|
(ns my-money.app.controller.navigation-test
(:require [cljs.test :refer-macros [is are deftest testing use-fixtures]]
[my-money.app.state :as state]
[my-money.app.controller.navigation :as nc]
[tuck.core :as tuck]))
(deftest test-set-in-progress
(testing "Setting in progress to true"
(is (= true
(:in-progress (nc/set-in-progress state/initial-state true)))))
(testing "Setting in progress to false"
(is (= false
(:in-progress (nc/set-in-progress state/initial-state false))))))
(deftest test-modal
(testing "OpenModal sets :modal in state"
(is (= :test-modal
(:modal (tuck/process-event (nc/->OpenModal :test-modal) state/initial-state)))))
(testing "CloseModal clears :modal in state"
(is (= nil
(->> state/initial-state
(tuck/process-event (nc/->OpenModal :test-modal))
(tuck/process-event (nc/->CloseModal))
:modal)))))
|
//------------------------------------------------------------------------------
// <自動產生的>
// 這段程式碼是由工具產生的。
//
// 變更這個檔案可能會導致不正確的行為,而且如果已重新產生
// 程式碼,則會遺失變更。
// </自動產生的>
//------------------------------------------------------------------------------
namespace RunningAccount_7324.backendweb
{
public partial class WebForm3
{
/// <summary>
/// LinkButton1 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton LinkButton1;
/// <summary>
/// LinkButton2 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton LinkButton2;
/// <summary>
/// LinkButton3 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton LinkButton3;
/// <summary>
/// Literal1 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Literal Literal1;
/// <summary>
/// DropDownList1 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList DropDownList1;
/// <summary>
/// TextBox1 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox TextBox1;
/// <summary>
/// Literal2 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Literal Literal2;
/// <summary>
/// TextBox2 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox TextBox2;
/// <summary>
/// Literal3 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Literal Literal3;
/// <summary>
/// TextBox3 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox TextBox3;
/// <summary>
/// saveButton1 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Button saveButton1;
/// <summary>
/// deleteButton2 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Button deleteButton2;
}
}
|
<?php
namespace CWM\BroadWorksConnector\Ocip\Models;
/**
* CollaborateRoomScheduleScheduleOneTime
*
* @Groups [{"id":"c0d21ef9ba207c335d8347e5172fce1d:1150","type":"sequence"}]
*/
class CollaborateRoomScheduleScheduleOneTime
{
/**
* @ElementName startTime
* @Type string
* @Group c0d21ef9ba207c335d8347e5172fce1d:1150
* @var string|null
*/
private $startTime = null;
/**
* @ElementName duration
* @Type \CWM\BroadWorksConnector\Ocip\Models\CollaborateRoomScheduleDuration
* @Group c0d21ef9ba207c335d8347e5172fce1d:1150
* @var \CWM\BroadWorksConnector\Ocip\Models\CollaborateRoomScheduleDuration|null
*/
private $duration = null;
/**
* Getter for startTime
*
* @return string
*/
public function getStartTime()
{
return $this->startTime instanceof \CWM\BroadWorksConnector\Ocip\Nil ? null : $this->startTime;
}
/**
* Setter for startTime
*
* @param string $startTime
* @return $this
*/
public function setStartTime($startTime)
{
$this->startTime = $startTime;
return $this;
}
/**
* @return $this
*/
public function unsetStartTime()
{
$this->startTime = null;
return $this;
}
/**
* Getter for duration
*
* @return \CWM\BroadWorksConnector\Ocip\Models\CollaborateRoomScheduleDuration
*/
public function getDuration()
{
return $this->duration instanceof \CWM\BroadWorksConnector\Ocip\Nil ? null : $this->duration;
}
/**
* Setter for duration
*
* @param \CWM\BroadWorksConnector\Ocip\Models\CollaborateRoomScheduleDuration $duration
* @return $this
*/
public function setDuration(\CWM\BroadWorksConnector\Ocip\Models\CollaborateRoomScheduleDuration $duration)
{
$this->duration = $duration;
return $this;
}
/**
* @return $this
*/
public function unsetDuration()
{
$this->duration = null;
return $this;
}
}
|
<?php
/**
* This file is automatically generated by the wp_install.sh
*
* @file Config.php
*/
namespace Base;
class Config {
public function __construct() {
// For our purposes, the theme name is the folder name that holds the WP theme.
$this->theme_name = ( basename( dirname( dirname( __FILE__ ) ) ) );
// Declare possible variable defaults.
// just a very basic blog
$this->has_blog = false;
// ie ping back, track backs, etc.
$this->has_full_blog = false;
// blog comments
$this->has_comments = false;
$this->has_ecommerce = false;
$this->has_news_feed = false;
$this->has_search = true;
$this->has_image_slider = true;
$this->is_template_debug = true;
$this->has_api = false;
// FIXME not working: can rename,eg posts_name = 'Latest News'
$this->posts_name = 'Blog Posts';
// give editors access to menus
$this->editor_menus = false;
// these are all used by Organization schema
$this->client_name = 'dbsinteractive';
$this->client_phone = '866-562-7895'; // needs to be 000-000-0000 format
$this->canonical_url = 'https://www.dbswebsite.com/';
// custom login url
$this->login_url = '/dbs-login/';
$this->has_search=true;
$this->has_ecommerce=false;
$this->has_blog=false;
$this->has_full_blog=false;
$this->has_comments=false;
$this->has_news_feed=false;
$this->has_api='false';
$this->client_name='kaoprint';
$this->client_phone='null';
$this->canonical_url='https://.www.kaoprint.com';
$this->login_url='/kao-print-login/';
$this->posts_name='News';
$this->has_search=false;
$this->has_ecommerce=false;
$this->has_blog=false;
$this->has_full_blog=false;
$this->has_comments=false;
$this->has_news_feed=false;
$this->has_api='false';
$this->client_name='dbsclients';
$this->client_phone='null';
$this->canonical_url='https://.www.dbsclients.com';
$this->login_url='/dbs-login/';
$this->posts_name='Blog Posts';
}
}
|
a. TypeError: fizzbuzz() missing 1 required positional argument
b. No google, just knowledge
c. When a function with positional parameters is called, all parameters must be provided to it
|
package com.spitchenko.pokeapp.component.databinding.adapters
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.spitchenko.pokeapp.component.messaging.Message
import com.spitchenko.pokeapp.component.messaging.toCharSequence
@BindingAdapter("android:text")
fun TextView.setMessage(message: Message?) {
text = message?.toCharSequence(context)
}
|
package com.sike.handler;
import com.sike.entity.user.RoleEntity;
import com.sike.entity.user.RolePermissionEntity;
import com.sike.entity.user.UserEntity;
import com.sike.exception.BusinessException;
import com.sike.exception.ExceptionCodeEnum;
import com.sike.permission.PermissionAuthService;
import com.sike.permission.bean.PermissionBean;
import com.sike.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import static com.sike.constant.RoleConstants.ROLE_ADMIN;
@Component
public class PermissionAuthHandler implements PermissionAuthService {
@Autowired
SessionUtil sessionUtil;
@Override
public void authentication(HttpServletRequest request, Object[] args, PermissionBean permissionBean) {
UserEntity userEntity = sessionUtil.getUser(request);
if(userEntity == null){
throw new BusinessException(ExceptionCodeEnum.UNLOGIN);
}
List<RolePermissionEntity> permissions = new ArrayList<>();
for (RoleEntity roleEntity : userEntity.getRoles()) {
if (ROLE_ADMIN.equals(roleEntity.getName())) {
return;
}
permissions.addAll(roleEntity.getPermissions());
}
for (RolePermissionEntity permissionEntity : permissions) {
if (permissionEntity.getApplication().equals(permissionBean.getApplicationName()) &&
permissionEntity.getPermission().equals(permissionBean.getCode())) {
return;
}
}
throw new BusinessException(ExceptionCodeEnum.NO_PERMISSION);
}
}
|
// Copyright (c) 2016, Alexander Johr. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.
import 'dart:html';
import 'dart:async';
import 'package:js/js.dart';
import 'package:redmine_spent_time_visualizer/spent_time_visualizer.dart';
SpiderChart spiderChart = new SpiderChart(
subdivisionCapsCount: 5,
width: 1000,
height: 1000,
padding: new Padding(200,200,50,50));
main() async {
Element spendTimeVisualizerElement = querySelector(
'#spent_time_visualizer_container');
spiderChart.renderTarget = spendTimeVisualizerElement;
TextAreaElement importCsvInput = querySelector(
"#import_csv_input") as TextAreaElement;
String textAreaCsvInput = await getTextAreaInput();
importCsvInput.value = textAreaCsvInput;
String csvInput = await getExampleInput();
handleCsvInput(csvInput);
Element calculateButton = querySelector("#calculate_button");
calculateButton.onClick.listen((MouseEvent event) {
String csvInput = importCsvInput.value;
handleCsvInput(csvInput);
});
}
void handleCsvInput(String csvInput) {
RedmineData parsedExampleData = parseExampleData(csvInput);
DateTime minDate = getMinDate(parsedExampleData);
DateTime maxDate = getMaxDate(parsedExampleData).add(new Duration(days: 1));
visualizeDataInSpiderChart(parsedExampleData, minDate, maxDate, spiderChart);
createJQRangeSlider(minDate, maxDate, parsedExampleData, spiderChart);
}
Future<String> getExampleInput() async =>
await HttpRequest.getString("./input/input.dsv");
Future<String> getTextAreaInput() async =>
await HttpRequest.getString("./input/text_area_input.dsv");
RedmineData parseExampleData(String input) {
RedmineCsvParser redmineCsvParser = new RedmineCsvParser();
RedmineData parsedData = redmineCsvParser.parse(input);
return parsedData;
}
DateTime getMinDate(RedmineData parsedRedmineData) =>
parsedRedmineData.timeSpendList.fold(
parsedRedmineData.timeSpendList.first.date
, (DateTime prev, RedmineSpentTime current) {
bool currentIsMinDate = current.date.isBefore(prev);
if (currentIsMinDate) return current.date;
else return prev;
});
DateTime getMaxDate(RedmineData parsedRedmineData) =>
parsedRedmineData.timeSpendList.fold(
parsedRedmineData.timeSpendList.first.date
, (DateTime prev, RedmineSpentTime current) {
bool currentIsMaxDate = current.date.isAfter(prev);
if (currentIsMaxDate) return current.date;
else return prev;
});
void visualizeDataInSpiderChart(RedmineData parsedRedmineData, DateTime minDate,
DateTime maxDate, SpiderChart spiderChart) {
Map<String, num> hoursByMember = getHoursByMemberInTimePeriod(
parsedRedmineData, minDate, maxDate);
spiderChart.data = hoursByMember;
}
Map<String, num> getHoursByMemberInTimePeriod(RedmineData parsedRedmineData,
DateTime minDate, DateTime maxDate) {
Map<String, num> hoursByMemberInTimePeriod = new Map<String, num>();
List<RedmineMember> members = parsedRedmineData.members;
members.forEach((RedmineMember member) {
List<RedmineSpentTime> spentTimeInPeriod = getSpentTimeInTimePeriod(
member, minDate, maxDate);
num sumOfHours = getSumOfHours(spentTimeInPeriod);
hoursByMemberInTimePeriod.putIfAbsent(member.name, () => sumOfHours);
});
return hoursByMemberInTimePeriod;
}
List<RedmineSpentTime> getSpentTimeInTimePeriod(RedmineMember member,
DateTime minDate, DateTime maxDate) =>
member.timeSpendList.where((RedmineSpentTime spentTime) {
return spentTime.date.isAfter(minDate) &&
spentTime.date.isBefore(maxDate);
});
num getSumOfHours(List<RedmineSpentTime> spentTimeInPeriod) =>
spentTimeInPeriod.fold(
0, (num sum, RedmineSpentTime spentTime) => sum + spentTime.hours);
void createJQRangeSlider(DateTime minDate, DateTime maxDate,
RedmineData parsedExampleData, SpiderChart spiderChart) {
var dateRangeSliderElement = jQuery('#date_section_range_slider');
Date jsMinDate = new Date(minDate.year, minDate.month, minDate.day);
Date jsMaxDate = new Date(maxDate.year, maxDate.month, maxDate.day);
RangeSliderOptions rangeSliderOptions = new RangeSliderOptions(
wheelMode: 'zoom',
bounds: new RangeSliderDateRange(min: jsMinDate, max: jsMaxDate),
defaultValues: new RangeSliderDateRange(min: jsMinDate, max: jsMaxDate));
dateRangeSliderElement.dateRangeSlider(rangeSliderOptions);
void dateSliderValuesChanging(e, ValueChangeEventData data) {
DateTime minDate =
new DateTime.fromMillisecondsSinceEpoch(data.values.min.getTime());
DateTime maxDate =
new DateTime.fromMillisecondsSinceEpoch(data.values.max.getTime());
visualizeDataInSpiderChart(
parsedExampleData, minDate, maxDate, spiderChart);
}
jQuery('#date_section_range_slider')
.bind("valuesChanging", allowInterop(dateSliderValuesChanging));
}
|
//B
template <int mod>
struct ModInt{
int n;
ModInt():n(0){}
ModInt(int n_):n(n_ >= 0 ? n_%mod : mod - ((-n_)%mod) ){}
ModInt &operator+=(const ModInt &p){
if((n+=p.n) >= mod)n-=mod;
return *this;
}
ModInt &operator-=(const ModInt &p){
n+=mod-p.n;
if(n >= mod)n-=mod;
return *this;
}
ModInt &operator*=(const ModInt &p){
n = (int) ((1LL*n*p.n)%mod);
return *this;
}
ModInt &operator/=(const ModInt &p){
*this *= p.inverse();
return *this;
}
ModInt operator-() const {return ModInt(-n);}
ModInt operator+(const ModInt &p) const {return ModInt(*this) += p;}
ModInt operator-(const ModInt &p) const {return ModInt(*this) -= p;}
ModInt operator*(const ModInt &p) const {return ModInt(*this) *= p;}
ModInt operator/(const ModInt &p) const {return ModInt(*this) /= p;}
bool operator==(const ModInt &p) const {return n==p.n;}
bool operator<(const ModInt &p) const {return n<p.n;}
bool operator>(const ModInt &p) const {return n>p.n;}
bool operator>=(const ModInt &p) const {return n>=p.n;}
bool operator<=(const ModInt &p) const {return n<=p.n;}
bool operator!=(const ModInt &p) const {return n!=p.n;}
ModInt inverse() const {
int a = n,b = mod,u = 1,v = 0;
while(b){
int t = a/b;
a -= t*b; swap(a,b);
u -= t*v; swap(u,v);
}
return ModInt(u);
}
ModInt pow(int64_t z) const {
ModInt ret(1),mul(n);
while(z > 0){
if(z & 1) ret *= mul;
mul *= mul;
z >>= 1;
}
return ret;
}
friend ostream &operator<<(ostream &os, const ModInt &p){
return os << p.n;
}
friend istream &operator>>(istream &is, ModInt &a){
int64_t t;
is >> t;
a = ModInt<mod> (t);
return (is);
}
};
using mint = ModInt<mod>;
|
# Summary
* [Workshop](README.md)
* [Create account and get cluster](GETSTARTED.md)
* [Setup CLI Access for the cluster](exercise-0/README.md)
* [Exercise 1: Using OpenShift](exercise-1/README.md)
* [Exercise 2: Logging and Monitoring](exercise-2/README.md)
* [Exercise 3: Metrics and Dashboards](exercise-3/README.md)
* [Exercise 4: Autoscale Pods](exercise-4/README.md)
* [Exercise 5: Liveness and Readiness Probes](exercise-5/README.md)
* [Exercise 6: Deploying the Example Health App from CLI](exercise-6/README.md)
* [TODO: Runtime Security with Falco](exercise-7/README.md)
* [Certification](https://cognitiveclass.ai/courses/beyond-the-basics-istio-and-ibm-cloud-kubernetes-service/)
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\AppModel;
class PropertyBookingPayment extends Model
{
use AppModel;
use SoftDeletes;
protected $table = 'property_booking_payments';
public $timestamps = true;
protected $fillable = [
'booking_id',
'transaction_source_id',
'amount',
'exchange_rate',
'damage_insurance',
'comission',
'bank_fees',
'net_comission',
'post_date',
'comments',
'is_paid',
'audit_datetime',
'audit_user_id',
];
public function booking()
{
return $this->belongsTo('App\Models\PropertyBooking');
}
public function transactionSource()
{
return $this->belongsTo('App\Models\TransactionSource');
}
public function auditedBy()
{
return $this->belongsTo('App\Models\User', 'audit_user_id');
}
}
|
---
layout: post
title: Two Treatment Temperature Trial
date: '2016-12-22'
categories: ChOAS
tag: oyster
tag: temperature
tag: acidification
---
I went out to Manchester yesterday and checked on the TripleT (Two Treatment Trial) project.
Oysters are split between two tanks. One (on the left) getting cold water and the other getting ambient water.
<img src="http://eagle.fish.washington.edu/cnidarian/skitch/Camera_Uploads_1E0C80BC.png" alt="Camera_Uploads_1E0C80BC.png"/>
<img src="http://eagle.fish.washington.edu/cnidarian/skitch/Camera_Uploads_1E0C810A.png" alt="Camera_Uploads_1E0C810A.png"/>
Algae is pumped in
<img src="http://eagle.fish.washington.edu/cnidarian/skitch/Camera_Uploads_1E0C81F0.png" alt="Camera_Uploads_1E0C81F0.png"/>
<img src="http://eagle.fish.washington.edu/cnidarian/skitch/Camera_Uploads_1E0C813E.png" alt="Camera_Uploads_1E0C813E.png"/>
<img src="http://eagle.fish.washington.edu/cnidarian/skitch/Camera_Uploads_1E0C8158.png" alt="Camera_Uploads_1E0C8158.png"/>
Algae is a little different in the tanks
via Jade
```
Cold input 39,408
Cold inside tank: 24,824
Warm input: 40,669
Warm inside tank: 9619
```
Temperature differences are about 2 C
<img src="http://eagle.fish.washington.edu/cnidarian/skitch/Camera_Uploads_1E0C817C.png" alt="Camera_Uploads_1E0C817C.png"/>
Will look into raising temperature in ambient (cold is being dropped to 6) and need to ID solution for algae.
|
#!/bin/bash
SERVER=$1
for i in `cat $SERVER`
do
echo $i
ssh $i -C " yum clean all && yum install ipmitool OpenIPMI* -y "
ssh $i -C " service ipmi start and chkconfig impi on "
done
|
using System.Windows.Markup;
namespace wpf_material_dialogs.Interfaces
{
/// <summary>
/// Interface IButtons
/// Implements the <see cref="IAddChild" />
/// </summary>
/// <seealso cref="IAddChild" />
/// <remarks>This is used to identify UserControl objects that can be used as buttons.</remarks>
public interface IButtons : IAddChild
{
}
}
|
/*
rules = [
"class:scalafix.test.NoDummy",
]
*/
// An anchor disable rules until the end of a file
// scalafix:off NoDummy
package test.escapeHatch
object AnchorEOF {
object Dummy
}
|
package tests.rescala.fullmv.mirrors
import org.scalatest.funsuite.AnyFunSuite
import rescala.fullmv.DistributedFullMVApi.{
FullMVEngine, FullMVTurnLocalClone, SerializationGraphTracking, FullMVTurnImpl, SubsumableLock
}
import rescala.fullmv.sgt.synchronization.{Blocked, Locked, SubsumableLock, Successful}
import scala.concurrent.duration.Duration
import scala.concurrent.Await
class LockUnionFindMirrorTest extends AnyFunSuite {
test("double remote direct lock/block/unlock works") {
val host1a = new FullMVEngine(Duration.Zero, "host1a")
val host1b = new FullMVEngine(Duration.Zero, "host1b")
val hostX = new FullMVEngine(Duration.Zero, "hostX")
val turn1 = host1a.newTurn()
val lock1 = turn1.subsumableLock.get
turn1.beginExecuting()
val turn1onB = FullMVTurnLocalClone(turn1, host1b)
val turn1onX = FullMVTurnLocalClone(turn1onB, hostX)
assert(lock1.refCount.get === 1) // turn1
assert(host1b.lockHost.getInstance(lock1.guid).isEmpty)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
val lock1onX = Await.result(turn1onX.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(lock1onX.remotelyEquals(lock1))
assert((lock1onX !== lock1) === true)
assert(lock1.refCount.get === 2) // turn1, lock1onB
val lock1onB = host1b.lockHost.getInstance(lock1.guid).get
assert(lock1onB.refCount.get === 1) // lock1onX
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
assert(lock1onX.refCount.get === 1) // thread
assert(Await.result(turn1.tryLock(), Duration.Zero) === Blocked)
assert(lock1.refCount.get === 2) // turn1, lock1onB
assert(host1b.lockHost.getInstance(lock1.guid).get === lock1onB)
assert(lock1onB.refCount.get === 1) // lock1onX
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
assert(lock1onX.refCount.get === 1) // thread
assert(Await.result(turn1onB.tryLock(), Duration.Zero) === Blocked)
assert(lock1.refCount.get === 2) // turn1, lock1onB
assert(host1b.lockHost.getInstance(lock1.guid).get === lock1onB)
assert(lock1onB.refCount.get === 1) // lock1onX
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
assert(lock1onX.refCount.get === 1) // thread
assert(Await.result(turn1onX.tryLock(), Duration.Zero) === Blocked)
assert(lock1.refCount.get === 2) // turn1, lock1onB
assert(host1b.lockHost.getInstance(lock1.guid).get === lock1onB)
assert(lock1onB.refCount.get === 1) // lock1onX
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
assert(lock1onX.refCount.get === 1) // thread
lock1onX.asyncUnlock()
assert(lock1.refCount.get === 1) // turn1
assert(lock1onB.refCount.get <= 0)
assert(host1b.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1onX.refCount.get <= 0)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
val lock1onB2 = Await.result(turn1onB.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(lock1onB.remotelyEquals(lock1onB2))
assert(lock1onB !== lock1onB2)
assert(lock1.refCount.get === 2) // turn1, lock1onB2
assert(host1b.lockHost.getInstance(lock1.guid).get === lock1onB2)
assert(lock1onB2.refCount.get === 1) // thread
assert(lock1onB.refCount.get <= 0)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1onX.refCount.get <= 0)
lock1onB2.asyncUnlock()
assert(lock1.refCount.get === 1) // turn1
assert(host1b.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1onB2.refCount.get <= 0)
assert(lock1onB.refCount.get <= 0)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1onX.refCount.get <= 0)
turn1.completeExecuting()
}
test("blocked remote direct subsume leaves reference counts intact") {
val host1a = new FullMVEngine(Duration.Zero, "host1a")
val host1b = new FullMVEngine(Duration.Zero, "host1b")
val hostX = new FullMVEngine(Duration.Zero, "hostX")
val turn1 = host1a.newTurn()
val lock1 = turn1.subsumableLock.get
turn1.beginExecuting()
val turn1onB = FullMVTurnLocalClone(turn1, host1b)
val turn1onX = FullMVTurnLocalClone(turn1onB, hostX)
assert(lock1.refCount.get === 1) // turn1
assert(host1b.lockHost.getInstance(lock1.guid).isEmpty)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
val lock1onX = Await.result(turn1onX.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(lock1onX.remotelyEquals(lock1))
assert((lock1onX !== lock1) === true)
assert(lock1.refCount.get === 2) // turn1, lock1onB
val lock1onB = host1b.lockHost.getInstance(lock1.guid).get
assert(lock1onB.refCount.get === 1) // lock1onX
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
assert(lock1onX.refCount.get === 1) // thread
val turn2 = hostX.newTurn()
turn2.beginExecuting()
val l2 = Await.result(turn2.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(l2.refCount.get === 2) // turn2, thread
assert(Await.result(turn1onX.trySubsume(l2), Duration.Zero) === Blocked)
assert(lock1.refCount.get === 2) // turn1, lock1onB
assert(host1b.lockHost.getInstance(lock1.guid).get === lock1onB)
assert(lock1onB.refCount.get === 1) // lock1onX
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
assert(lock1onX.refCount.get === 1) // thread
assert(l2.refCount.get === 2) // turn2, thread
}
test("single remote direct subsume and gc works") {
val host1 = new FullMVEngine(Duration.Zero, "host1")
val turn1 = host1.newTurn()
turn1.beginExecuting()
val lock1 = turn1.subsumableLock.get
val host2 = new FullMVEngine(Duration.Zero, "host2")
val turn1on2 = FullMVTurnLocalClone(turn1, host2)
val lock1on2 = Await.result(turn1on2.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(lock1on2.remotelyEquals(lock1))
assert(lock1on2 !== lock1)
assert(lock1.refCount.get === 2) // turn1, lock1on2
assert(lock1on2.refCount.get === 1) // thread
val turn2 = host2.newTurn()
turn2.beginExecuting()
val lock2 = turn2.subsumableLock.get
assert(Await.result(turn2.trySubsume(lock1on2), Duration.Zero) === Successful)
assert(lock1.refCount.get === 2) // turn1, lock1on2
assert(lock1on2.refCount.get === 2) // thread, turn2
assert(lock2.refCount.get <= 0)
lock1on2.asyncUnlock()
assert(lock1.refCount.get === 2) // turn1, lock1on2
assert(lock1on2.refCount.get === 1) // turn2
assert(lock2.refCount.get <= 0)
turn1.completeExecuting()
assert(lock1.refCount.get === 1) // lock1on2
assert(lock1on2.refCount.get === 1) // turn2
assert(lock2.refCount.get <= 0)
turn2.completeExecuting()
assert(lock1.refCount.get <= 0)
assert(lock1on2.refCount.get <= 0)
assert(lock2.refCount.get <= 0)
}
test("quintuple remote direct single subsume and gc works") {
val host1a = new FullMVEngine(Duration.Zero, "host1a")
val host1b = new FullMVEngine(Duration.Zero, "host1b")
val host2a = new FullMVEngine(Duration.Zero, "host2a")
val host2b = new FullMVEngine(Duration.Zero, "host2b")
val hostX = new FullMVEngine(Duration.Zero, "hostX")
val turn1 = host1a.newTurn()
val lock1 = turn1.subsumableLock.get
turn1.beginExecuting()
val turn2 = host2a.newTurn()
val lock2 = turn2.subsumableLock.get
turn2.beginExecuting()
val turn1onB = FullMVTurnLocalClone(turn1, host1b)
val turn1onX = FullMVTurnLocalClone(turn1onB, hostX)
val turn2onB = FullMVTurnLocalClone(turn2, host2b)
val turn2onX = FullMVTurnLocalClone(turn2onB, hostX)
assert(lock1.refCount.get === 1) // turn1
assert(host1a.lockHost.getInstance(lock1.guid).get === lock1)
assert(host1b.lockHost.getInstance(lock1.guid).isEmpty)
assert(host2a.lockHost.getInstance(lock1.guid).isEmpty)
assert(host2b.lockHost.getInstance(lock1.guid).isEmpty)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock2.refCount.get === 1) // turn2
assert(host1a.lockHost.getInstance(lock2.guid).isEmpty)
assert(host1b.lockHost.getInstance(lock2.guid).isEmpty)
assert(host2a.lockHost.getInstance(lock2.guid).get === lock2)
assert(host2b.lockHost.getInstance(lock2.guid).isEmpty)
assert(hostX.lockHost.getInstance(lock2.guid).isEmpty)
val lock1onX = Await.result(turn1onX.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(lock1onX.remotelyEquals(lock1))
assert((lock1onX !== lock1) === true)
assert(lock1.refCount.get === 2) // turn1, lock1onB
assert(host1a.lockHost.getInstance(lock1.guid).get === lock1)
val lock1onB = host1b.lockHost.getInstance(lock1.guid).get
assert(lock1onB.refCount.get === 1) // lock1onX
assert(host2a.lockHost.getInstance(lock1.guid).isEmpty)
assert(host2b.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1onX.refCount.get === 1) // thread
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
assert(lock2.refCount.get === 1) // turn2
assert(host1a.lockHost.getInstance(lock2.guid).isEmpty)
assert(host1b.lockHost.getInstance(lock2.guid).isEmpty)
assert(host2a.lockHost.getInstance(lock2.guid).get === lock2)
assert(host2b.lockHost.getInstance(lock2.guid).isEmpty)
assert(hostX.lockHost.getInstance(lock2.guid).isEmpty)
assert(Await.result(turn2onX.trySubsume(lock1onX), Duration.Zero) === Successful)
assert(lock1.refCount.get === 2) // turn1, lock1onB
assert(host1a.lockHost.getInstance(lock1.guid).get === lock1)
assert(lock1onB.refCount.get === 1) // lock1onX
assert(host1b.lockHost.getInstance(lock1.guid).get === lock1onB)
val lock1on2a = host2a.lockHost.getInstance(lock1.guid).get
assert(lock1on2a.refCount.get === 1) // turn2
val lock1on2b = host2b.lockHost.getInstance(lock1.guid).get
assert(lock1on2b.refCount.get === 1) // lock1on2a
assert(lock1onX.refCount.get === 2) // thread, lock1on2b
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
assert(lock2.refCount.get <= 0)
assert(host1a.lockHost.getInstance(lock2.guid).isEmpty)
assert(host1b.lockHost.getInstance(lock2.guid).isEmpty)
assert(host2a.lockHost.getInstance(lock2.guid).isEmpty)
assert(host2b.lockHost.getInstance(lock2.guid).isEmpty)
assert(hostX.lockHost.getInstance(lock2.guid).isEmpty)
lock1onX.asyncUnlock()
assert(lock1.refCount.get === 2) // turn1, lock1onB
assert(host1a.lockHost.getInstance(lock1.guid).get === lock1)
assert(lock1onB.refCount.get === 1) // lock1onX
assert(host1b.lockHost.getInstance(lock1.guid).get === lock1onB)
assert(lock1on2a.refCount.get === 1) // turn2
assert(host2a.lockHost.getInstance(lock1.guid).get === lock1on2a)
assert(lock1on2b.refCount.get === 1) // lock1on2a
assert(host2b.lockHost.getInstance(lock1.guid).get === lock1on2b)
assert(lock1onX.refCount.get === 1) // lock1on2b
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
turn1.completeExecuting()
assert(lock1.refCount.get === 1) // lock1onB
assert(host1a.lockHost.getInstance(lock1.guid).get === lock1)
assert(lock1onB.refCount.get === 1) // lock1onX
assert(host1b.lockHost.getInstance(lock1.guid).get === lock1onB)
assert(lock1on2a.refCount.get === 1) // turn2
assert(host2a.lockHost.getInstance(lock1.guid).get === lock1on2a)
assert(lock1on2b.refCount.get === 1) // lock1on2a
assert(host2b.lockHost.getInstance(lock1.guid).get === lock1on2b)
assert(lock1onX.refCount.get === 1) // lock1on2b
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
turn2.completeExecuting()
assert(host1a.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1.refCount.get <= 0)
assert(host1b.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1onB.refCount.get <= 0)
assert(host2a.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1on2a.refCount.get <= 0)
assert(host2b.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1on2b.refCount.get <= 0)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock1onX.refCount.get <= 0)
}
test("direct reentrant tryLock works") {
val host1a = new FullMVEngine(Duration.Zero, "host1a")
val host1b = new FullMVEngine(Duration.Zero, "host1b")
val hostX = new FullMVEngine(Duration.Zero, "hostX")
val turn1 = host1a.newTurn()
turn1.beginExecuting()
val lock1 = turn1.subsumableLock.get()
if (SubsumableLock.DEBUG) println(s"reentrant trylock with $turn1 under $lock1")
val turn1onB = FullMVTurnLocalClone(turn1, host1b)
val turn1onX = FullMVTurnLocalClone(turn1onB, hostX)
assert(lock1.refCount.get === 1) // turn1
assert(host1a.lockHost.getInstance(lock1.guid).get === lock1)
assert(host1b.lockHost.getInstance(lock1.guid).isEmpty)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
val l1 = Await.result(turn1onX.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(lock1.refCount.get === 2) // Turn1, lock1onB
assert(host1a.lockHost.getInstance(lock1.guid).get === lock1)
val lock1onB = host1b.lockHost.getInstance(lock1.guid).get
assert(lock1onB.refCount.get === 1) // lock1onX
val lock1onX = hostX.lockHost.getInstance(lock1.guid).get
assert(lock1onX.refCount.get === 1) // thread
assert(Await.result(turn1onX.trySubsume(l1), Duration.Zero) === Successful)
assert(lock1.refCount.get === 2) // Turn1, lock1onB
assert(host1a.lockHost.getInstance(lock1.guid).get === lock1)
assert(lock1onB.refCount.get === 1) // lock1onX
assert(host1b.lockHost.getInstance(lock1.guid).get === lock1onB)
assert(lock1onX.refCount.get === 1) // thread
assert(hostX.lockHost.getInstance(lock1.guid).get === lock1onX)
l1.asyncUnlock()
assert(lock1.refCount.get === 1) // turn1
assert(host1a.lockHost.getInstance(lock1.guid).get === lock1)
assert(host1b.lockHost.getInstance(lock1.guid).isEmpty)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
turn1.completeExecuting()
assert(lock1.refCount.get <= 1)
assert(host1a.lockHost.getInstance(lock1.guid).isEmpty)
assert(host1b.lockHost.getInstance(lock1.guid).isEmpty)
assert(hostX.lockHost.getInstance(lock1.guid).isEmpty)
}
test("remote indirect and direct blocked-self trySubsume works") {
val host1 = new FullMVEngine(Duration.Zero, "host1")
val host2 = new FullMVEngine(Duration.Zero, "host2")
val turn1 = host1.newTurn()
turn1.beginExecuting()
val lock1 = turn1.subsumableLock.get()
val turn2 = host2.newTurn()
turn2.beginExecuting()
val lock2 = turn2.subsumableLock.get()
val turn3 = host2.newTurn()
turn3.beginExecuting()
val lock3 = turn3.subsumableLock.get()
val l3 = Await.result(turn3.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
val turn1on2 = FullMVTurnLocalClone(turn1, host2)
val lock1on2 = Await.result(turn1on2.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(Await.result(turn2.trySubsume(lock1on2), Duration.Zero) === Successful)
assert(lock1on2.remotelyEquals(lock1))
assert(lock1on2 !== lock1)
assert(lock1.refCount.get === 2) // turn1, lock1on2
assert(lock1on2.refCount.get === 2) // turn2, thread
assert(lock2.refCount.get <= 0)
assert(lock3.refCount.get === 2) // turn3, thread
assert(host1.lockHost.getInstance(lock3.guid).isEmpty)
assert(Await.result(turn2.trySubsume(l3), Duration.Zero) === Blocked)
assert(lock1.refCount.get === 2) // turn1, lock1on2
assert(lock1on2.refCount.get === 2) // turn2, thread
assert(lock3.refCount.get === 2) // turn3, thread
assert(host1.lockHost.getInstance(lock3.guid).isEmpty)
lock1on2.asyncUnlock()
assert(lock1.refCount.get === 2) // turn1, lock1on2
assert(lock1on2.refCount.get === 1) // turn2
assert(host2.lockHost.getInstance(lock1.guid).get === lock1on2)
assert(lock3.refCount.get === 2) // turn3, thread
assert(host1.lockHost.getInstance(lock3.guid).isEmpty)
assert(Await.result(turn2.trySubsume(l3), Duration.Zero) === Successful)
assert(lock1.refCount.get === 1) // turn1
assert(lock1on2.refCount.get <= 0) // turn2
assert(host2.lockHost.getInstance(lock1.guid).isEmpty)
assert(lock3.refCount.get === 4) // turn2, turn3, thread, lock3on1
val lock3on1 = host1.lockHost.getInstance(lock3.guid).get
assert(lock3on1.refCount.get === 1) // lock1
}
test("remote direct blocked-other trySubsume works") {
val host1 = new FullMVEngine(Duration.Zero, "host1")
val host2 = new FullMVEngine(Duration.Zero, "host2")
val host3 = new FullMVEngine(Duration.Zero, "host3")
val turn1 = host1.newTurn()
turn1.beginExecuting()
val lock1 = turn1.subsumableLock.get()
val turn2 = host2.newTurn()
turn2.beginExecuting()
val lock2 = turn2.subsumableLock.get()
val turn3 = host3.newTurn()
turn3.beginExecuting()
val lock3 = turn3.subsumableLock.get()
val turn1on2 = FullMVTurnLocalClone(turn1, host2)
val lock1on2 = Await.result(turn1on2.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(Await.result(turn2.trySubsume(lock1on2), Duration.Zero) === Successful)
lock1on2.asyncUnlock()
val turn3on1 = FullMVTurnLocalClone(turn3, host1)
val lock3on1 = Await.result(turn3on1.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(Await.result(turn1.trySubsume(lock3on1), Duration.Zero) === Successful)
assert(lock1on2.remotelyEquals(lock1))
assert(lock1on2 !== lock1)
assert(lock3on1.remotelyEquals(lock3))
assert(lock3on1 !== lock3)
assert(lock1.refCount.get === 1) // lock1on2
assert(lock1on2.refCount.get === 1) // turn2
assert(lock2.refCount.get <= 0)
assert(lock3.refCount.get === 2) // turn3, lock3on1
assert(lock3on1.refCount.get === 3) // turn1, lock1, thread
val turn4 = host2.newTurn()
turn4.beginExecuting()
val lock4 = turn3.subsumableLock.get()
val l4 = Await.result(turn4.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(lock4.refCount.get === 2) // turn4, thread
assert(Await.result(turn2.trySubsume(l4), Duration.Zero) === Blocked)
assert(lock1.refCount.get <= 0)
assert(lock1on2.refCount.get <= 0)
assert(lock3.refCount.get === 2) // turn3, lock3on1
assert(lock3on1.refCount.get === 3) // turn1, lock3on2, thread
val lock3on2 = host2.lockHost.getInstance(lock3.guid).get
assert(lock3on2.refCount.get === 1) // turn2
assert(lock4.refCount.get === 2) // turn4, thread
}
test("remote indirect and direct other trySubsume works") {
val host1 = new FullMVEngine(Duration.Zero, "host1")
val host2 = new FullMVEngine(Duration.Zero, "host2")
val host3 = new FullMVEngine(Duration.Zero, "host3")
val turn1 = host1.newTurn()
turn1.beginExecuting()
val lock1 = turn1.subsumableLock.get()
val turn2 = host2.newTurn()
turn2.beginExecuting()
val lock2 = turn2.subsumableLock.get()
val turn3 = host3.newTurn()
turn3.beginExecuting()
val lock3 = turn3.subsumableLock.get()
val turn1on2 = FullMVTurnLocalClone(turn1, host2)
val lock1on2 = Await.result(turn1on2.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(Await.result(turn2.trySubsume(lock1on2), Duration.Zero) === Successful)
lock1on2.asyncUnlock()
val turn3on1 = FullMVTurnLocalClone(turn3, host1)
val lock3on1 = Await.result(turn3on1.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(Await.result(turn1.trySubsume(lock3on1), Duration.Zero) === Successful)
lock3on1.asyncUnlock()
assert(lock1on2.remotelyEquals(lock1))
assert(lock1on2 !== lock1)
assert(lock3on1.remotelyEquals(lock3))
assert(lock3on1 !== lock3)
assert(lock1.refCount.get === 1) // lock1on2
assert(lock1on2.refCount.get === 1) // turn2
assert(lock2.refCount.get <= 0)
assert(lock3.refCount.get === 2) // turn3, lock3on1
assert(lock3on1.refCount.get === 2) // turn1, lock1
val turn4 = host2.newTurn()
turn4.beginExecuting()
val lock4 = turn4.subsumableLock.get()
val l4 = Await.result(turn4.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(lock4.refCount.get === 2) // turn4, thread
assert(Await.result(turn2.trySubsume(l4), Duration.Zero) === Successful)
assert(lock1.refCount.get <= 0)
assert(lock1on2.refCount.get <= 0)
assert(lock3.refCount.get === 2) // turn3, lock3on1
assert(lock3on1.refCount.get === 1) // turn1
assert(lock4.refCount.get === 4) // turn2, turn4, lock4on1, thread
val lock4on1 = host1.lockHost.getInstance(lock4.guid).get
assert(lock4on1.refCount.get === 1) // lock4on3
val lock4on3 = host3.lockHost.getInstance(lock4.guid).get
assert(lock4on3.refCount.get === 1) // lock3
}
test("remote indirect trylock failure works") {
val host1 = new FullMVEngine(Duration.Zero, "host1")
val host2 = new FullMVEngine(Duration.Zero, "host2")
val turn1 = host1.newTurn()
turn1.beginExecuting()
val lock1 = turn1.subsumableLock.get
val turn2 = host2.newTurn()
turn2.beginExecuting()
val lock2 = turn2.subsumableLock.get
val turn1on2 = FullMVTurnLocalClone(turn1, host2)
val l2 = Await.result(turn2.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(Await.result(turn1on2.trySubsume(l2), Duration.Zero) === Successful)
l2.asyncUnlock()
val turn3 = host2.newTurn()
turn3.beginExecuting()
val lock3 = turn3.subsumableLock.get
val l3 = Await.result(turn3.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(Await.result(turn2.trySubsume(l3), Duration.Zero) === Successful)
assert(lock1.refCount.get <= 0)
val lock2on1 = host1.lockHost.getInstance(lock2.guid).get
assert(lock2on1.refCount.get === 1) // turn1
assert(lock2.refCount.get === 1) // lock2on1
assert(lock3.refCount.get === 4) // turn2, turn3, lock2, thread
assert(Await.result(turn1.tryLock(), Duration.Zero) === Blocked)
assert(lock1.refCount.get <= 0)
assert(lock2on1.refCount.get <= 0)
assert(lock2.refCount.get <= 0)
val lock3on1 = host1.lockHost.getInstance(lock3.guid).get
assert(lock3on1.refCount.get === 1) // turn1
assert(lock3.refCount.get === 4) // turn2, turn3, lock3on1, thread
}
test("remote indirect trylock success works") {
val host1 = new FullMVEngine(Duration.Zero, "host1")
val host2 = new FullMVEngine(Duration.Zero, "host2")
val turn1 = host1.newTurn()
turn1.beginExecuting()
val lock1 = turn1.subsumableLock.get
val turn2 = host2.newTurn()
turn2.beginExecuting()
val lock2 = turn2.subsumableLock.get
val turn1on2 = FullMVTurnLocalClone(turn1, host2)
val l2 = Await.result(turn2.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(Await.result(turn1on2.trySubsume(l2), Duration.Zero) === Successful)
l2.asyncUnlock()
val turn3 = host2.newTurn()
turn3.beginExecuting()
val lock3 = turn3.subsumableLock.get
val l3 = Await.result(turn3.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(Await.result(turn2.trySubsume(l3), Duration.Zero) === Successful)
l3.asyncUnlock()
assert(lock1.refCount.get <= 0)
val lock2on1 = host1.lockHost.getInstance(lock2.guid).get
assert(lock2on1.refCount.get === 1) // turn1
assert(lock2.refCount.get === 1) // lock2on1
assert(lock3.refCount.get === 3) // turn2, turn3, lock2
Await.result(turn1.tryLock(), Duration.Zero).asInstanceOf[Locked].lock
assert(lock1.refCount.get <= 0)
assert(lock2on1.refCount.get <= 0)
assert(lock2.refCount.get <= 0)
val lock3on1 = host1.lockHost.getInstance(lock3.guid).get
assert(lock3on1.refCount.get === 2) // turn1, thread
assert(lock3.refCount.get === 3) // turn2, turn3, lock3on1
}
}
|
<?php
/**
* Dida Framework -- PHP轻量级快速开发框架
* 版权所有 (c) 上海宙品信息科技有限公司
*
* 官网: <https://github.com/zeupin/dida>
* Gitee: <https://gitee.com/zeupin/dida>
*/
use \Dida\Log\Log;
use \Dida\Log\Logger;
$test_start = microtime();
require __DIR__ . "/_bootstrap.php";
DidaTest::section("Log");
$loggerSetting = [
"classname" => "\Dida\Log\FileLogger",
"path" => __DIR__ . "/logs",
];
Log::init($loggerSetting);
Log::emergency("now");
Log::alert("now");
Log::critical("now");
Log::error("now");
Log::warning("now");
Log::notice("now");
Log::info("now");
Log::debug("now");
|
fun String.invoke() = this
val some = ""
fun sss() {
val some = 10
<!INAPPLICABLE_CANDIDATE!>some<!>() // Should be inapplicable
}
|
package com.shafeeq.ucrbook.ucridebook.app.model;
public enum VehicleType {
SEDAN, HATCHBACK, LUXURY
}
|
---
title: C6527
ms.date: 11/04/2016
ms.topic: reference
f1_keywords:
- C6527
helpviewer_keywords:
- C6527
ms.assetid: 5ebb6279-0f75-4566-a5f3-a47834de9625
author: mikeblome
ms.author: mblome
manager: wpickett
ms.workload:
- multiple
ms.openlocfilehash: 735d51b418f94ada4aef90347cadc885cfd8b58c
ms.sourcegitcommit: 94b3a052fb1229c7e7f8804b09c1d403385c7630
ms.translationtype: MT
ms.contentlocale: cs-CZ
ms.lasthandoff: 04/23/2019
ms.locfileid: "62781012"
---
# <a name="c6527"></a>C6527
upozornění C6527: Neplatná Poznámka: Vlastnost NeedsRelease nesmí být použita pro hodnoty typu void.
|
using FASTER.core;
namespace Zeus.Storage.Faster.Tests.Utils
{
internal static class Comparers
{
internal class IntComparer : IFasterEqualityComparer<int>
{
public static IntComparer Instance { get; } = new IntComparer();
public long GetHashCode64(ref int k)
{
return Utility.GetHashCode(k);
}
public bool Equals(ref int k1, ref int k2)
{
return k1 == k2;
}
}
}
}
|
namespace Elephant.Common
{
/// <summary>
/// Interface with an <see cref="Id"/> property.
/// </summary>
public interface IId
{
/// <summary>
/// Unique identifier.
/// </summary>
int Id { get; set; }
}
}
|
#
# Cookbook Name:: hana-studio
# Resource:: sap_media
#
# Copyright 2016, SAP
#
# 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.
#
resource_name :hana_studio_sap_media
attribute :extractDir, String, name_property: true
attribute :remote_path, String
attribute :sapcar, String
load_current_value do
sapcar_path = node['platform_family'] == 'windows' ? ENV['WINDIR'] : '/usr/local/bin' # Where to look for SAPCAR
sapcar_path += '/SAPCAR'
sapcar_path += '.exe' if node['platform_family'] == 'windows' # add exe if windows
puts "\n::File.exist?(#{sapcar_path}) = #{::File.exist?(sapcar_path)}"
extractDir '' unless ::File.exist?(sapcar_path) # mark the resource as not up-to-date
end
action :extract do
converge_if_changed :extractDir do
#######################
## Collect Variables ##
#######################
sapcar_dir = node['platform_family'] == 'windows' ? ENV['WINDIR'] : '/usr/local/bin/' # Where to put SAPCAR
sapcar_ex = 'SAPCAR' # The file name of the sapcar binary
sapcar_ex += '.exe' if node['platform_family'] == 'windows' # add exe if windows
sar_url = new_resource.remote_path # The full URL to the sar package
sar_file = sar_url.split('/')[-1] # The file name of the sar package, for friendly logging
sar_extract_dir = new_resource.extractDir # Where to put the extracted contents
local_sar = "#{Chef::Config[:file_cache_path]}/#{sar_file}" # The path to the loac copy of the SAR
########################
## Download SAPCAR ##
########################
remote_file "#{sapcar_dir}/#{sapcar_ex}" do
source new_resource.sapcar
mode 00755 unless node['platform_family'] == 'windows'
action :create_if_missing
end
######################
## Download the SAR ##
######################
remote_file local_sar do
source sar_url
mode 0755 unless node['platform_family'] == 'windows'
backup false
action :create_if_missing
end
##########################
## Extract the package ##
##########################
# Creates the destination directory
directory sar_extract_dir do
recursive true
action :create
end
# Use SAPCAR to extract the downloaded package to its destination
# Using execute here instead of shell_out to ensure proper flow order.
execute "Extract media #{sar_file} to #{sar_extract_dir}" do
command "#{sapcar_ex} -xf #{local_sar} -R #{sar_extract_dir}"
notifies :delete, "remote_file[#{local_sar}]", :immediately
end
end
end
|
// SPDX-FileCopyrightText: 2020 Ethel Morgan
//
// SPDX-License-Identifier: MIT
package controlpoint
import (
"errors"
"math/rand"
"sync"
"github.com/ethulhu/helix/upnpav"
)
type (
Queue interface {
Skip()
Current() (upnpav.Item, bool)
Next() (upnpav.Item, bool)
}
TrackList struct {
items map[int]upnpav.Item
order []int
current int
mu sync.Mutex
}
QueueItem struct {
ID int
Item upnpav.Item
}
)
func NewTrackList() *TrackList {
return &TrackList{
items: map[int]upnpav.Item{},
}
}
func (t *TrackList) Items() []QueueItem {
t.mu.Lock()
defer t.mu.Unlock()
var queueItems []QueueItem
for id, item := range t.items {
queueItems = append(queueItems, QueueItem{id, item})
}
return queueItems
}
func (t *TrackList) Upcoming() []QueueItem {
t.mu.Lock()
defer t.mu.Unlock()
var queueItems []QueueItem
for _, id := range t.order[t.current:] {
queueItems = append(queueItems, QueueItem{id, t.items[id]})
}
return queueItems
}
func (t *TrackList) History() []QueueItem {
t.mu.Lock()
defer t.mu.Unlock()
var queueItems []QueueItem
for _, id := range t.order[:t.current] {
queueItems = append(queueItems, QueueItem{id, t.items[id]})
}
return queueItems
}
func (t *TrackList) Append(item upnpav.Item) int {
t.mu.Lock()
defer t.mu.Unlock()
var id int
for {
id = int(rand.Int31())
// id MUST NOT be 0.
if _, alreadyExists := t.items[id]; !alreadyExists && id != 0 {
break
}
}
t.items[id] = item
t.order = append(t.order, id)
return id
}
func (t *TrackList) SetCurrent(id int) error {
for i := range t.order {
if t.order[i] == id {
t.current = i
return nil
}
}
return errors.New("unknown id")
}
func (t *TrackList) Remove(id int) {
t.mu.Lock()
defer t.mu.Unlock()
if _, exists := t.items[id]; !exists {
return
}
for i := range t.order {
if t.order[i] == id {
if i < t.current {
t.current--
}
t.order = append(t.order[:i], t.order[i+1:]...)
break
}
}
delete(t.items, id)
}
func (t *TrackList) RemoveAll() {
t.items = nil
t.order = nil
t.current = 0
}
func (t *TrackList) Skip() {
if t.current < len(t.order) {
t.current++
}
}
func (t *TrackList) Current() (upnpav.Item, bool) {
return t.atIndex(t.current)
}
func (t *TrackList) Next() (upnpav.Item, bool) {
return t.atIndex(t.current + 1)
}
func (t *TrackList) atIndex(i int) (upnpav.Item, bool) {
if i < len(t.order) {
return t.items[t.order[i]], true
}
return upnpav.Item{}, false
}
|
from __future__ import annotations
import logging
from functools import wraps
import maya
from CaseInsensitiveDict import CaseInsensitiveDict
from async_property import async_property
from roblox.abc import Group as _Group
from roblox.abc import GroupMember as _GroupMember
from roblox.abc import Role as _Role
from roblox.abc import Shout as _Shout
from roblox.errors import *
from roblox.http import Session
from roblox.iterables import AsyncIterator
from roblox.user import User, BaseUser
from roblox.util import urlify
from typing import Union
log = logging.getLogger(__name__)
# util decorator
def g_info(name, nocache=False):
"""This decorator will check if the property is in the group"s _data, and if it isn"t send a request to the
groups API endpoint"""
def decorator(fn):
@wraps(fn)
async def new_fn(self):
if nocache or self._data[name] is None:
await self._get_group_details()
return self._data[name]
return new_fn
return decorator
class Group(_Group):
__slots__ = ("_data", "_state")
def __init__(self, *, state: Session, data):
self._state = state
self._data = CaseInsensitiveDict({
"id": None,
"name": None,
"description": None,
"owner": None,
"shout": None,
"membercount": None,
"isbuildersclubonly": None,
"publicentryallowed": None,
"islocked": None
})
self._update(data)
def __repr__(self):
return "Group({!r})".format(self._data["name"] or self._data["id"])
def __hash__(self):
return self._data["id"] or -2
def __eq__(self, other):
if not isinstance(other, Group):
return False
return self._data["id"] == other._data["id"]
def _update(self, data):
self._data.update(data)
async def _get_group_details(self):
data = await self._state.get_group_details(await self.id)
self._update(data)
@async_property
@g_info("id")
async def id(self):
"""|asyncprop|
The group's ID.
:rtype: int
"""
pass
@async_property
@g_info("name")
async def name(self):
"""|asyncprop|
The group's name.
:rtype: str
"""
pass
@async_property
@g_info("description")
async def description(self):
"""|asyncprop|
The group's description.
:rtype: str
"""
pass
@async_property
@g_info("publicentryallowed", nocache=True)
async def is_public(self):
"""|asyncprop|
Whether new members must be approved.
:rtype: bool
"""
pass
@async_property
async def owner(self):
"""|asyncprop|
The group's owner.
:rtype: :class:`.User`
"""
await self._get_group_details()
if self._data["owner"] is None:
return None
data = {
"user": self._data["owner"],
"role": (await self.roles)[-1]._data
}
return GroupMember(state=self._state, data=data, group=self)
@async_property
async def created_at(self):
if self._data["shout"] is None:
await self._get_group_details()
raise NotImplemented
updated_at = created_at
@async_property
async def url(self):
"""|asyncprop|
The group's URL.
:rtype: str
"""
if self._data["id"] is None or self._data["name"] is None:
await self._get_group_details()
return "https://roblox.com/groups/{}/{}#!/about".format(self._data["id"], urlify(self._data["name"]))
@async_property
async def shout(self):
"""|asyncprop|
The group's current shout.
:rtype: :class:`.Shout`
"""
await self._get_group_details()
try:
return Shout(state=self._state, data=self._data.get("shout"), group=self)
except TypeError:
return None
@async_property
async def roles(self, reverse=False):
"""|asyncprop|
List of the group's roles.
:rtype: List[:class:`.Role`]
"""
data = await self._state.get_group_roles(await self.id)
roles = []
for role in data["roles"]:
roles.append(
Role(state=self._state, data=role, group=self)
)
roles.sort(key=lambda r: r._data["rank"], reverse=reverse)
return roles
async def get_role(self, role: Union[str, int]):
"""
Attempts to find a role within a group given a name or ID.
Args:
role: Role's name or ID.
:rtype: Optional[:class:`.Role`]
"""
if isinstance(role, str) or isinstance(role, int):
role = str(role).lower()
for obj in await self.roles:
if obj == role or str(await obj.id) == role or (await obj.name).lower() == role:
return obj
@property
def members(self) -> _MembersIterator:
"""
:class:`.AsyncIterator` for this group's members.
Yields:
:class:`.GroupMember`
"""
return _MembersIterator(state=self._state, opts={"group": self})
async def get_member(self, user):
"""
Tries to find a group member given a username, ID, or :class:`.User`.
Args:
user: User to try and find within the group.
:rtype: :class:`.GroupMember`
"""
user_data = {}
if isinstance(user, BaseUser):
user_id = await user.id
user_data = user._data
elif isinstance(user, str):
user = await self._state.client.get_user(username=user)
user_id = await user.id
user_data = user._data
else:
user_id = int(user)
user_data["id"] = user_id
all_roles = await self._state.get_user_roles(user_id)
match = None
for data in all_roles["data"]:
if data["group"]["id"] == await self.id:
match = data
break
if match is None:
raise UserNotInGroup
data = {
"user": user_data,
"role": match["role"]
}
return GroupMember(state=self._state, data=data, group=self)
async def upload_asset(self, file, name, asset_type):
if isinstance(file, str):
file = open(file, "rb")
r = await self._state.upload_asset(file, name, int(asset_type), group_id=await self.id)
file.close()
return r
class _MembersIterator(AsyncIterator):
async def __aiter__(self):
async for data in self._state.get_group_members(await self._opts["group"].id):
yield GroupMember(state=self._state, data=data, group=self)
async def count(self):
await self._opts["group"]._get_group_details()
return self._opts["group"]._data.get("membercount")
class Shout(_Shout):
__slots__ = ("_data", "_state", "group")
def __init__(self, *, state, data, group: Group):
self._state = state
self._data = CaseInsensitiveDict({
"body": None,
"poster": None,
"created": None,
"updated": None
})
self.group = group
self._update(data)
def __repr__(self):
return "Shout({!r}, {!r}, {!r})".format(self.group,
self._data["poster"]["username"],
self._data["body"])
def _update(self, data):
self._data.update(data)
@property
def body(self):
"""
Shout's body.
:type: str
"""
return self._data["body"]
@property
def created_at(self):
"""
Date/time when the shout was last updated.
:type: :class:`datetime.datetime`
"""
try:
return maya.parse(self._data["updated"]).datetime()
except OSError:
return None
@async_property
async def poster(self) -> Union[GroupMember, User]:
"""|asyncprop|
User who posted the shout.
Return:
:class:`.GroupMember` if poster is still in the group, :class:`.User` otherwise.
:rtype: Union[:class:`.GroupMember`, :class:`.User`]
"""
poster_id = self._data["poster"]["userid"]
poster_user = self._data["poster"]["username"]
user = await self._state.client.get_user(id=poster_id, username=poster_user)
try: # try to get a GroupMember instead of User
return await self.group.get_member(user)
except UserNotInGroup:
return user
class GroupMember(User, _GroupMember):
"""
Represents a group member.
This class inherits all functionality from :class:`.User`.
**Operations**
**x == y**
Checks that two users are equal.
**x != y**
Checks that two users are not equal.
**x > y**
Checks that member X has a greater rank than member Y.
**x >= y**
Checks that member X's rank is greater than or equal to member Y.
**x < y**
Checks that member X has a lesser rank than member Y.
**x <= y**
Checks that member X's rank is less than or equal to member Y.
Attributes:
group (:class:`.Group`): Group the member belongs to.
"""
__slots__ = ("_state", "_data", "group")
def __init__(self, *, state, data, group):
super().__init__(state=state, data=data.get("user", data.get("User")))
self._data.update({
"role": None
})
self._data.update(data)
self.group = group
def __repr__(self):
return "GroupMember({!r}, group={!r}, rank={!r})".format(self._data["username"] or self._data["id"],
self.group._data["name"] or self.group._data["id"],
(self._data["role"] or {}).get("rank"))
def _comp(self, other):
if self._data["role"] is None:
my_rank = 0
else:
my_rank = self._data["role"].get("rank", 0)
if isinstance(other, GroupMember):
if other._data["role"] is None:
other_rank = 0
else:
other_rank = other._data["role"].get("rank", 0)
elif isinstance(other, Role):
other_rank = other._data.get("rank", 0)
else:
raise UserError("Can't compare GroupMember with {}".format(other.__class__.__name__))
if my_rank > other_rank:
return 1
elif my_rank == other_rank:
return 0
else:
return -1
def __gt__(self, other):
c = self._comp(other)
return c == 1
def __ge__(self, other):
c = self._comp(other)
return c > 0
def __lt__(self, other):
c = self._comp(other)
return c == -1
def __le__(self, other):
c = self._comp(other)
return c < 0
@property
def role(self):
"""
Member's role within the group.
:type: :class:`.Role`
"""
if self._data["role"] is None:
raise RoleNotFound
return Role(state=self._state, data=self._data["role"], group=self.group)
@async_property
async def rank(self):
"""|asyncprop|
Member's rank within the group. Shortcut for ``await member.role.rank`
:rtype: int
"""
return await self.role.rank
class Role(_Role):
"""
Represents a roleset within a group.
**Operations**
**x == y**
Checks that two roles are equal.
**x != y**
Checks that two roles are not equal.
**x > y**
Checks that role X has a greater rank than role Y.
**x >= y**
Checks that role X's rank is greater than or equal to role Y.
**x < y**
Checks that role X has a lesser rank than role Y.
**x <= y**
Checks that role X's rank is less than or equal to role Y.
"""
__slots__ = ("_state", "_data", "group")
def __init__(self, *, state: Session, data, group):
self._state = state
self._data = CaseInsensitiveDict({
"id": None,
"name": None,
"description": None,
"rank": None,
"membercount": None,
"permissions": None,
})
self._update(data)
self.group = group
def __repr__(self):
return "Role({!r}, {!r}, rank={!r})".format(self.group, self._data["name"], self._data["rank"])
def __hash__(self):
return hash(self._data["id"] << 22 | self.group._data["id"])
def __eq__(self, other):
if not isinstance(other, Role):
return False
if self.group != other.group:
return False
return self._data["id"] == other._data["id"] and self._data["id"] is not None
def _comp(self, other):
if isinstance(other, Role):
other = other._data["rank"]
elif isinstance(other, GroupMember):
if other._data["role"] is None:
return False
other = other._data["role"]["rank"]
if self._data["rank"] > other:
return 1
elif self._data["rank"] < other:
return -1
else:
return 0
def __gt__(self, other):
c = self._comp(other)
return c == 1
def __ge__(self, other):
c = self._comp(other)
return c >= 0
def __lt__(self, other):
c = self._comp(other)
return c == -1
def __le__(self, other):
c = self._comp(other)
return c <= 0
def _update(self, data):
self._data.update(data)
async def _get_role_details(self):
data = await self._state.get_role_details(await self.id)
data = data["data"][0]
self._update(data)
@async_property
async def id(self):
"""|asyncprop|
The role's ID.
:rtype: int
"""
return self._data["id"]
@async_property
async def name(self):
"""|asyncprop|
The role's name.
:rtype: str
"""
if self._data["name"] is None:
await self._get_role_details()
return self._data["name"]
@async_property
async def description(self):
"""|asyncprop|
The role's description.
:rtype: str
"""
if self._data["description"] is None:
await self._get_role_details()
return self._data["description"]
@async_property
async def rank(self):
"""|asyncprop|
The role's integer rank.
:rtype: int
"""
if self._data["rank"] is None:
await self._get_role_details()
return self._data["rank"]
@async_property
async def member_count(self):
"""|asyncprop|
Number of members belonging to this role.
:rtype: int
"""
await self._get_role_details()
return self._data["membercount"]
|
package logger
import (
"io"
"log"
"os"
"sync"
)
func NewFileLogger(filepath string, prefix string) *log.Logger {
f, err := os.OpenFile("log",
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
logger := log.New(f, prefix+" ", log.Ldate|log.Ltime|log.Lshortfile|log.LUTC)
return logger
}
func NewLogger(out io.Writer, prefix string) *log.Logger {
logger := log.New(out, prefix+" ", log.Ldate|log.Ltime|log.Lshortfile|log.LUTC)
return logger
}
type FileConcurrentWriter struct {
f *os.File
m *sync.Mutex
}
func NewFileConcurrentWriter(filename string) *FileConcurrentWriter {
fw := &FileConcurrentWriter{}
f, err := os.OpenFile(filename,
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
fw.f = f
fw.m = &sync.Mutex{}
return fw
}
func (w *FileConcurrentWriter) Write(p []byte) (n int, err error) {
w.m.Lock()
defer w.m.Unlock()
return w.f.Write(p)
}
|
using System;
using Take.Elephant.Sql;
namespace Take.Elephant.Tests.Sql
{
public interface ISqlFixture : IDisposable
{
IDatabaseDriver DatabaseDriver { get; }
string ConnectionString { get; }
void DropTable(string schemaName, string tableName);
}
}
|
# GenServer test
A quick test making a GenServer that keeps track of how many messages it has received.
```
$ iex -S mix
Erlang/OTP 21 [erts-10.0.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe] [dtrace]
Compiling 1 file (.ex)
Generated gen_server_demo app
Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> s = Scorer.start
{:ok, #PID<0.160.0>}
iex(2)> GenServer.cast(:scorer, "test")
[%Scorer.State{num_messages: 0}}]: test}
:ok
iex(3)> GenServer.cast(:scorer, "test")
[%Scorer.State{num_messages: 1}}]: test}
:ok
```
|
/*
* Duy Nguyen - duy@cs.brown.edu
* May 18, 2011
*/
#include <pthread.h>
#include <utils/SHA256.h>
static pthread_mutex_t _sha256Mutex = PTHREAD_MUTEX_INITIALIZER;
MySHA256* MySHA256::_instance = NULL;
MySHA256::MySHA256(){
}
MySHA256* MySHA256::getInstance(){
if(_instance == NULL){
pthread_mutex_lock(&_sha256Mutex);
if(_instance == NULL){
_instance = new MySHA256();
}
pthread_mutex_unlock(&_sha256Mutex);
}
return _instance;
}
void MySHA256::computeDigest(const char *input, int length, vector<unsigned char> &output){
unsigned char tempOutput[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, input, length);
SHA256_Final(tempOutput, &sha256);
output.clear();
for(int i=0; i<SHA256_DIGEST_LENGTH; i++){
output.push_back(tempOutput[i]);
}
}
void MySHA256::computeAccumulatorDigest(const G *acc, vector<unsigned char> &output){
computeDigest(acc->getByteBuffer(), acc->getSize(), output);
}
bool MySHA256::isHashesEqual(const vector<unsigned char> &hash1, const vector<unsigned char> &hash2){
if(hash1.size() != hash2.size() || hash1.size() != SHA256_DIGEST_LENGTH){
return false;
}
for(int i=0; i<SHA256_DIGEST_LENGTH; i++){
if(hash1[i] != hash2[i]){
return false;
}
}
return true;
}
|
require "rails_helper"
describe LoanAlerts::PriorityGrouping do
describe "for Not Drawn alert" do
let(:start_date) { alert.start_date }
let!(:lender) { FactoryGirl.create(:lender) }
let!(:overdue_priority_loan) do
FactoryGirl.create(
:loan,
:offered,
lender: lender,
facility_letter_date: start_date)
end
let!(:high_priority_loan) do
FactoryGirl.create(
:loan,
:offered,
lender: lender,
facility_letter_date: 10.weekdays_from(start_date))
end
let!(:medium_priority_loan1) do
FactoryGirl.create(
:loan,
:offered,
lender: lender,
facility_letter_date: 21.weekdays_from(start_date))
end
let!(:medium_priority_loan2) do
FactoryGirl.create(
:loan,
:offered,
lender: lender,
facility_letter_date: 39.weekdays_from(start_date))
end
let!(:low_priority_loan1) do
FactoryGirl.create(
:loan,
:offered,
lender: lender,
facility_letter_date: 40.weekdays_from(start_date))
end
let!(:low_priority_loan2) do
FactoryGirl.create(
:loan,
:offered,
lender: lender,
facility_letter_date: 59.weekdays_from(start_date))
end
let(:alert) do
LoanAlerts::NotDrawn.new(lender)
end
let(:priority_grouping) do
LoanAlerts::PriorityGrouping.new(alert)
end
describe "#alerts_grouped_by_priority" do
it "returns groups in the expected order" do
group_names = priority_grouping.alerts_grouped_by_priority.
map(&:priority)
expect(group_names).to eq([:overdue, :high, :medium, :low])
end
it "includes the correct loans in the first group" do
first_group = priority_grouping.alerts_grouped_by_priority.first
expect(first_group.total_loans).to eq(1)
end
it "includes the correct loans in the second group" do
second_group = priority_grouping.alerts_grouped_by_priority.second
expect(second_group.total_loans).to eq(1)
end
it "includes the correct loans in the third group" do
third_group = priority_grouping.alerts_grouped_by_priority.third
expect(third_group.total_loans).to eq(2)
end
it "includes the correct loans in the fourth group" do
fourth_group = priority_grouping.alerts_grouped_by_priority.fourth
expect(fourth_group.total_loans).to eq(2)
end
end
context "for not demanded alert" do
it "returns groups in the expected order" do
alert = LoanAlerts::NotDemanded.new(lender)
priority_grouping = LoanAlerts::PriorityGrouping.new(alert)
group_names = priority_grouping.alerts_grouped_by_priority.
map(&:priority)
expect(group_names).to eq([:high, :medium, :low])
end
end
end
end
|
import { SphereTracingScene } from './../../SphereTracingScene';
import * as PULSAR from './../../Window';
import reflectionFragmentShader from './shader/reflection.fs';
import reflectionVertexShader from './shader/reflection.vs';
export class Application {
public main(): void {
const window: PULSAR.Window = new PULSAR.Window('canvas');
window.setScene(new SphereTracingScene(reflectionVertexShader, reflectionFragmentShader));
window.start();
}
}
new Application().main();
|
from .core import _Value
class Float(_Value):
__slots__ = ()
def incr(self, value=1):
self._memoryview[0] = value
__iadd__ = incr
def _get_size(self):
return 8
def _get_type(self):
return ('d', 'level 8 float')
def set(self, value):
self._memoryview[0] = value
def __setitem__(self, key, value):
assert key == 0, "Only single value is expected"
self._memoryview[key] = value
class Integer(_Value):
__slots__ = ()
def _get_size(self):
return 8
def _get_type(self):
return ('q', 'level 8 signed')
def set(self, value):
self._memoryview[0] = value
def get(self):
return self._memoryview[0]
def incr(self, value=1):
self._memoryview[0] += value
def decr(self, value=1):
self._memoryview[0] -= value
def __setitem__(self, key, value):
assert key == 0, "Only single value is expected"
self._memoryview[key] = value
|
//!
//! The semantic analyzer scope type item index.
//!
use std::collections::HashMap;
use std::sync::RwLock;
use lazy_static::lazy_static;
use crate::semantic::scope::intrinsic::IntrinsicTypeId;
///
/// The type item index where the unique IDs for all declared types are recorded.
///
/// It is initialized with some intrinsic and standard library types.
///
/// The index treats type aliases equal to the type they point to.
///
pub struct Index {
/// The inner type storage with the type unique ID as the key.
pub inner: RwLock<HashMap<usize, String>>,
}
lazy_static! {
pub static ref INDEX: Index = Index::new();
}
impl Index {
/// The type hashmap default capacity.
const INITIAL_CAPACITY: usize = 512;
///
/// A shortcut constructor.
///
pub fn new() -> Self {
let index = Self {
inner: RwLock::new(HashMap::with_capacity(Self::INITIAL_CAPACITY)),
};
index.next_with_id(
"structure std::crypto::ecc::Point".to_owned(),
IntrinsicTypeId::StdCryptoEccPoint as usize,
);
index.next_with_id(
"structure std::crypto::schnorr::Signature".to_owned(),
IntrinsicTypeId::StdCryptoSchnorrSignature as usize,
);
index.next_with_id(
"structure zksync::Transaction".to_owned(),
IntrinsicTypeId::ZkSyncTransaction as usize,
);
index.next_with_id(
"structure std::collections::MTreeMap".to_owned(),
IntrinsicTypeId::StdCollectionsMTreeMap as usize,
);
index
}
///
/// Generate the next type sequence ID and add the ID with the type `title` to the index.
///
pub fn next(&self, title: String) -> usize {
let type_id = self
.inner
.write()
.expect(zinc_const::panic::SYNCHRONIZATION)
.len();
self.next_with_id(title, type_id)
}
///
/// Add the item `title` to the index with the specified `type_id` key.
///
fn next_with_id(&self, title: String, type_id: usize) -> usize {
let mut index = self
.inner
.write()
.expect(zinc_const::panic::SYNCHRONIZATION);
log::debug!("Type ID {:06} for {}", type_id, title);
index.insert(type_id, title);
type_id
}
}
|
#proc1 = lambda { |arg| p arg }
#proc1.call( '다현', '채영') # => wrong number of arguments (given 2, expected 1) (ArgumentError)
#proc2 = lambda { |arg,arg2| p "#{arg} #{arg2}" }
#proc2.call( '다현', '채영')
proc3 = lambda { |arg| p arg }
proc3.call() # => wrong number of arguments (given 0, expected 1) (ArgumentError)
|
# server-based syntax
# ======================
# Defines a single server with a list of roles and multiple properties.
# You can define all roles on a single server, or split them:
server "thecloud12.mycpnv.ch", user: "maw11_12", ssh_options: {
user: 'maw11_12',
keys: %w(~/.ssh/swisscenter),
forward_agent: false,
auth_methods: %w(publickey)
}
task :copy_dotenv do
on roles(:all) do
execute :cp, "#{shared_path}/.env #{release_path}/.env"
end
end
set :laravel_version, 8.0
set :laravel_upload_dotenv_file_on_deploy, false
# swisscenter disables acls, instead use chmod
set :laravel_set_acl_paths, false
after 'composer:run', 'copy_dotenv'
after 'composer:run', 'laravel:migrate'
# role-based syntax
# ==================
# Defines a role with one or multiple servers. The primary server in each
# group is considered to be the first unless any hosts have the primary
# property set. Specify the username and a domain or IP for the server.
# Don't use `:all`, it's a meta role.
# role :app, %w{deploy@example.com}, my_property: :my_value
# role :web, %w{user1@primary.com user2@additional.com}, other_property: :other_value
# role :db, %w{deploy@example.com}
# Configuration
# =============
# You can set any configuration variable like in config/deploy.rb
# These variables are then only loaded and set in this stage.
# For available Capistrano configuration variables see the documentation page.
# http://capistranorb.com/documentation/getting-started/configuration/
# Feel free to add new variables to customise your setup.
|
package com.capitalone.dashboard.misc;
public class HygieiaException extends Exception {
private static final long serialVersionUID = 4596406816345733781L;
public static final int NOTHING_TO_UPDATE = 0;
public static final int JSON_FORMAT_ERROR = -1;
public static final int COLLECTOR_CREATE_ERROR = -10;
public static final int COLLECTOR_ITEM_CREATE_ERROR = -11;
public static final int ERROR_INSERTING_DATA = -12;
public static final int DUPLICATE_DATA = -13;
private int errorCode = 0;
public HygieiaException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public HygieiaException(String message, Throwable cause, int errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
public HygieiaException(Throwable cause) {
super(cause);
}
public HygieiaException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public int getErrorCode() {
return errorCode;
}
}
|
/*
* Copyright (C) 2013-2016 Rinde van Lon, iMinds-DistriNet, KU Leuven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.rinde.logistics.pdptw.mas.route;
import static com.google.common.collect.Lists.newLinkedList;
import java.io.Serializable;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import com.github.rinde.rinsim.central.GlobalStateObject;
import com.github.rinde.rinsim.central.Measurable;
import com.github.rinde.rinsim.central.SimSolverBuilder;
import com.github.rinde.rinsim.central.Solver;
import com.github.rinde.rinsim.central.SolverTimeMeasurement;
import com.github.rinde.rinsim.central.SolverUser;
import com.github.rinde.rinsim.central.Solvers.SolveArgs;
import com.github.rinde.rinsim.central.rt.RealtimeSolver;
import com.github.rinde.rinsim.central.rt.RtSimSolver;
import com.github.rinde.rinsim.central.rt.RtSimSolver.EventType;
import com.github.rinde.rinsim.central.rt.RtSimSolverBuilder;
import com.github.rinde.rinsim.central.rt.RtSolverUser;
import com.github.rinde.rinsim.central.rt.RtStAdapters;
import com.github.rinde.rinsim.core.model.pdp.PDPModel.VehicleState;
import com.github.rinde.rinsim.core.model.pdp.Parcel;
import com.github.rinde.rinsim.event.Event;
import com.github.rinde.rinsim.event.Listener;
import com.github.rinde.rinsim.pdptw.common.PDPRoadModel;
import com.github.rinde.rinsim.pdptw.common.RouteFollowingVehicle;
import com.github.rinde.rinsim.util.StochasticSupplier;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
/**
*
* @author Rinde van Lon
*/
public final class RtSolverRoutePlanner extends AbstractRoutePlanner
implements RtSolverUser, Measurable {
Deque<Parcel> route;
Optional<PDPRoadModel> pdpRoadModel;
Optional<RtSimSolver> simSolver;
private final RealtimeSolver solver;
RtSolverRoutePlanner(RealtimeSolver s) {
route = newLinkedList();
solver = s;
simSolver = Optional.absent();
pdpRoadModel = Optional.absent();
}
@Override
protected void afterInit() {
pdpRoadModel = Optional.of((PDPRoadModel) roadModel.get());
}
@Override
protected void doUpdate(Set<Parcel> onMap, long time) {
if (onMap.isEmpty()
&& pdpModel.get().getContents(vehicle.get()).isEmpty()) {
route.clear();
} else {
final Set<Parcel> toRemove = new LinkedHashSet<Parcel>();
// remove all parcels which are no longer assigned to this routeplanner
for (final Parcel p : route) {
if (!onMap.contains(p)
&& !pdpModel.get().getParcelState(p).isPickedUp()
&& !pdpModel.get().getParcelState(p).isTransitionState()) {
toRemove.add(p);
}
}
LOGGER.trace("route {}", route);
route.removeAll(toRemove);
LOGGER.trace("to remove: {}, remaining route: {}", toRemove, route);
// when diversion is allowed we can just change course
@Nullable
final Parcel destination =
pdpRoadModel.get().isVehicleDiversionAllowed()
? null
: pdpRoadModel.get().getDestinationToParcel(vehicle.get());
if (pdpModel.get().getVehicleState(vehicle.get()) != VehicleState.IDLE
|| destination != null) {
// vehicle is picking up or delivering -> make sure that first item in
// route is the parcel that is being serviced
final Parcel next = destination == null
? pdpModel.get().getVehicleActionInfo(vehicle.get()).getParcel()
: destination;
if (!route.peek().equals(next)) {
// remove first occurrence
route.removeFirstOccurrence(next);
route.addFirst(next);
LOGGER.trace("moved {} to first position in route", next);
}
}
final Iterable<Parcel> newRoute =
RouteFollowingVehicle.delayAdjuster().adjust(route,
(RouteFollowingVehicle) vehicle.get());
LOGGER.trace("adjusted route: {}", newRoute);
route.clear();
Iterables.addAll(route, newRoute);
final GlobalStateObject gso = simSolver.get().getCurrentState(
SolveArgs.create()
.useParcels(onMap)
.useCurrentRoutes(ImmutableList.of(ImmutableList.copyOf(route))));
final Optional<Parcel> dest = gso.getVehicles().get(0).getDestination();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("destination {}", dest);
if (dest.isPresent()) {
LOGGER.trace("parcel state {}",
pdpModel.get().getParcelState(dest.get()));
}
}
simSolver.get().solve(gso);
}
}
@Override
public boolean hasNext() {
return !route.isEmpty();
}
@Override
public Optional<Parcel> current() {
return Optional.fromNullable(route.peek());
}
@Override
public Optional<ImmutableList<Parcel>> currentRoute() {
if (route.isEmpty()) {
return Optional.absent();
}
return Optional.of(ImmutableList.copyOf(route));
}
@Override
protected void nextImpl(long time) {
route.poll();
}
@Override
public void setSolverProvider(RtSimSolverBuilder builder) {
simSolver = Optional.of(builder.setVehicles(vehicle.asSet()).build(solver));
final RtSolverRoutePlanner rp = this;
simSolver.get().getEventAPI().addListener(new Listener() {
@Override
public void handleEvent(Event e) {
route = newLinkedList(simSolver.get().getCurrentSchedule().get(0));
LOGGER.trace("Computed new route for {}: {}.", vehicle.get(), route);
rp.dispatchChangeEvent();
}
}, EventType.NEW_SCHEDULE);
}
@Override
public List<SolverTimeMeasurement> getTimeMeasurements() {
if (solver instanceof Measurable) {
return ((Measurable) solver).getTimeMeasurements();
}
throw new IllegalStateException("Solver " + solver + " is not measurable.");
}
public static StochasticSupplier<RoutePlanner> supplier(
StochasticSupplier<? extends RealtimeSolver> solver) {
return new RtSup(solver);
}
public static StochasticSupplier<RoutePlanner> simulatedTimeSupplier(
final StochasticSupplier<? extends Solver> solver) {
return new StSup(solver);
}
static String toStringHelper(String methodName, Object obj) {
return Joiner.on("").join(RtSolverRoutePlanner.class.getSimpleName(),
".", methodName, "(", obj, ")");
}
static class StSolverRoutePlanner extends ForwardingRoutePlanner
implements SolverUser {
RtSolverRoutePlanner delegate;
SolverUser stAdapter;
StSolverRoutePlanner(RtSolverRoutePlanner deleg) {
delegate = deleg;
stAdapter = RtStAdapters.toSimTime(deleg);
}
@Override
protected RtSolverRoutePlanner delegate() {
return delegate;
}
@Override
public void setSolverProvider(SimSolverBuilder builder) {
stAdapter.setSolverProvider(builder);
}
@Override
public String toString() {
return "ST" + delegate().toString();
}
}
static final class StSup
implements StochasticSupplier<RoutePlanner>, Serializable {
private static final long serialVersionUID = 8587803855370922629L;
final StochasticSupplier<? extends Solver> solver;
StSup(StochasticSupplier<? extends Solver> s) {
solver = s;
}
@Override
public RoutePlanner get(long seed) {
return new StSolverRoutePlanner(new RtSolverRoutePlanner(
RtStAdapters.toRealtime(solver.get(seed))));
}
@Override
public String toString() {
return toStringHelper("simulatedTimeSupplier", solver);
}
}
static final class RtSup implements StochasticSupplier<RoutePlanner> {
final StochasticSupplier<? extends RealtimeSolver> solver;
RtSup(StochasticSupplier<? extends RealtimeSolver> s) {
solver = s;
}
@Override
public RoutePlanner get(long seed) {
return new RtSolverRoutePlanner(solver.get(seed));
}
@Override
public String toString() {
return toStringHelper("supplier", solver);
}
}
}
|
package GraspPatterns;
public class SalesLineItem {
private int quantity;
private ProductDesc productDesc;
private double discount;
private double tax;
SalesLineItem(ProductDesc productDesc, int quantity, double discount) {
this.productDesc = productDesc;
this.quantity = quantity;
this.discount = discount;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public ProductDesc getProductDesc() {
return productDesc;
}
public double getSubTotal(boolean includeTax) {
if (!includeTax){
this.tax = 1;
}
return (productDesc.getPrice() * quantity
- productDesc.getPrice() * quantity * discount / 100) * productDesc.getPrice() * quantity * tax;
}
}
|
import { AccessoryConfig, AccessoryPlugin, API, Logging, Service } from 'homebridge';
import { Humidifier2 } from './humidifier2';
export class HumidifierAccessory implements AccessoryPlugin {
client: Humidifier2;
readonly infoService: Service;
readonly displayService: Service;
readonly humidifierService: Service;
readonly humiditySensor: Service;
readonly temperatureSensor: Service;
// Update Interval in milliseconds
readonly interval = 3000;
constructor(public logger: Logging, public config: AccessoryConfig, public api: API) {
logger.debug(JSON.stringify(config, null, 2));
const { Characteristic, Service } = api.hap;
this.client = new Humidifier2(config.ip, config.token);
this.infoService = new Service.AccessoryInformation()
.setCharacteristic(Characteristic.Manufacturer, 'SmartMi')
.setCharacteristic(Characteristic.Model, 'Humidifier2')
.setCharacteristic(Characteristic.SerialNumber, config.ip);
this.displayService = new Service.Lightbulb('Screen Brightness');
this.displayService
.getCharacteristic(Characteristic.On)
.onGet(() => {
return this.client.getScreenBrightness().then((value) => {
logger.info('getScreenBrightness: ', value);
return value > 0;
});
})
.onSet((value) => {
logger.info('setScreenPower: ', value);
this.client.setScreenBrightness(value ? 1 : 0);
});
this.displayService
.getCharacteristic(Characteristic.Brightness)
.setProps({ minValue: 0, maxValue: 2, minStep: 1 })
.onGet(() => this.client.getScreenBrightness())
.onSet((value) => {
logger.info('setScreenBrightness: ', value);
this.client.setScreenBrightness(value as number);
});
// Temperature Sensor
this.temperatureSensor = new Service.TemperatureSensor('Temperature');
this.temperatureSensor
.getCharacteristic(Characteristic.CurrentTemperature)
.onGet(() => this.client.getTemperature());
// Humidity Sensor
this.humiditySensor = new Service.HumiditySensor('Humidify Sensor');
this.humiditySensor
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.onGet(() => this.client.getHumidity());
// Main Service: HumidifierDehumidifier
this.humidifierService = new Service.HumidifierDehumidifier(config.name);
this.humidifierService.isPrimaryService = true;
// Power active or not
this.humidifierService.getCharacteristic(Characteristic.Active).onSet((value) => {
logger.info('setPower: ', value);
this.client.power(value == 1);
});
// Current Humidifier State (Auto / Humidifying / Dehumidifying / Off)
this.humidifierService
.getCharacteristic(Characteristic.CurrentHumidifierDehumidifierState)
.setProps({ validValues: [0, 2] });
// Target Humidifier Dehumidifier State
this.humidifierService
.getCharacteristic(Characteristic.TargetHumidifierDehumidifierState)
.setProps({ validValues: [1] });
this.humidifierService
.getCharacteristic(Characteristic.RelativeHumidityHumidifierThreshold)
.setProps({
minValue: 0,
maxValue: 100,
minStep: 1,
})
.onGet(() => this.client.getHumidity());
// .onSet((value) => {
// // TODO: Setting Target Humidity Threshold
// logger.debug(`Setting Humidity Threshold to ${value}`);
// this.client.setHumidityHumidifierThreshold(value as number);
// });
// Current Relative Humidity
this.humidifierService
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.onGet(() => this.client.getHumidity());
// Water level
this.humidifierService
.getCharacteristic(Characteristic.WaterLevel)
.onGet(() => this.client.getWaterLevel());
// Fan Level
this.humidifierService
.getCharacteristic(Characteristic.RotationSpeed)
.setProps({ minValue: 0, maxValue: 100, minStep: 25 })
.onGet(() => this.client.getFanLevel())
.onSet((value) => {
logger.info('setFanLevel: ', value);
if (value >= 1 && value < 33) {
this.client.setFanLevel(1);
} else if (value >= 33 && value <= 66) {
this.client.setFanLevel(2);
} else if (value > 66 && value <= 100) {
this.client.setFanLevel(3);
}
});
setInterval(() => {
this.client.batchGet().then((result) => {
// this.logger.debug("batchGet: ", result);
// Power
this.humidifierService
.getCharacteristic(Characteristic.Active)
.updateValue(result[0].value);
// Screen Brightness
this.displayService
.getCharacteristic(Characteristic.Brightness)
.updateValue(result[5].value);
// Screen On/Off
this.displayService.getCharacteristic(Characteristic.On).updateValue(result[5].value > 0);
this.humidifierService
.getCharacteristic(Characteristic.CurrentHumidifierDehumidifierState)
.updateValue(
result[0].value
? Characteristic.CurrentHumidifierDehumidifierState.HUMIDIFYING
: Characteristic.CurrentHumidifierDehumidifierState.INACTIVE,
);
// Water Level
this.humidifierService
.getCharacteristic(Characteristic.WaterLevel)
.updateValue(result[3].value / 1.25);
this.humidifierService
.getCharacteristic(Characteristic.RelativeHumidityHumidifierThreshold)
.updateValue(result[1].value);
this.humidifierService
.getCharacteristic(Characteristic.TargetHumidifierDehumidifierState)
.setValue(Characteristic.TargetHumidifierDehumidifierState.HUMIDIFIER);
// Humidity
this.humiditySensor
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.updateValue(result[1].value);
this.humidifierService
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.updateValue(result[1].value);
// Water level
this.humidifierService
.getCharacteristic(Characteristic.WaterLevel)
.updateValue(result[3].value / 1.25);
// Temperature
this.temperatureSensor
.getCharacteristic(Characteristic.CurrentTemperature)
.updateValue(result[7].value);
// Fan Level
// this.humidifierService
// .getCharacteristic(Characteristic.RotationSpeed)
// .updateValue(result[8].value);
});
}, this.interval);
}
getServices() {
return [
this.infoService,
this.displayService,
this.humidifierService,
this.temperatureSensor,
this.humiditySensor,
];
}
}
|
import BlogProviderFc2 from './fc2';
import BlogProviderLivedoor from './livedoor';
import BlogProviderSeesaa from './seesaa';
import BlogProviderAmeba from './ameba';
import BlogProviderNinjya from './ninjya';
import BlogProviderRakuten from './rakuten';
import BlogProviderCocolog from './cocolog';
import BlogProviderYaplog from './yaplog';
import BlogProviderJugem from './jugem';
import BlogProviderHatena from './hatena';
import BlogProviderWebryBlog from './webryBlog';
import BlogProviderGoo from './goo';
import BlogProviderWebnode from './webNode';
import BlogProviderWpcom from './wpcom';
class BlogProviderManager {
constructor() {
this.providers = {
fc2: BlogProviderFc2,
livedoor: BlogProviderLivedoor,
seesaa: BlogProviderSeesaa,
ameba: BlogProviderAmeba,
ninjya: BlogProviderNinjya,
rakuten: BlogProviderRakuten,
cocolog: BlogProviderCocolog,
yaplog: BlogProviderYaplog,
jugem: BlogProviderJugem,
hatena: BlogProviderHatena,
webryblog: BlogProviderWebryBlog,
goo: BlogProviderGoo,
webnode: BlogProviderWebnode,
wpcom: BlogProviderWpcom
};
}
getProviderByName(name, opts) {
if (!name) {
throw new Error('ブログ提供元は必須です。');
}
const Provider = this.providers[name.toLowerCase()];
if (!Provider) throw new Error(`現在登録されているブログ提供元ではありません。`);
return new Provider(opts);
}
}
export default BlogProviderManager;
|
package utilities;
import java.awt.Color;
import java.awt.Font;
public class RichText
{
private String text;
private Font font;
private float fontSize;
private Color textColor;
public RichText(String text, Font font, float size, Color c)
{
this.text = text;
this.font = font;
fontSize = size;
textColor = c;
}
public void setText(String text)
{
this.text = text;
}
public String getText()
{
return text;
}
public void setFont(Font font)
{
this.font = font;
}
public Font getFont()
{
return font;
}
public void setSize(float size)
{
this.fontSize = size;
}
public float getSize()
{
return fontSize;
}
public void setColor(Color c)
{
textColor = c;
}
public Color getColor()
{
return textColor;
}
}
|
import core.Bot
import core.NetworkingClient
import core.api.InitialData
import core.api.MatchState
import core.api.Response
import core.api.UnitType
/** Example Kotlin bot implementation for Planetization game. */
class MyBot : Bot {
lateinit var data: InitialData;
// Called only once before the match starts. It holds the
// data that you may need to setup your bot.
override fun setup(data: InitialData) {
this.data = data
}
// Called repeatedly while the match is generating. Read game state using
// state parameter and issue your commands with response parameter.
override fun update(state: MatchState, response: Response) {
// Iterate through all the planets you own
for (planet in state.yourPlanets) {
// If the planet has enough resources, spawn new unit on it
if (planet.canSpawnNewUnit) {
val type = if (Math.random() < 0.5f) UnitType.WARRIOR else UnitType.WORKER
response.spawnUnit(planet.id, type)
}
// Only a certain number of workers can mine resources on
// a planet. Let's send the rest of them somewhere else.
for (i in data.maxActiveWorkersPerPlanet until planet.idsOfUnitsOnPlanet.size) {
val unitId = planet.idsOfUnitsOnPlanet[i]
// Randomly select if you will send the unit to a free or opponent planet
val planets = if (Math.random() < 0.5f) state.freePlanets else state.opponentPlanets
if (planets.isNotEmpty()) {
// Select a random planet in planets and send your unit there
val destinationPlanetIndex = (Math.random() * planets.size).toInt()
val destinationPlanetId = planets[destinationPlanetIndex].id
response.sendUnit(unitId, destinationPlanetId)
}
}
}
}
// Connects your bot to match generator, don't change it.
companion object {
@JvmStatic fun main(args: Array<String>) {
NetworkingClient.connectNew(args, MyBot())
}
}
}
|
require 'sinatra/base'
require 'airbrake'
Airbrake.configure do |c|
c.project_id = 142535
c.project_key = 'c25391b87ebc657115438d5f134c59f1'
# Display debug output.
c.logger.level = Logger::DEBUG
end
class MyApp < Sinatra::Base
use Airbrake::Rack::Middleware
get('/') {
# Indirectly raise a ZeroDivisionError for testing.
1/0
}
end
run MyApp.run!
|
from django.forms import Form, CharField, PasswordInput
from django.contrib.auth.models import User
class RegistrationForm(Form):
username = CharField(label='Username: ', max_length=50)
password = CharField(widget=PasswordInput)
def is_valid(self):
valid = super (Form, self).is_valid()
if not valid:
return valid
uname = self.cleaned_data['username']
users = User.objects.filter(username=uname).count()
if users > 0:
self._errors['Validation_Error'] = 'The username is taken. Pick a new one'
return False
else:
return True
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataTools.Graphs.EdgeWeightedDirectedGraph
{
using Collections;
/// <summary>
/// The EdgeWeightedDigraph class represents an edge-weighted digraph of vertices named 0 through V-1,
/// where each directed edge is a type of DirectedEdge and has a double-value weight.
/// </summary>
public class EdgeWeightedDigraph
{
/// <summary>
/// Number of vertices in this digraph.
/// </summary>
public int V { get; private set; }
/// <summary>
/// Number of edges in this digraph.
/// </summary>
public int E { get; private set; }
// Adjacency lists for vertices.
private LinkedList<DirectedEdge>[] adjacent;
// In degree of vertices.
private int[] inDegree;
/// <summary>
/// Initializes an empty edge-weighted digrpah with V vertices and 0 edges.
/// </summary>
/// <param name="v">The number of vertices.</param>
public EdgeWeightedDigraph(int V) { Initialize(V); }
/// <summary>
/// Returns a random edge-weighted digraph with V vertices and E edges.
/// </summary>
/// <param name="V">The number of vertices.</param>
/// <param name="E">The number of edges.</param>
public EdgeWeightedDigraph(int V, int E)
: this(V)
{
if (E < 0)
throw new ArgumentException("Number of edges in a Digraph must be non-negative.");
for (int i = 0; i < E; i++)
{
int v = StdRandom.Uniform(V);
int w = StdRandom.Uniform(V);
double weight = StdRandom.Uniform(100) * 0.01;
DirectedEdge e = new DirectedEdge(v, w, weight);
AddEdge(e);
}
}
/// <summary>
/// Initializes an edge-weighted digraph from the specified file.
/// The format is the number of vertices V,
/// followed by the number of edges E,
/// followed by E pairs of vertices and edge weights,
/// with each entry separated by white-space.
/// </summary>
/// <param name="fullFileName"></param>
public EdgeWeightedDigraph(string fullFileName)
{
// Read complete content from file.
string text = System.IO.File.ReadAllText(fullFileName);
// Split content into individual strings.
string[] numberString = System.Text.RegularExpressions.Regex.Split(text, "\\s+");
// Get V and E.
int V = int.Parse(numberString[0]);
int E = int.Parse(numberString[1]);
if (V < 0)
throw new ArgumentException("The number of vertices must be non-negative.");
if (E < 0)
throw new ArgumentException("The number of edges must be non-negative.");
// Initializes an empty edge-weighted digraph.
Initialize(V);
// Read edges from index 2 in the numberStrings[].
int numberIndex = 2;
// Read edges and add them into this edge-weighted digraph.
for (int i = 0; i < E; i++)
{
int v = int.Parse(numberString[numberIndex++]);
int w = int.Parse(numberString[numberIndex++]);
ValidateVertex(v);
ValidateVertex(w);
double weight = double.Parse(numberString[numberIndex++]);
DirectedEdge e = new DirectedEdge(v, w, weight);
AddEdge(e);
}
}
/// <summary>
/// Initializes a new edge-weighted digraph that is a deep copy of G.
/// </summary>
/// <param name="G">The edge-weighted digraph to copy.</param>
public EdgeWeightedDigraph(EdgeWeightedDigraph G)
: this(G.V)
{
E = G.E;
for (int v = 0; v < V; v++)
inDegree[v] = G.inDegree[v];
for (int v = 0; v < V; v++)
{
// Reverse so that adjacency list is in same order as original.
Stack<DirectedEdge> reverse = new Stack<DirectedEdge>();
foreach (DirectedEdge e in G.adjacent[v])
reverse.Push(e);
foreach (DirectedEdge e in reverse)
AddEdge(e);
}
}
/// <summary>
/// Initializes an empty edge-weighted digraph with V vertices and 0 edges.
/// This is a helper function for constructors.
/// </summary>
/// <param name="V">The number of vertices.</param>
private void Initialize(int V)
{
if (V < 0)
throw new ArgumentException("Number of vertices in a Digraph must be non-negative.");
this.V = V;
E = 0;
inDegree = new int[V];
adjacent = new LinkedList<DirectedEdge>[V];
for (int v = 0; v < V; v++)
adjacent[v] = new LinkedList<DirectedEdge>();
}
/// <summary>
/// Throw an ArgumentOutOfRangeException unless 0 <= v < V
/// </summary>
/// <param name="v">The vertex.</param>
private void ValidateVertex(int v)
{
if ((v < 0) || (v >= V))
throw new ArgumentOutOfRangeException(string.Format("Vertex {0} is not between [0,{1}].", v, V - 1));
}
/// <summary>
/// Adds the directed edge e to this edge-weighted digrpah.
/// </summary>
/// <param name="e">The edge.</param>
public void AddEdge(DirectedEdge e)
{
int v = e.From();
int w = e.To();
ValidateVertex(v);
ValidateVertex(w);
adjacent[v].AddFirst(e);
inDegree[w]++;
E++;
}
/// <summary>
/// Returns the directed edges incident from vertex v as an enumerator.
/// </summary>
/// <param name="v">The edge.</param>
/// <returns>The directed edges incident from vertex v as an enumerator.</returns>
public IEnumerable<DirectedEdge> Adjacent(int v)
{
ValidateVertex(v);
return adjacent[v];
}
/// <summary>
/// Returns the number of edges incident from vertex v.
/// This is known as the out degree of vertex v.
/// </summary>
/// <param name="v">The vertex.</param>
/// <returns>The out-degree of vertex v.</returns>
public int OutDegree(int v)
{
ValidateVertex(v);
return adjacent[v].Size;
}
/// <summary>
/// Returns the number of edges incident to vertex v.
/// This is known as the in degree of vertex v.
/// </summary>
/// <param name="v">The vertex.</param>
/// <returns>The indegree of vertex v.</returns>
public int InDegree(int v)
{
ValidateVertex(v);
return inDegree[v];
}
/// <summary>
/// Returns all directed edges in this directed digraph, as an enumerator.
/// </summary>
/// <returns>All directed edges in this directed digraph, as an enumerator.</returns>
public IEnumerable<DirectedEdge> Edges()
{
LinkedList<DirectedEdge> list = new LinkedList<DirectedEdge>();
for (int v = 0; v < V; v++)
{
foreach (DirectedEdge e in adjacent[v])
list.AddFirst(e);
}
return list;
}
/// <summary>
/// Returns a string representation of this edge-weighted digraph.
/// </summary>
/// <returns>A string representation of this edge-weighted digraph.</returns>
public override string ToString()
{
StringBuilder s = new StringBuilder();
s.Append(V + " vertices and " + E + " edges\n");
for (int v = 0; v < V; v++)
{
s.Append(v + ": ");
foreach (DirectedEdge e in adjacent[v])
s.Append(e + " ");
s.Append("\n");
}
return s.ToString();
}
}
}
|
SELECT non2.nonprofits_id, non2.name as charity, weight as similarity
FROM giving.nonprofit_twitter_edges as edges, giving.nonprofits as non, giving.nonprofits as non2
WHERE non.ein = 'XX-XXXXXXX' and non.twitter_name = edges.source and non2.twitter_name = edges.target
UNION
SELECT non2.nonprofits_id, non2.name as charity, weight as similarity
FROM giving.nonprofit_twitter_edges as edges, giving.nonprofits as non, giving.nonprofits as non2
WHERE non.ein = 'XX-XXXXXXX' and non.twitter_name = edges.target and non2.twitter_name = edges.source
ORDER BY similarity DESC
LIMIT 10
|
# Scaffold Market
[](https://travis-ci.org/ant-design/scaffold-market)
- All Scaffolds: http://scaffold.ant.design/
- Submit new scaffold: http://scaffold.ant.design/#/contribute
- Ant Design: https://ant.design/
- Ant Design Pro: https://pro.ant.design/

## Development
```bash
$ npm install
$ npm start
```
|
package weco.storage_service
import java.time.Instant
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers
import weco.storage_service.generators.{
ExternalIdentifierGenerators,
StorageSpaceGenerators
}
import weco.storage_service.ingests.models._
import weco.storage.fixtures.S3Fixtures
class SourceLocationPayloadTest
extends AnyFunSpec
with Matchers
with ExternalIdentifierGenerators
with StorageSpaceGenerators
with S3Fixtures {
it("creates a payload from an ingest") {
val ingestId = createIngestID
val ingestType = CreateIngestType
val sourceLocation = createS3ObjectLocation
val space = createStorageSpace
val ingestDate = Instant.now()
val externalIdentifier = createExternalIdentifier
val ingest = Ingest(
id = ingestId,
ingestType = ingestType,
sourceLocation = S3SourceLocation(
location = sourceLocation
),
space = space,
createdDate = ingestDate,
externalIdentifier = externalIdentifier,
callback = None,
status = Ingest.Accepted
)
val expectedPayload = SourceLocationPayload(
context = PipelineContext(
ingestId = ingestId,
ingestType = ingestType,
storageSpace = space,
ingestDate = ingestDate,
externalIdentifier = externalIdentifier
),
sourceLocation = S3SourceLocation(sourceLocation)
)
SourceLocationPayload(ingest) shouldBe expectedPayload
}
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Start our application."""
from flask import g
from flask_babel import Babel
from api.src.config.create_app import create_app
app = create_app()
babel = Babel(app)
app.run(**app.config.get_namespace('RUN_'))
@babel.timezoneselector
def get_timezone():
"""Set the user timezone on babel."""
user = g.get('user', None)
if user is not None:
return user.timezone
|
# frozen_string_literal: true
module Armadillo
class Configuration
attr_accessor :rails_config, :envs, :position, :environments
def setup!
@environments = []
@envs.to_a.each { |env| @environments << Environment.new(env) }
mount!
end
def mount!
return unless current&.show
@rails_config.rack_dev_mark.enable = true
@rails_config.rack_dev_mark.theme = theme
@rails_config.rack_dev_mark.env = current.name.to_s.titleize
end
private
def current
@current ||= @environments.find(&:condition)
end
def theme
[:title, Rack::DevMark::Theme::GithubForkRibbon.new(position: @position)]
end
end
end
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(optin_builtin_traits)]
use std::marker::Copy;
impl Copy for i32 {}
//~^ ERROR conflicting implementations of trait `std::marker::Copy` for type `i32`:
//~| ERROR only traits defined in the current crate can be implemented for arbitrary types
enum TestE {
A
}
struct MyType;
struct NotSync;
impl !Sync for NotSync {}
impl Copy for TestE {}
impl Clone for TestE { fn clone(&self) -> Self { *self } }
impl Copy for MyType {}
impl Copy for &'static mut MyType {}
//~^ ERROR the trait `Copy` may not be implemented for this type
impl Clone for MyType { fn clone(&self) -> Self { *self } }
impl Copy for (MyType, MyType) {}
//~^ ERROR the trait `Copy` may not be implemented for this type
//~| ERROR only traits defined in the current crate can be implemented for arbitrary types
impl Copy for &'static NotSync {}
//~^ ERROR conflicting implementations of trait `std::marker::Copy` for type `&NotSync`:
impl Copy for [MyType] {}
//~^ ERROR the trait `Copy` may not be implemented for this type
//~| ERROR only traits defined in the current crate can be implemented for arbitrary types
impl Copy for &'static [NotSync] {}
//~^ ERROR conflicting implementations of trait `std::marker::Copy` for type `&[NotSync]`:
//~| ERROR only traits defined in the current crate can be implemented for arbitrary types
fn main() {
}
|
package org.dave.bats.util.serialization;
public @interface SerializationHandler {
Class readClass() default void.class;
Class writeClass() default void.class;
}
|
package game
import ai.MiniMax
import game.Implicit.convertToPlayer
import game.boards.implementations.Board2dArray
import game.types.Position
import org.scalacheck.Gen
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{FlatSpec, Matchers}
import scala.collection.immutable.NumericRange
class BoardMNKPSpec extends FlatSpec with Matchers with GeneratorDrivenPropertyChecks {
"BoardMNKP" should "compute nextPlayer correctly" in {
val maxP: Byte = Byte.MaxValue
val m: Short = (maxP + 1).toShort
val n: Short = 3
val k: Short = 3
val ps = for (i <- Gen.choose[Byte](2, maxP)) yield i
forAll(ps) { p: Byte =>
whenever(p >= 2) {
val game = new BoardMNKP(m, n, k, p) with Board2dArray
game.lastPlayer shouldBe p
for (i <- NumericRange.inclusive[Short](1, p, 1)) {
val np = game.nextPlayer()
np shouldBe i
game.playMove(Position(i, 0), np) shouldBe true
}
}
}
}
ignore should "draw using Minimax with 3, 3, 3, 2" in {
val game = new BoardMNKP(3, 3, 3, 2) with MiniMax with Board2dArray
game.solve shouldBe 0
}
}
|
# document and view classes for MFC.
import win32ui
import win32con
from . import object
from . import window
class View(window.Wnd):
def __init__(self, initobj):
window.Wnd.__init__(self, initobj)
def OnInitialUpdate(self):
pass
# Simple control based views.
class CtrlView(View):
def __init__(self, doc, wndclass, style=0):
View.__init__(self, win32ui.CreateCtrlView(doc, wndclass, style))
class EditView(CtrlView):
def __init__(self, doc):
View.__init__(self, win32ui.CreateEditView(doc))
class RichEditView(CtrlView):
def __init__(self, doc):
View.__init__(self, win32ui.CreateRichEditView(doc))
class ListView(CtrlView):
def __init__(self, doc):
View.__init__(self, win32ui.CreateListView(doc))
class TreeView(CtrlView):
def __init__(self, doc):
View.__init__(self, win32ui.CreateTreeView(doc))
# Other more advanced views.
class ScrollView(View):
def __init__(self, doc):
View.__init__(self, win32ui.CreateView(doc))
class FormView(View):
def __init__(self, doc, id):
View.__init__(self, win32ui.CreateFormView(doc, id))
class Document(object.CmdTarget):
def __init__(self, template, docobj=None):
if docobj is None:
docobj = template.DoCreateDoc()
object.CmdTarget.__init__(self, docobj)
class RichEditDoc(object.CmdTarget):
def __init__(self, template):
object.CmdTarget.__init__(self, template.DoCreateRichEditDoc())
class CreateContext:
"A transient base class used as a CreateContext"
def __init__(self, template, doc=None):
self.template = template
self.doc = doc
def __del__(self):
self.close()
def close(self):
self.doc = None
self.template = None
class DocTemplate(object.CmdTarget):
def __init__(
self, resourceId=None, MakeDocument=None, MakeFrame=None, MakeView=None
):
if resourceId is None:
resourceId = win32ui.IDR_PYTHONTYPE
object.CmdTarget.__init__(self, self._CreateDocTemplate(resourceId))
self.MakeDocument = MakeDocument
self.MakeFrame = MakeFrame
self.MakeView = MakeView
self._SetupSharedMenu_()
def _SetupSharedMenu_(self):
pass # to be overridden by each "app"
def _CreateDocTemplate(self, resourceId):
return win32ui.CreateDocTemplate(resourceId)
def __del__(self):
object.CmdTarget.__del__(self)
def CreateCreateContext(self, doc=None):
return CreateContext(self, doc)
def CreateNewFrame(self, doc):
makeFrame = self.MakeFrame
if makeFrame is None:
makeFrame = window.MDIChildWnd
wnd = makeFrame()
context = self.CreateCreateContext(doc)
wnd.LoadFrame(
self.GetResourceID(), -1, None, context
) # triggers OnCreateClient...
return wnd
def CreateNewDocument(self):
makeDocument = self.MakeDocument
if makeDocument is None:
makeDocument = Document
return makeDocument(self)
def CreateView(self, frame, context):
makeView = self.MakeView
if makeView is None:
makeView = EditView
view = makeView(context.doc)
view.CreateWindow(frame)
class RichEditDocTemplate(DocTemplate):
def __init__(
self, resourceId=None, MakeDocument=None, MakeFrame=None, MakeView=None
):
if MakeView is None:
MakeView = RichEditView
if MakeDocument is None:
MakeDocument = RichEditDoc
DocTemplate.__init__(self, resourceId, MakeDocument, MakeFrame, MakeView)
def _CreateDocTemplate(self, resourceId):
return win32ui.CreateRichEditDocTemplate(resourceId)
def t():
class FormTemplate(DocTemplate):
def CreateView(self, frame, context):
makeView = self.MakeView
# view = FormView(context.doc, win32ui.IDD_PROPDEMO1)
view = ListView(context.doc)
view.CreateWindow(frame)
t = FormTemplate()
return t.OpenDocumentFile(None)
|
---
title: In-cluster Deployment
weight: 10
---
A common use-case for any Kubernetes web UI is to deploy it in-cluster and
set up an ingress server for having it available to users.
We maintain a simple/vanilla [file](https://github.com/kinvolk/headlamp/blob/main/kubernetes-headlamp.yaml)
for setting up a Headlamp deployment and service. Be sure to review it and change
anything you need.
If you're happy with the options in the this deployment file, and assuming
you have a running Kubernetes cluster and your `kubeconfig` pointing to it,
you can run:
```bash
kubectl apply -f https://raw.githubusercontent.com/kinvolk/headlamp/main/kubernetes-headlamp.yaml
```
## Exposing Headlamp with an ingress server
With the instructions in the previous section, the Headlamp service should be
running, but you still need the
ingress server as mentioned. We provide an example sample ingress yaml file
for this purpose, but you have to manually replace the __URL__ placeholder
with the desired URL (the ingress file also assumes that you have contour
and a cert-manager set up, but if you don't then you'll just not have TLS).
Assuming your URL is `headlamp.mydeployment.io`, getting the sample ingress
file and changing the URL can quickly be done by:
```bash
curl -s https://raw.githubusercontent.com/kinvolk/headlamp/main/kubernetes-headlamp-ingress-sample.yaml | sed -e s/__URL__/headlamp.mydeployment.io/ > headlamp-ingress.yaml
```
and with that, you'll have a configured ingress file, so verify it and apply it:
```bash
kubectl apply -f ./headlamp-ingress.yaml
```
## Exposing Headlamp with port-forwarding
If you want to quickly access Headlamp (after having its service running) and
don't want to set up an ingress for it, you can run use port-forwarding as follows:
```bash
kubectl port-forward -n kube-system service/headlamp 8080:80
```
and then you can access `localhost:8080` in your browser.
## Accessing Headlamp
Once Headlamp is up and running, be sure to enable access to it either by creating
a [service account](../#create-a-service-account-token) or by setting up
[OIDC](./oidc).
|
import prevIcon from "./assets/icon-prev.svg";
import nextIcon from "./assets/icon-next.svg";
import {Box} from "@material-ui/core";
import React from "react";
import styles from './style/HarPaging.module.sass'
import numeral from 'numeral';
interface HarPagingProps {
showPageNumber?: boolean;
}
export const HarPaging: React.FC<HarPagingProps> = ({showPageNumber=false}) => {
return <Box className={styles.HarPaging} display='flex'>
<img src={prevIcon} onClick={() => {
// harStore.data.moveBack(); todo
}} alt="back"/>
{showPageNumber && <span className={styles.text}>
Page <span className={styles.pageNumber}>
{/*{numeral(harStore.data.currentPage).format(0, 0)}*/} //todo
</span>
</span>}
<img src={nextIcon} onClick={() => {
// harStore.data.moveNext(); todo
}} alt="next"/>
</Box>
};
|
//import javax.inject.Inject
//import play.api.http.{DefaultHttpFilters, HttpFilters}
//import play.filters.cors.CORSFilter
//
//class Filters @Inject() (corsFilter: CORSFilter) extends DefaultHttpFilters {
// override def val filters = Seq(corsFilter.Filters.super)
//}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics.CodeAnalysis;
namespace vsteam_lib.Test.Provider
{
[TestClass]
[ExcludeFromCodeCoverage]
public class FeedTests
{
[TestMethod]
public void Feed_Constructor()
{
// Arrange
var obj = BaseTests.LoadJson("Get-VSTeamFeed.json");
// Act
var actual = new Feed(obj[0]);
// Assert
Assert.AreEqual("ber", actual.Name, "Name");
Assert.AreEqual(null, actual.Description, "Description");
Assert.AreEqual(true, actual.UpstreamEnabled, "UpstreamEnaabled");
Assert.AreEqual("00000000-0000-0000-0000-000000000001", actual.Id, "Id");
Assert.AreEqual("00000000-0000-0000-0000-000000000001", actual.FeedId, "FeedId");
Assert.AreEqual("https://feeds.dev.azure.com/Test/_apis/Packaging/Feeds/00000000-0000-0000-0000-000000000000", actual.Url, "Url");
Assert.IsNotNull(actual.UpstreamSources, "UpstreamSources");
Assert.AreEqual(4, actual.UpstreamSources.Count, "UpstreamSources.Count");
Assert.AreEqual("npmjs", actual.UpstreamSources[0].Name, "Name");
Assert.AreEqual("ok", actual.UpstreamSources[0].Status, "Status");
Assert.AreEqual("npm", actual.UpstreamSources[0].Protocol, "Protocol");
Assert.IsNotNull(actual.UpstreamSources[0].InternalObject, "InternalObject");
Assert.AreEqual("00000000-0000-0000-0000-000000000010", actual.UpstreamSources[0].ID);
Assert.AreEqual("public", actual.UpstreamSources[0].UpstreamSourceType, "UpstreamSourceType");
Assert.AreEqual("https://registry.npmjs.org/", actual.UpstreamSources[0].Location, "Location");
Assert.AreEqual("https://registry.npmjs.org/", actual.UpstreamSources[0].DisplayLocation, "DisplayLocation");
}
}
}
|
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import "errors"
// RetryableError indicates that an error can possibly be retried.
// Cloud providers can wrap selectively wrap certain errors to
// indicate that they might be retryable.
type RetryableError interface {
error
IsRetryable() bool
}
// CodedError can be implemented by error types that have a
// short (1-3 word) summary of their error status. This can be
// used by code in places where longer error messages won't do,
// such as Conditions.
type CodedError interface {
// Very short message explaining the problem
ErrorCode() string
}
// IsRetryable is a utility function intended to help controllers and
// other clients determine whether a particular error indicates a
// fundamental problem with a resource (one that cannot be resolved
// without operator intervention) or whether it indicates a problem
// that could simply resolve itself.
func IsRetryable(err error) bool {
var transient RetryableError
if errors.As(err, &transient) {
return transient.IsRetryable()
}
return false
}
// ErrorCode returns a short version of the error's message, if there
// is one, otherwise nothing. Useful in places where a long message
// isn't acceptable, and you don't want to just randomly hack off a
// longer error message at some fixed byte offset.
func ErrorCode(err error) string {
var transient CodedError
if errors.As(err, &transient) {
return transient.ErrorCode()
}
return ""
}
|
package edu.cornell.cs.apl.viaduct.errors
import edu.cornell.cs.apl.prettyprinting.Document
import edu.cornell.cs.apl.viaduct.syntax.HasSourceLocation
/**
* Thrown when a `break`, `continue`, or a similar statement occurs outside the scope of a loop.
*/
class JumpOutsideLoopScopeError(val node: HasSourceLocation) : CompilationError() {
override val category: String
get() = "Control Error"
override val source: String
get() = node.sourceLocation.sourcePath
override val description: Document
get() =
Document("This statement is only valid inside a loop:")
.withSource(node.sourceLocation)
}
|
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.patches as patch
from matplotlib import ticker
import numpy as np
from astropy.io import fits
from copy import copy
from argparse import ArgumentParser
parser = ArgumentParser(prog='Plot continuum', description='Free free emission from HII regions')
parser.add_argument('-i', '--id', help='id of fits file to be plotted')
args = parser.parse_args()
if args.id is None: id = ''
else: id = args.id
tag = 'img_HII_env+disc_'+id
#------------------
#LOADING DATA
#------------------
if id: image_cont_349 = 'img_HII_env+disc-'+id+'.fits'
else: image_cont_349 = 'img_HII_env+disc.fits'
data_349, header_349 = fits.getdata(image_cont_349, header=True)
if id == 'CONV_noise': pass
else: data_349 = data_349[0]
#-------------------------
#RESOLUTION AND IMAGE SIZE
#-------------------------
distance = 4000 # parsecs
x_lim = 4000 #AUs
extent = [-x_lim, x_lim, -x_lim, x_lim]
#-----------
#CONT. DATA
#-----------
Npix_349 = header_349['NAXIS1']
resolution_349 = abs(header_349['CDELT1']) * 3600 # in arcsecs
#x_lim = (round (Npix / 2.) - x_init) * resolution * distance
x_inits = int(round (round (Npix_349 / 2.) - (x_lim / (resolution_349 * distance)) ))
x_ends = Npix_349 - x_inits
#-----
#BEAM
#-----
header = header_349
i = 0
ellipse = 0
flag_beam = False
try:
if header['BMAJ']: pass
a, b = np.array([header['BMAJ'] , header['BMIN']]) * 3600 * distance
if id == 'CONV': f_c, e_c = 'gray', 'white'
elif id == 'CONV_noise': f_c, e_c = 'black', 'white'
ellipse = patch.Ellipse(xy = (-3500,-3500), angle = 90 + header['BPA'],
width = a, height = b, linewidth = 1,
fill = True, facecolor = f_c, edgecolor = e_c)
flag_beam = True
except KeyError: pass
#-----
#-----
#-----------------------------
#COLORS IN LIMITS OF COLORBARS
#-----------------------------
#Use copy so that we don't mutate the global colormap instance
colormm = plt.cm.hot
palette_hot = copy(colormm)
palette_hot.set_over('red', 0.8)#colormm(255), 0.8)
if id == 'CONV_noise': palette_hot.set_under('gray', 0.9)#colormm(0), 0.8)
else: palette_hot.set_under('black', 1.0)#colormm(0), 0.8)
colormm = plt.cm.cubehelix_r
palette_helix = copy(colormm)
palette_helix.set_over('black', 1)#colormm(255), 0.8)
palette_helix.set_under('white', 1)#colormm(0), 0.8)
#-----------------------------
#-----------------------------
#---------
#PLOTTING
#---------
images = data_349
fig, ax = plt.subplots(nrows=1, ncols=1) #, figsize=(8, 4.5))
if id == 'CONV_noise': ax.set_facecolor('darkgray')
else: ax.set_facecolor('black')
im = np.ones((3,3))
#plt.subplots_adjust(bottom = 0.01, top = 0.99, left = 0.1, right = 0.9, hspace = 0.1, wspace = 0.3)
vmax = images.max()
vmin = vmax * 1e-3
im = ax.imshow(images[::-1][x_inits : x_ends, x_inits : x_ends],
cmap = palette_hot,
norm=colors.LogNorm(vmin = vmin, vmax = vmax),
extent = extent)
if flag_beam: ax.add_artist(ellipse)
#-----------------
#LABELS AND TITLES
#-----------------
if flag_beam: cbar_label = r'log$_{10}$($I_\nu$ [Jy beam$^{-1}$])'
else: cbar_label = r'log$_{10}$($I_\nu$ [Jy pixel$^{-1}$])'
cbar_extend = 'min'
ax_title = r'$\nu$ = 33 GHz, $S_\nu$ = 103 $\rm{mJy}$'
if id == 'CONV_noise': ax_title += r', $\sigma$ = 6 $\rm{\mu Jy}/bm$'
cbar = fig.colorbar(im, extend = cbar_extend, ax = ax, aspect = 15,
orientation = 'vertical', pad = 0.02, shrink = 1.0)
cbar.set_label(cbar_label, labelpad = 2, fontsize = 8)
cbar.ax.tick_params(labelsize = 8)
ax.set_title(ax_title, fontsize = 10)
ax.set_ylabel('AU', fontsize = 10)
ax.set_xlabel('AU', fontsize = 10)
ax.tick_params(axis='both', labelsize = 7)
#-----------------
#-----------------
plt.savefig('%s.png'%tag, facecolor = 'white', dpi = 500)
plt.show()
#---------
#---------
|
using FluentAssertions;
using Xunit;
using AutoPipe.Modifications;
namespace AutoPipe.Tests.Units
{
public class ProcessorMatcherByTypeTests
{
[Fact]
public void Instance_ReturnsTrue_WhenTheSameTypeIsPassed()
{
var processor = new TestProcessor(() => { });
new ProcessorMatcherByType(typeof(TestProcessor)).Matches(processor).Should().BeTrue();
}
[Fact]
public void Instance_ReturnsFalse_WhenOtherTypeIsPassed()
{
var processor = new Processor(o => PipelineTask.CompletedTask);
new ProcessorMatcherByType(typeof(TestProcessor)).Matches(processor).Should().BeFalse();
}
}
}
|
Changelog
=========
2016-02-11 Load Balancer added
The script will install haproxy and create a new instance
listening on http/80. Requests are forwarded to web1:7777
and web2:7777. Run as root:
lib/templates/root/setup-proxy.sh
2016-02-11 PS3: provisioning of cluster was successful. We need to skip
last step (verification), since health checks can only be
executed. Instance: iamvc-ps3
2016-02-12 Health-Check: a new subcommand is calling the Oracle Health
Checks in all currently possible variations. Call it instead
the broken postinstall verification phase (last phase)
|
using System.Management.Automation;
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.TeamFoundation.Wiki.WebApi;
using TfsCmdlets.Extensions;
namespace TfsCmdlets.Cmdlets.Wiki
{
/// <summary>
/// Creates a new Wiki repository in a team project.
/// </summary>
[Cmdlet(VerbsCommon.New, "TfsWiki", ConfirmImpact = ConfirmImpact.Medium, SupportsShouldProcess = true)]
[OutputType(typeof(WikiV2))]
public class NewWiki : NewCmdletBase<WikiV2>
{
/// <summary>
/// Specifies the name of the new Wiki
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "Create Code Wiki")]
[Alias("Name", "Id")]
public string Wiki { get; set; }
/// <summary>
/// Specifies the name or ID of the Git repository to publish as a Wiki
/// </summary>
[Parameter(Position = 1, Mandatory = true, ParameterSetName = "Create Code Wiki")]
public object Repository { get; set; }
/// <summary>
/// Creates a provisioned ("project") Wiki in the specified Team Project.
/// </summary>
[Parameter(ParameterSetName = "Provision Project Wiki", Mandatory = true)]
public SwitchParameter ProjectWiki { get; set; }
}
partial class WikiDataService
{
protected override WikiV2 DoNewItem()
{
var (tpc, tp) = GetCollectionAndProject();
var isProjectWiki = GetParameter<bool>(nameof(NewWiki.ProjectWiki));
var createParams = new WikiCreateParametersV2()
{
Name = GetParameter<string>(nameof(NewWiki.Wiki)),
Type = isProjectWiki ? WikiType.ProjectWiki : WikiType.CodeWiki,
ProjectId = tp.Id
};
if(createParams.Type == WikiType.CodeWiki)
{
var repo = GetItem<GitRepository>(new {
Repository = GetParameter<object>(nameof(NewWiki.Repository)),
Project = tp
});
createParams.RepositoryId = repo.Id;
}
var client = GetClient<WikiHttpClient>();
return client.CreateWikiAsync(createParams)
.GetResult("Error creating Wiki repository");
}
}
}
|
SELECT * FROM " + table + " WHERE
SELECT * FROM " + table + " ORDER BY RANDOM() LIMIT 1
SELECT * FROM " + table;
SELECT * FROM " + table + " WHERE " + QuoteFields.TEXT + " IS NOT NULL ORDER BY RANDOM() LIMIT 1
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "stdio.h"
#include "BackupManagerActor.h"
#include <elastos/System.h>
#include <elastos/utility/logging/Logger.h>
#include <unistd.h>
using Elastos::Core::System;
using Elastos::Utility::Logging::Logger;
using Elastos::IO::CFile;
using Elastos::IO::IFile;
using Elastos::IO::IRandomAccessFile;
using Elastos::IO::CRandomAccessFile;
using Elastos::Droid::Commands::Bmgr::BackupManagerActor;
void Usage()
{
printf("Bmgr <Option> [args ...]\n");
printf("Options: \n");
printf("\t-?\t\t\tFor Help\n");
}
int main(int argc, char *argv[])
{
if (argc < 2) {
Usage();
return 0;
}
AutoPtr<BackupManagerActor> actor = new BackupManagerActor();
actor->Init();
char* cmd;
cmd = argv[1];
if(!strcmp("enabled", cmd)) {
actor->DoEnabled();
}
else if (!strcmp("enable", cmd)) {
int isEnable = atoi(argv[2]);
actor->DoEnable(isEnable);
printf("doenable\n");
}
else if (!strcmp("backup", cmd)) {
char* pkg = argv[2];
String pkgName(pkg);
actor->DoBackup(pkgName);
}
else if (!strcmp("transport", cmd)) {
char* transport = argv[2];
String transportName(transport);
actor->DoTransport(transportName);
}
else if (!strcmp("listTransport", cmd)) {
actor->DoListTransport();
}
else if (!strcmp("run", cmd)) {
actor->DoRun();
}
else if (!strcmp("restore", cmd)) {
char* restore = argv[2];
String restoreName(restore);
actor->DoRestorePackage(restoreName);
}
else if (!strcmp("?", cmd)) {
Usage();
}
else {
printf("Unknown command\n");
Usage();
}
return 0;
}
|
/*Copyright 2019 Steve Meckl
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. */
#include "stdafx.h"
#include "DNSLookup.h"
#include <cpprest\json.h>
#include <windns.h> //DNS api's
using namespace web::json;
const std::wstring DNSLookup::DNS_LOOKUP = L"networkDNSLookup";
const std::wstring DNSLookup::FQDN = L"fqdn";
DNSLookup::DNSLookup()
{
}
DNSLookup::~DNSLookup()
{
}
std::shared_ptr<IArtifact> DNSLookup::createArtifact(const std::wstring &jsonData)
{
std::shared_ptr<IArtifact> pArt(reinterpret_cast<IArtifact*>(new DNSLookup(jsonData)));
return pArt;
}
// Methods required for IArtifact interface
DNSLookup::DNSLookup(const std::wstring &jsonData)
{
utility::stringstream_t ss;
ss << jsonData.c_str();
value v = value::parse(ss);
if (v.has_field(FQDN))
fqdn(v[FQDN].as_string());
}
PhorgrError DNSLookup::Phorge(const std::wstring &strKillEvent)
{
PhorgrError ret(PhorgrError::Success);
PDNS_RECORD pRecord;
if(DnsQuery_W(fqdn().c_str(), DNS_TYPE_A, DNS_QUERY_WIRE_ONLY, NULL, &pRecord, NULL))
{
ret = PhorgrError::NetworkDNS;
}
return ret;
}
PhorgrError DNSLookup::Erase(const std::wstring &strKillEvent)
{
PhorgrError ret(PhorgrError::Success);
// There is no way to Erase this artifact type, as once the request occurs
// the evidence is gone from the host making the query.
return ret;
}
// Accessors
void DNSLookup::fqdn(const std::wstring &fqdn)
{
m_fqdn = fqdn;
}
const std::wstring &DNSLookup::DNSLookup::fqdn() const
{
return m_fqdn;
}
|
require File.expand_path('../../support_helper', __FILE__)
def register_seed_engines
clear_engine_instances
file = nil
register_engine(file: file, path: 'test/framework/core', platform_path: 'test/framework')
register_engine(file: file, path: 'test/framework/seed_one', platform_path: 'test/framework')
register_engine(file: file, path: 'test/framework/seed_two', platform_path: 'test/framework')
register_engine(file: file, path: 'test/framework/seed_zero', platform_path: 'test/framework')
register_engine(file: file)
register_engine(file: file, path: 'test/platform/seed_zero')
register_engine(file: file, path: 'test/platform/seed_one')
register_engine(file: file, path: 'test/platform/seed_two')
end
def seed_loader
Totem::Core::Support::SeedLoader
end
|
package com.learn.tablayout;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.viewpage)
MyViewPager viewpage;
@BindView(R.id.tablayout)
TabLayout tablayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
FragmentManager fm = getSupportFragmentManager();
viewpage.setAdapter(new FragmentAdapter(fm));
viewpage.setPagingEnabled(false);
tablayout.setupWithViewPager(viewpage);
//在这里添加增加图标方法
addIcon();
tablayout.setTabMode(TabLayout.MODE_FIXED);
}
private void addIcon() {
for (int i = 0; i < tablayout.getTabCount(); i++) {
tablayout.getTabAt(i).setIcon(R.mipmap.ic_launcher_round);
}
}
}
|
require 'test/unit'
require 'rbconfig'
class TestRbConfig < Test::Unit::TestCase
def test_sitedirs
RbConfig::MAKEFILE_CONFIG.each do |key, val|
next unless /\Asite(?!arch)/ =~ key
assert_match(/(?:\$\(|\/)site/, val, key)
end
end
def test_vendordirs
RbConfig::MAKEFILE_CONFIG.each do |key, val|
next unless /\Avendor(?!arch)/ =~ key
assert_match(/(?:\$\(|\/)vendor/, val, key)
end
end
def test_archdirs
RbConfig::MAKEFILE_CONFIG.each do |key, val|
next unless /\A(?!site|vendor|archdir\z).*arch.*dir\z/ =~ key
assert_match(/\$\(arch|\$\(rubyarchprefix\)/, val, key)
end
end
def test_sitearchdirs
bug7823 = '[ruby-dev:46964] [Bug #7823]'
RbConfig::MAKEFILE_CONFIG.each do |key, val|
next unless /\Asite.*arch.*dir\z/ =~ key
assert_match(/\$\(sitearch|\$\(rubysitearchprefix\)/, val, "#{key} #{bug7823}")
end
end
def test_vendorarchdirs
bug7823 = '[ruby-dev:46964] [Bug #7823]'
RbConfig::MAKEFILE_CONFIG.each do |key, val|
next unless /\Avendor.*arch.*dir\z/ =~ key
assert_match(/\$\(sitearch|\$\(rubysitearchprefix\)/, val, "#{key} #{bug7823}")
end
end
end
|
"""File operations for this integration."""
import shutil
import os
from .const import (
LOVELACE_CARD_DIR,
LOVELACE_CUSTOM_CARDS,
LOVELACE_DASHBOARD_URL_PATH,
LOVELACE_DIR,
)
from .share import get_hass
async def setup_files() -> None:
"""Setup files for this integration."""
await update_files()
def mkdir(path: str, remove: bool = False) -> None:
"""Make a directory if it does not exist."""
if os.path.exists(path) and remove:
shutil.rmtree(path)
if not os.path.exists(path):
os.makedirs(path)
async def update_files() -> None:
"""Copy files from the integration's source to HA config directory."""
py_dir = os.path.dirname(__file__)
# Copy custom Lovelace cards
local_dir = get_hass().config.path("www")
mkdir(local_dir)
card_dir = os.path.join(local_dir, LOVELACE_DASHBOARD_URL_PATH)
mkdir(card_dir, True)
for card in LOVELACE_CUSTOM_CARDS:
src_card_dir = os.path.join(
py_dir, LOVELACE_DIR, LOVELACE_CARD_DIR, card["dirname"]
)
dst_card_dir = os.path.join(card_dir, card["dirname"])
shutil.copytree(src_card_dir, dst_card_dir)
|
<?php
namespace HotspotMap\Model\ORM;
class PlaceModel
{
public $latitude = 0;
public $longitude = 0;
public $address = "";
public $country = "";
public $town = "";
public $name = "";
public $distance = 0;
public $description = "";
public $validated = 0;
public $copy_of = 0;
protected $website = "";
protected $id;
}
|
/**
* Copyright 2014 CMBI (contact: <Coos.Baakman@radboudumc.nl>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.ru.cmbi.vase.analysis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import nl.ru.cmbi.vase.data.stockholm.Alignment;
public class Calculator {
/** logger. */
private static final Logger LOG = Logger.getLogger(Calculator.class);
public static MutationDataObject generateCorrelatedMutationAndEntropyVariabilityData( Alignment alignment ) {
MutationDataObject cmdo = new MutationDataObject();
List<Double> entropyScores = new ArrayList<Double>();
List<Integer> variabilityScores = new ArrayList<Integer>();
for (int i = 0; i < alignment.countColumns(); i++) {
Map<Character, Double> residueOccurrences = new HashMap<Character, Double>();
int n=0;
for (String label : alignment.getLabels()) {
char oneLetterCode = Character.toUpperCase( alignment.getAlignedSeq(label).charAt(i) );
if( !Character.isLetter(oneLetterCode) ||
oneLetterCode == 'X' || oneLetterCode== 'Z' ||
oneLetterCode == 'B' || oneLetterCode== 'J' ||
oneLetterCode == 'U' || oneLetterCode== 'O' ) {
continue;
}
if(!residueOccurrences.containsKey(oneLetterCode)) {
residueOccurrences.put(oneLetterCode, 1.0);
}
else {
residueOccurrences.put(oneLetterCode, residueOccurrences.get(oneLetterCode) + 1.0);
}
n++;
}
double entropyScore = 0.0;
int variabilityScore = 0;
for (Character oneLetterCode : residueOccurrences.keySet()) {
// min 0.0, max 1.0
double relativeOccurrence = residueOccurrences.get(oneLetterCode) / (1.0 * n );
if(relativeOccurrence > 0.0) {
entropyScore -= relativeOccurrence * Math.log(relativeOccurrence);
}
if (relativeOccurrence > 0.005) {
variabilityScore++;
}
}
entropyScores.add(entropyScore);
variabilityScores.add(variabilityScore);
}
cmdo.setEntropyScores(entropyScores);
cmdo.setVariabilityScores(variabilityScores);
return cmdo;
}
}
|
// A sample project to use ALL THE SYNTAX FEATURES
fn main() {
println!("Hello, world!");
let number: i32 = 42;
let (x,y,z) = (1,2,3);
let small_int:i8 = number as i8; // Unsafe?
let small_int:i32 = small_int as i32 + 212; // Shadowing!
let mut thing = 42;
thing += 106;
print_int(thing);
print_int(small_int);
println!("{},{},{}", x, y, z);
print_int(sum(thing, number));
let func = print_int; // Function pointers!
func(123);
let do_the_thing = true;
if do_the_thing {
let two_hearts = '💕';
println!("{0}{0}{0}", two_hearts);
}
let some_array = ["thing1", "thing2", "thing3"];
for element in some_array.into_iter() {
println!("some_array has element {}", element);
}
let a = [0, 1, 2, 3, 4];
let middle_of_a = &a[1..a.len()-1];
for i in middle_of_a {
println!("{}", i);
}
let i_got_tuples = (123, 456, "yay");
println!("{}", i_got_tuples.2);
for i in 0..10 {
if i % 2 == 0 { continue; }
println!("{}", i);
}
}
fn print_int(x: i32) {
println!("print_int is printing {}!", x);
}
fn sum(x: i32, y: i32) -> i32 {
x + y
}
|
### 下载 MM 演示
直接从应用程序下载最后一场比赛(官方竞技)的 Demo 。每次 CSGO 关闭时应用程序都会发送一条通知,邀请您下载最新的 Demo 。
### 分享链接
使用分享链接下载 Demo,将分享链接发送至第三方应用程序以分享您的 Demo 。
|
unless ENV['COVERAGE'].nil?
require "simplecov"
require "simplecov-gem-profile"
SimpleCov.start "gem"
end
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'rspec'
require 'clickmeetings'
require 'pry-byebug'
require 'webmock/rspec'
Dir[File.expand_path("../support/**/*.rb", __FILE__)].each { |f| require f }
Dir[File.expand_path("../helpers/**/*.rb", __FILE__)].each { |f| require f }
Dir[File.expand_path("../shared_examples/**/*.rb", __FILE__)].each { |f| require f }
RSpec.configure do |config|
config.mock_with :rspec
include ClickmeetingWebMock
include FixturesHelpers
config.example_status_persistence_file_path = File.expand_path("../../examples.txt", __FILE__)
end
|
package example
import org.komapper.annotation.KomapperAutoIncrement
import org.komapper.annotation.KomapperColumn
import org.komapper.annotation.KomapperCreatedAt
import org.komapper.annotation.KomapperEntityDef
import org.komapper.annotation.KomapperId
import org.komapper.annotation.KomapperUpdatedAt
import org.komapper.annotation.KomapperVersion
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.SchemaDsl
import org.komapper.core.dsl.query.first
import org.komapper.jdbc.JdbcDatabase
import org.komapper.tx.jdbc.withTransaction
import java.time.LocalDateTime
data class Address(
val id: Int = 0,
val street: String,
val version: Int = 0,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null,
)
@KomapperEntityDef(Address::class)
data class AddressDef(
@KomapperId @KomapperAutoIncrement @KomapperColumn(name = "ADDRESS_ID")
val id: Nothing,
@KomapperVersion val version: Nothing,
@KomapperCreatedAt val createdAt: Nothing,
@KomapperUpdatedAt val updatedAt: Nothing,
)
data class Employee(
val id: Int = 0,
val name: String,
val version: Int = 0,
val createdAt: LocalDateTime = LocalDateTime.MIN,
val updatedAt: LocalDateTime = LocalDateTime.MIN,
)
annotation class KomapperStub
@KomapperEntityDef(Employee::class)
@KomapperStub
data class EmployeeDef(
@KomapperId @KomapperAutoIncrement val id: Nothing,
@KomapperVersion val version: Nothing,
@KomapperCreatedAt val createdAt: Nothing,
@KomapperUpdatedAt val updatedAt: Nothing,
)
fun main() {
// create a Database instance
val db = JdbcDatabase.create("jdbc:h2:mem:example;DB_CLOSE_DELAY=-1")
// get a metamodel
val a = Meta.address
// execute simple CRUD operations as a transaction
db.withTransaction {
// create a schema
db.runQuery {
SchemaDsl.create(a)
}
// CREATE
val newAddress = db.runQuery {
QueryDsl.insert(a).single(Address(street = "street A"))
}
// READ: select by id
val address1 = db.runQuery {
QueryDsl.from(a).where { a.id eq newAddress.id }.first()
}
println("address1 = $address1")
// UPDATE
db.runQuery {
QueryDsl.update(a).single(address1.copy(street = "street B"))
}
// READ: select by street
val address2 = db.runQuery {
QueryDsl.from(a).where { a.street eq "street B" }.first()
}
println("address2 = $address2")
check(address1.id == address2.id)
check(address1.street != address2.street)
check(address1.version + 1 == address2.version)
// DELETE
db.runQuery {
QueryDsl.delete(a).single(address2)
}
// READ: select all
val addressList = db.runQuery {
QueryDsl.from(a).orderBy(a.id)
}
println("addressList = $addressList")
check(addressList.isEmpty()) { "The addressList must be empty." }
}
}
|
import { SfdxProject } from "@salesforce/core";
import { isNullOrUndefined } from "util";
import { UX } from "@salesforce/command";
const Logger = require("pino");
const NodeCache = require("node-cache");
export enum LoggerLevel {
TRACE = 10,
DEBUG = 20,
INFO = 30,
WARN = 40,
ERROR = 50,
FATAL = 60,
}
export class SFPowerkit {
private static defaultFolder: string;
private static projectDirectories: string[];
private static pluginConfig;
public static isJsonFormatEnabled: boolean;
private static ux: UX;
private static sourceApiVersion: any;
private static logger;
public static logLevel;
private static cache;
public static getCache() {
if (SFPowerkit.cache == null) {
SFPowerkit.cache = new NodeCache();
}
return SFPowerkit.cache;
}
public static setLogLevel(logLevel: string, isJsonFormatEnabled: boolean) {
logLevel = logLevel.toLowerCase();
this.isJsonFormatEnabled = isJsonFormatEnabled;
if (!isJsonFormatEnabled) {
SFPowerkit.logger = Logger({
name: "sfpowerkit",
level: logLevel,
prettyPrint: {
levelFirst: true, // --levelFirst
colorize: true,
translateTime: true,
ignore: "pid,hostname", // --ignore
},
});
} else {
//do nothing for now, need to put pino to move to file
}
switch (logLevel) {
case "trace":
SFPowerkit.logLevel = LoggerLevel.TRACE;
break;
case "debug":
SFPowerkit.logLevel = LoggerLevel.DEBUG;
break;
case "info":
SFPowerkit.logLevel = LoggerLevel.INFO;
break;
case "warn":
SFPowerkit.logLevel = LoggerLevel.WARN;
break;
case "error":
SFPowerkit.logLevel = LoggerLevel.ERROR;
break;
case "fatal":
SFPowerkit.logLevel = LoggerLevel.FATAL;
break;
}
}
public static setProjectDirectories(packagedirectories: string[]) {
SFPowerkit.projectDirectories = packagedirectories;
}
public static async getProjectDirectories() {
if (!SFPowerkit.projectDirectories) {
SFPowerkit.projectDirectories = [];
const dxProject = await SfdxProject.resolve();
const project = await dxProject.retrieveSfdxProjectJson();
let packages = (project.get("packageDirectories") as any[]) || [];
packages.forEach((element) => {
SFPowerkit.projectDirectories.push(element.path);
if (element.default) {
SFPowerkit.defaultFolder = element.path;
}
});
}
return SFPowerkit.projectDirectories;
}
public static async getDefaultFolder() {
if (!SFPowerkit.defaultFolder) {
await SFPowerkit.getProjectDirectories();
}
return SFPowerkit.defaultFolder;
}
public static setDefaultFolder(defaultFolder: string) {
SFPowerkit.defaultFolder = defaultFolder;
}
public static async getConfig() {
if (!SFPowerkit.pluginConfig) {
const dxProject = await SfdxProject.resolve();
const project = await dxProject.retrieveSfdxProjectJson();
let plugins = project.get("plugins") || {};
let sfpowerkitConfig = plugins["sfpowerkit"];
SFPowerkit.pluginConfig = sfpowerkitConfig || {};
}
return SFPowerkit.pluginConfig;
}
public static setapiversion(apiversion: any) {
SFPowerkit.sourceApiVersion = apiversion;
}
public static async getApiVersion(): Promise<any> {
if (!SFPowerkit.sourceApiVersion) {
const dxProject = await SfdxProject.resolve();
const project = await dxProject.retrieveSfdxProjectJson();
SFPowerkit.sourceApiVersion = project.get("sourceApiVersion");
}
return SFPowerkit.sourceApiVersion;
}
/**
* Print log only if the log level for this commamnd matches the log level for the message
* @param message Message to print
* @param messageLoglevel Log level for the message
*/
public static log(message: any, logLevel: LoggerLevel) {
if (isNullOrUndefined(this.logger)) return;
if (this.isJsonFormatEnabled) return;
switch (logLevel) {
case LoggerLevel.TRACE:
this.logger.trace(message);
break;
case LoggerLevel.DEBUG:
this.logger.debug(message);
break;
case LoggerLevel.INFO:
this.logger.info(message);
break;
case LoggerLevel.WARN:
this.logger.warn(message);
break;
case LoggerLevel.ERROR:
this.logger.error(message);
break;
case LoggerLevel.FATAL:
this.logger.fatal(message);
break;
}
}
public static setUx(ux: UX) {
this.ux = ux;
}
public static setStatus(status: string) {
this.ux.setSpinnerStatus(status);
}
}
|
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using Bogus;
namespace App;
[MemoryDiagnoser]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
[CategoriesColumn]
public class BookSerializeBenchmark
{
private List<Book> _books = new();
private readonly Newtonsoft.Json.JsonSerializerSettings _newtonOptions = SerializationOptions.Newtonsoft;
private readonly System.Text.Json.JsonSerializerOptions _systemOptions = SerializationOptions.SystemTextJson;
[GlobalSetup]
public void Setup()
{
Faker<Book> faker = new();
_books = faker.CustomInstantiator(f =>
new Book(
f.Name.FirstName(),
f.PickRandom<CoverType>(),
f.Random.Int()
)).Generate(1000);
}
[BenchmarkCategory("List"), Benchmark]
public string NewtonSoftSerializerList()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(_books, _newtonOptions);
}
[BenchmarkCategory("List"), Benchmark(Baseline = true)]
public string SystemTextJsonSerializerStringList()
{
return System.Text.Json.JsonSerializer.Serialize(_books, _systemOptions);
}
[BenchmarkCategory("List"), Benchmark]
public string GeneratedSerializerStringList()
{
return System.Text.Json.JsonSerializer.Serialize(_books, JsonContext.Default.ListBook);
}
[BenchmarkCategory("Single"), Benchmark]
public string NewtonSoftSerializer()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(_books[0], _newtonOptions);
}
[BenchmarkCategory("Single"), Benchmark(Baseline = true)]
public string SystemTextJsonSerializerString()
{
return System.Text.Json.JsonSerializer.Serialize(_books[0], _systemOptions);
}
[BenchmarkCategory("Single"), Benchmark]
public string GeneratedSerializerString()
{
return System.Text.Json.JsonSerializer.Serialize(_books[0], JsonContext.Default.Book);
}
}
|
# Release Checklist
## Documentation
- [ ] Quickstart verified working and up-to-date
- [ ] Tutorial verified working and up-to-date
- [ ] Fidesdemo verified working and up-to-date
- [ ] New/updated API endpoints described in the Guides
- [ ] New/updated API endpoints included in the Postman collections
- [ ] New tables/columns added to database diagram
|
rm ./out.tar
rm -rf ./perf/payloadFolder
mkdir ./perf/payloadFolder
rm -rf ./perf/output
mkdir ./perf/output
rm -rf ./perf/xmlSource
mkdir ./perf/xmlSource
rm -rf ./perf/jsonSource
mkdir ./perf/jsonSource
rm -rf ./perf/xmlGenerated
mkdir ./perf/xmlGenerated
rm -rf ./perf/jsonGenerated
mkdir ./perf/jsonGenerated
rm -rf ./generatePerfData/output
mkdir ./generatePerfData/output
|
%%%-------------------------------------------------------------------
%%% @author thomasguenzel
%%% @copyright (C) 2016, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 17. Jul 2016 22:14
%%%-------------------------------------------------------------------
-module(ms_ctx_infer).
-author("thomasguenzel").
%% API
-export([infer/1]).
infer(Parsed) ->
lists:map(fun traverse/1, Parsed).
infer_time(#{time_context := TimeContext} = Rec) when is_map(TimeContext)->
NewCtx = ms_ctx_time:extract(TimeContext),
Rec#{time_context => NewCtx};
infer_time(Rec) ->
Rec.
infer_ctx(Rec) ->
R1 = infer_time(Rec),
R2 = ms_ctx_weather:infer(R1),
R3 = ms_ctx_activity:infer_activity(R2),
R4 = ms_ctx_location:infer(R3),
R4.
traverse(#{type := touch_recording, gestures := Gestures} = Rec) ->
NewGestures = lists:map(fun traverse/1, Gestures),
NewRec = infer_ctx(Rec#{gestures => NewGestures}),
NewRec;
traverse(#{type := gesture} = Rec) ->
NewRec = infer_ctx(Rec),
NewRec;
traverse(#{type := segue} = Rec) ->
NewRec = infer_ctx(Rec),
NewRec;
traverse(#{type := action} = Rec) ->
NewRec = infer_ctx(Rec),
NewRec;
traverse(Rec) ->
Rec.
|
A* Package for Go
=================
[](https://travis-ci.org/samuel/go-astar)
This package is just a code example of implementing A* in Go. It's probably
not suitable for any real use.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.