content
stringlengths 10
4.9M
|
---|
10 years ago
Palin visited the crucial battleground state of Ohio Sunday.
ST. CLAIRSVILLE, Ohio (CNN) - At a campaign rally designed to reflect the pastoral beauty of the heartland in autumn - with a stage set up in a red barn overlooking a sweeping field and piles of pumpkins - Sarah Palin warned the audience about the threat of terrorism, and explained that the Republican ticket should be elected because “we know who the bad guys are.”
“Help me, Ohio, to help put John McCain in the White House,” she said. “He understands. He understands you. We understand how important it is that this team be elected. For one thing, we know who the bad guys are, OK?”
That statement elicited scattered shouts of “Obama!” throughout the crowd.
“We know that in the war, it’s terrorists, terrorists who hate America and her allies and would seek to destroy us, and the bad guys are those who would support and sympathize with the terrorists,” she said. “They do not like America because of what we stand for. Liberty. Freedom. Equal rights. Those who sympathize and support those terrorists who would seek to destroy all that it is that we value, those are the bad guys, OK?”
Was Palin suggesting that Barack Obama and Joe Biden don’t understand the terrorist threat? Who exactly were the “bad guys” Palin was referring to? A spokesperson for the campaign would only say that the governor was describing “nations that sympathize with terrorists, period.”
The vice presidential nominee pressed on and pointed the finger at more bad guys - the “greedy and corrupt and arrogant” mavens of Wall Street and Washington who, she said, have pushed the nation’s economy to the brink.
“We know who the good guys are, and it is you, and we will fight for you, and we will put government on your side,” she promised. “We will end the arrogant and the selfish practices of Washington and of Wall Street because your United States government is to be of the people, by the people, for the people.”
In her remarks, Palin also appeared to acknowledge the snow-balling narrative that Republican rallies have grown increasingly hostile and angry in the waning weeks of the campaign, echoing weekend remarks by McCain himself.
“All across America, I know that there’s a lot of anger right now,” she said. “There’s anger about the insider dealing of lobbyists and anger at the greed of Wall Street, and anger about the arrogance of the Washington elite. And with serious reforms to change Washington, John McCain is going to turn your anger into action.” |
import { RootState } from "~/types"
import { CampaignTypes, Campaign } from "~/types/campaigns"
import { GetterTree, MutationTree, ActionTree } from "vuex"
import indev_campaigns_data from "~/static/campaigns/indev.json"
export const state = (): RootState => ({
campaigns: new Map<CampaignTypes, Campaign>()
})
export const getters: GetterTree<RootState, RootState> = {
getCampaignsList(state: RootState): Array<Campaign> {
let flat_campaigns_list = []
for(var key in state.campaigns) {
flat_campaigns_list = flat_campaigns_list.concat(state.campaigns[key])
}
return flat_campaigns_list
}
}
export const mutations: MutationTree<RootState> = {
setCampaigns(state: RootState, campaigns_to_add: [ string, [] ]): void {
state.campaigns[campaigns_to_add[0]] = campaigns_to_add[1]
}
}
export const actions: ActionTree<RootState, RootState> = {
async nuxtServerInit({ commit }) {
let indev_campaigns: Campaign[] = []
indev_campaigns = indev_campaigns_data
commit("setCampaigns", [CampaignTypes.Indev, indev_campaigns]);
}
}
|
<filename>tests/test_detector.py
import pytest
import pandas as pd
import astropy.units as u
import numpy as np
import numpy.testing
from wayne import detector
class Test_WFC3_IR:
def test__init__(self):
detector.WFC3_IR()
def test_get_modes(self):
det = detector.WFC3_IR()
df, df2 = det._get_modes()
assert isinstance(df, pd.DataFrame)
assert df.shape == (360, 4)
assert isinstance(df2, pd.DataFrame)
assert df2.shape == (19, 3)
def test_get_exptime_works(self):
det = detector.WFC3_IR()
assert det.exptime(NSAMP=2, SAMPSEQ='RAPID', SUBARRAY=1024) == 2.932*u.s
assert det.exptime(NSAMP=16, SAMPSEQ='RAPID', SUBARRAY=64) == 0.912*u.s
assert det.exptime(NSAMP=8, SAMPSEQ='SPARS25', SUBARRAY=512).value - 161.302 < 0.001
def test_exptime_return_type(self):
# Testing that the return is a single quantity and not a single quantity in an array.
# this results in x += exptime + overhead failing with "ValueError: non-broadcastable output"
det = detector.WFC3_IR()
exp_time = det.exptime(NSAMP=2, SAMPSEQ='RAPID', SUBARRAY=1024)
x = 4. * u.s
x += exp_time + 6. * u.s # should run without ValueError
def test_getexptime_raises_WFC3SimSampleModeError_if_invalid_NSAMP(self):
det = detector.WFC3_IR()
with pytest.raises(detector.WFC3SimSampleModeError):
det.exptime(NSAMP=17, SAMPSEQ='RAPID', SUBARRAY=1024)
with pytest.raises(detector.WFC3SimSampleModeError):
det.exptime(NSAMP=0, SAMPSEQ='RAPID', SUBARRAY=1024)
def test_getexptime_raises_WFC3SimSampleModeError_if_invalid_SAMPSEQ(self):
det = detector.WFC3_IR()
with pytest.raises(detector.WFC3SimSampleModeError):
det.exptime(NSAMP=15, SAMPSEQ='WRONG', SUBARRAY=1024)
with pytest.raises(detector.WFC3SimSampleModeError):
# 128 where SPARS25 not permitted
det.exptime(NSAMP=15, SAMPSEQ='SPARS25', SUBARRAY=128)
def test_getexptime_raises_WFC3SimSampleModeError_if_invalid_SUBARRAY(self):
det = detector.WFC3_IR()
with pytest.raises(detector.WFC3SimSampleModeError):
det.exptime(NSAMP=15, SAMPSEQ='RAPID', SUBARRAY=1023)
with pytest.raises(detector.WFC3SimSampleModeError):
det.exptime(NSAMP=15, SAMPSEQ='RAPID', SUBARRAY=0)
def test_get_read_times_works(self):
det = detector.WFC3_IR()
exptimes = det.get_read_times(NSAMP=5, SAMPSEQ='RAPID', SUBARRAY=1024).to(u.s).value
answer = np.array([2.932, 5.865, 8.797, 11.729])
numpy.testing.assert_array_almost_equal(exptimes, answer, 3)
exptimes = det.get_read_times(NSAMP=3, SAMPSEQ='SPARS10', SUBARRAY=256).to(u.s).value
answer = np.array([0.278, 7.624])
numpy.testing.assert_array_almost_equal(exptimes, answer, 3)
def test_get_read_times_raises_WFC3SimSampleModeError_if_invalid_NSAMP(self):
det = detector.WFC3_IR()
with pytest.raises(detector.WFC3SimSampleModeError):
det.get_read_times(NSAMP=17, SAMPSEQ='RAPID', SUBARRAY=1024)
with pytest.raises(detector.WFC3SimSampleModeError):
det.get_read_times(NSAMP=0, SAMPSEQ='RAPID', SUBARRAY=1024)
def test_get_read_times_raises_WFC3SimSampleModeError_if_invalid_SAMPSEQ(self):
det = detector.WFC3_IR()
with pytest.raises(detector.WFC3SimSampleModeError):
det.get_read_times(NSAMP=15, SAMPSEQ='WRONG', SUBARRAY=1024)
with pytest.raises(detector.WFC3SimSampleModeError):
# 128 with SPARS25 not permitted
det.get_read_times(NSAMP=15, SAMPSEQ='SPARS25', SUBARRAY=128)
def test_get_read_times_raises_WFC3SimSampleModeError_if_invalid_SUBARRAY(self):
det = detector.WFC3_IR()
with pytest.raises(detector.WFC3SimSampleModeError):
det.get_read_times(NSAMP=15, SAMPSEQ='RAPID', SUBARRAY=1023)
with pytest.raises(detector.WFC3SimSampleModeError):
det.get_read_times(NSAMP=15, SAMPSEQ='RAPID', SUBARRAY=0) |
import os
import sys
import scipy as sp
import autograd.numpy as np
from autograd import grad, jacobian, elementwise_grad
from sklearn.cluster import KMeans
base_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..")
sys.path.append(base_dir)
from src.kernels.featuremaps.base import FeatureMap
from utils.prepare import get_kernel_by_name
class Nystrom(FeatureMap):
""" Nystrom feature map utilities
Inherits from the parent class FeatureMap
"""
def __init__(self, *args):
"""Initializes the class
Attributes:
hyperparams (dict): dictionnary parameters
name (str): name of the distribution
contextual_K (int): number of action anchor points
contextual_bandwidth (float): contextual bandwidth for kernel in nystrom
"""
super(Nystrom, self).__init__(*args)
self.name = 'nystrom'
self.contextual_K = self.hyperparams['nb_context_anchors']
self.contextual_bandwidth = self.hyperparams['contextual_bandwidth']
def contextual_feature_map_size(self, d):
""" Gets size of contextual feature_map
"""
return self.contextual_K
def set_contextual_anchor_points(self, features):
""" Set contextual anchor points with K-means for contextual nystrom
Args:
features (np.array): observation features
"""
kmeans = KMeans(n_clusters=self.contextual_K, random_state=self.hyperparams['random_seed']).fit(features)
self.anchor_points = kmeans.cluster_centers_
variances = []
labels = kmeans.labels_
for label in np.unique(labels):
mask = labels == label
variances.append(np.mean((features[mask] - self.anchor_points[labels][mask]) ** 2))
self.contextual_bandwidth *= np.sqrt(np.mean(variances))
self.contextual_kernel = get_kernel_by_name('gaussian')(self.contextual_bandwidth)
def contextual_feature_map(self, features):
""" Creates contextual feature map
Args:
features (np.array): observation features
"""
gram_matrix = self.contextual_kernel(self.anchor_points, self.anchor_points)
gram_pred = self.contextual_kernel(self.anchor_points, features)
return np.dot(np.linalg.inv(sp.linalg.sqrtm(gram_matrix)), gram_pred).T |
<reponame>new-kernel/novusk<filename>drivers/device/src/board.rs
pub struct Board {
pub name: &'static str,
pub peripheral_addr: usize,
pub early_printing_method: &'static str,
pub main_printing_method: &'static str,
pub arch_init: bool,
pub kernel_init: bool,
pub board_specific_kernel: Option<unsafe extern "C" fn()>,
}
impl Board {
pub const fn empty() -> Self {
return Board {
name: "Unknown",
peripheral_addr: 0x0,
early_printing_method: "Serial",
main_printing_method: "Serial",
arch_init: true,
kernel_init: true,
board_specific_kernel: None
}
}
pub fn set(&mut self, board: Board) {
self.name = board.name;
self.peripheral_addr = board.peripheral_addr;
self.early_printing_method = board.early_printing_method;
self.main_printing_method = board.main_printing_method;
self.arch_init = board.arch_init;
self.kernel_init = board.kernel_init;
self.board_specific_kernel = board.board_specific_kernel;
}
pub unsafe fn run_board_specific_kernel(&self) {
if self.board_specific_kernel.is_none() {
panic!("Can't find board specific kernel for {}", self.name);
} else {
self.board_specific_kernel.unwrap()();
}
}
}
|
/**
* @Author secoder
* @File ExcelReadTest
* @Time 2021-08-06 10:36
* @Description
*/
public class ExcelReadTest {
ExcelRead excelRead = new ExcelRead();
String excel_path = "src/main/java/excel_data/";
@Test
public void read2003Test(){
try {
excelRead.read2003(excel_path);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void read2007Test(){
try {
excelRead.read2007(excel_path);
} catch (IOException e) {
e.printStackTrace();
}
}
} |
As a reluctant spring eventually kicks out the last vestiges of winter, the number of asylum seekers entering Canada illegally from the United States will ramp up considerably.
Only a fool—or the Trudeau Liberals who thus far appear to lack any plan—would think otherwise.
Gone will be the emotive images of queue-jumping refugee claimants with legal status in the U.S.—Turks, Somalis, Syrians, Yemenis—trudging through the snow as they hand their bundled-up child into the waiting arms of the RCMP.
Soon it will be a summer walk in the park.
Canadians, however, are growing tired of being used by a loophole in the Canada-U.S. Safe Third Country Agreement where refugee claimants would be turned back if they crossed at legal border checkpoints, but somehow accepted if they cross into Canada illegally through a back door.
They are tired of being the patsies.
A new Ipsos poll Wednesday commissioned by Global News shows over 90% of Canadians believe the Liberals’ approach to dealing with asylum seekers is in dire need of changes.
As Ipsos CEO Darrell Bricker put it, “For Canadians it’s not either a discussion about compassion or a discussion about security, it’s a discussion about rules.
“Regardless of your views on immigration in general, there’s an overall perspective among Canadians that rules must make sense, and they must be followed.”
That view was unequivocal, with only eight percent of Canadians content with the status quo.
According to the RCMP, upwards of 1,200 asylum seekers crossed the Canadian border illegally in January and February, a number that will only spike as summer beckons.
In fact, as Toronto immigration lawyer Guidy Mamann recently told Macleans, Canadians can expect a more clandestine infiltration as the weather betters.
“We are going to see a steep increase in numbers,” he said. “What you are seeing now is only those people who want to be seen.
“There are other people who are going further down the fence who do not want to be detected, and they’re coming across with the intention of avoiding the system.”
Yet, one of the last times Canadians heard from Public Safety Minister Ralph Goodale, he was playing the hyperbole game rather than addressing legitimate concerns regarding these illegal entries into our country, insinuating that only the opposition Conservatives were making a big deal of the situation.
“I guess what the Conservatives are saying is maybe we should line up the RCMP at the border, link arms and shoo people away,” Goodale recently told CTV’s Question Period.
“Or maybe use fire hoses, or whatever, to keep people from crossing at the border.”
It was a ludicrous statement, of course, but not unexpected from a party increasingly out of touch with the average Canadian, as the results of this Ipsos poll clearly underlines.
While fire hoses never came up in the poll, Canadians are nonetheless seeking the regulatory equivalent from the Liberals who thus far see asylum seekers as nothing more than a minor nuisance.
“(When) we’re not talking about a couple of people coming across, but busloads coming across, that’s when it becomes problematic,” said Ipsos’ CEO Darren Bricker.
“Because that’s when it will look like the rules are unclear, to the extent that they exist and are being violated, and that the government is out of control.”
Right now, it is not front-page news, but it will be.
In fact, Bricker sees the influx on illegal asylum seekers evolving into “the number one issue facing the country.”
Maybe then Ralph Goodale will break out the fire hoses.
If only to wash away his party’s smug indifference.
[email protected] |
/**
* Disposes of any resources hold by this support.
*/
public void dispose() {
if(m_contentFrame != null) {
m_contentFrame.setVisible(false);
m_contentFrame.dispose();
m_contentFrame = null;
}
getRuntime().dispose();
m_runtime = null;
} |
/**
* This method is called when a periodic command has thrown a fatal exception as defined by the list in getFatalPeriodicExceptionClasses(). At the point when this method is called
* the periodic command has already stopped executing and will not execute again. This method is meant to allow the command to alert someone of the failure (such as by sending
* an email message)
* @param t
*/
public void handleFatalPeriodicException(Throwable t)
{
String subject = "Invalid HDIG service account credentials";
String message = "The ProcessAsyncStorageQueue periodic command has shut down due to invalid HDIG service account credentials.";
NotificationFacade.sendNotification(NotificationTypes.InvalidServiceAccountCredentials, subject, message);
} |
In what may be a precedent-setting decision, a California chapter of the Boy Scouts of America has approved a gay former member's Eagle Scout application, despite the national organization's ban on gay participants.
Ryan Andresen, 18, was a scout from the San Francisco area when he was denied his Eagle Scout award in October 2011, NBC News reports. Andresen had come out in July and had completed all the requirements for the Eagle honor, including helping spearhead the construction of a “Tolerance Wall” at a local middle school to raise awareness about bullying.
But Andresen's troop leader refused to grant him the award. Frustrated, his mother, Karen Andresen, launched a Change.org petition in support of her son.
The petition received overwhelming support from 463,151 signers. In addition, California Senator Barbara Boxer and Lieutenant Governor Gavin Newsom sent letters to the Scouts in support of Andresen.
Then, in December, local Boy Scout leaders approved an official Eagle Board of Review. Their decision in favor of Andresen was announced January 7.
The Eagle Board of Review decision overrides the initial refusal, issued by Troop 212's Scoutmaster, according to a Change.org press release emailed to The Huffington Post. National headquarters must still approve the Eagle award, however.
"It's the first in-your-face (challenge)," Bonnie Hazarabedian, chairwoman of the Boy Scout district review board that handled Andresen's application, told Reuters. "I don't think sexual orientation should enter into why a Scout is a Scout, or whether they are Eagle material... We felt without a doubt he deserved that rank."
Karen Andresen released the following statement through Change.org:
I’m just so incredibly happy for Ryan. He’s worked so hard for this honor, and as a mother, it means the world to me to know that our local Scouting community believes in him, too,” she said. “Regardless of what the BSA’s National Advancement Team decides to do with his application, this victory makes it all worth it, and gives me so much hope for the future of the organization.
GLAAD President Herndon Graddick welcomed the Review Board's decision in Andresen's case.
"Councils across the nation are rejecting the Boy Scouts' grossly discriminatory ban on gay scouts, echoing the support of fellow scouts, business leaders, and the American public,” Graddick said in a statement released by Change.org. “How long can the BSA go on ignoring its own members and its core values of fairness, leadership and integrity? The growing number of councils welcoming gay scouts and leaders reminds BSA autocrats: change will come with you, or without you."
The Boy Scouts' policy regarding gay scouts received national scrutiny last year with the elevation of several high-profile cases, in addition to Andresen's. One such case involved Ohio mother Jennifer Tyrrell, who was ousted as leader of her son's Tiger Cubs pack because she is a lesbian. Tyrell delivered over 300,000 signatures to the Boy Scouts in an effort to get the ban on gay leaders and scouts overturned. |
Two-thirds of likely voters say the weak economy is Washington’s fault, and more blame President Obama than anybody else, according to a new poll for The Hill.
It found that 66 percent believe paltry job growth and slow economic recovery is the result of bad policy. Thirty-four percent say Obama is the most to blame, followed by 23 percent who say Congress is the culprit. Twenty percent point the finger at Wall Street, and 18 percent cite former President George W. Bush.
ADVERTISEMENT
The results highlight the reelection challenge Obama faces amid dissatisfaction with his first-term performance on the economy.
The poll, conducted for The Hill by Pulse Opinion Research, found 53 percent of voters say Obama has taken the wrong actions and has slowed the economy down. Forty-two percent said he has taken the right actions to revive the economy, while six percent said they were not sure.
Obama has argued throughout the presidential campaign that his policies have made the economy better. He says recovery is taking a long time because he inherited such deep economic trouble upon taking office in 2009.
“The problems we’re facing right now have been more than a decade in the making,” he told an audience last month in Cleveland.
More from The Hill:
♦ Mormons on cusp of new powerful era in capital
♦ Rewards, risks as Romney heads overseas amid campaign
♦ Brown ad hits Warren on Obama's 'you didn't build that' remark
♦ GOP ex-lawmaker: Facts will ‘overwhelm’ Republican opposition to climate change
♦ Geithner set to defend actions on Libor scandal before Congress
♦ Make-or-break time for cybersecurity bill
♦ Challenges to Obama birth-control mandate piling up in court
♦ Pre-election deal to avert sequestration looks unlikely
Obama’s campaign, under the slogan “Forward,” has sought to steer voter attention less toward current and past economic performance and more toward questions about Republican Mitt Romney’s work in the private sector economy. It has launched attacks on the challenger’s role as head of the private equity firm Bain Capital, casting him as a jobs “outsourcer” whose firm shipped thousands of U.S. positions overseas.
The Hill Poll, however, shows the extent to which voters hold Obama responsible for the economy and reveals his vulnerability should the election become primarily a referendum on his economic management.
It finds that voters strongly believe more could have been done by the White House and in Congress to achieve growth in the economy and employment.
While 64 percent of voters consider this downturn to be “much more severe” than previous contractions, barely one quarter (26 percent) say the agonizingly slow pace of the recovery was unavoidable.
While voters feel Obama carries a greater portion of the blame than others, the poll found almost 6-in-10 are unhappy with the actions of Republicans in Congress who have challenged the president on an array of policy initiatives.
Fifty-seven percent of voters said congressional Republicans have impeded the recovery with their policies, and only 30 percent overall believe the GOP has done the right things to boost the economy.
The tension between a Republican-controlled House of Representatives and a Democratic-run White House has also featured in Obama’s campaign strategy.
In his economic speech last month in Cleveland, Obama cast the 2012 election as a chance to choose between two competing visions for the nation.
“What’s holding us back is a stalemate in Washington between two fundamentally different views of which direction America should take,” he said. “This election is your chance to break that stalemate.”
Romney agrees that the election is a choice between two radically different views of America, but he characterizes it as a contest between his own vision of an industrious people free to achieve their dreams and Obama’s faith in big government.
If there is a silver lining for Obama in the poll results, it’s that centrist voters, who may well decide the 2012 outcome, tend to blame Republicans in Congress more than the president for hindering a more robust recovery.
Twenty-six percent of centrists cited Congress as most to blame for U.S. economic woes, compared to 20 percent who blame Obama.
Similarly, 53 percent of centrists said Obama has taken the right actions as president to boost the economy, compared with 38 percent who said he had taken the wrong steps.
Seventy-nine percent of centrist voters said Republicans had slowed the economy by taking wrong actions. Only 13 percent of centrists credited GOP lawmakers with policies that have helped the economy.
The poll found sharp differences in opinions along racial lines, with 94 percent of African-Americans saying Obama had taken the right actions on the economy, compared to 34 percent of white voters.
The Hill poll was conducted July 19 among 1,000 likely voters, and has a 3 percentage point margin of error.
UPDATED: This story has been updated to show correct date the poll was conducted.
Click here to view data from The Hill Poll. |
/**
* Tests the resettable iterator with enough memory so that all data
* is kept locally in a membuffer.
*/
@Test
public void testResettableIteratorInMemory() {
try {
SpillingResettableIterator<IntValue> iterator = new SpillingResettableIterator<IntValue>(
this.reader, this.serializer, this.memman, this.ioman, 20, this.memOwner);
iterator.open();
int count = 0;
while (iterator.hasNext()) {
Assert.assertEquals("In initial run, element " + count + " does not match expected value!", count++,
iterator.next().getValue());
}
Assert.assertEquals("Too few elements were deserialzied in initial run!", NUM_TESTRECORDS, count);
for (int j = 0; j < 10; ++j) {
count = 0;
iterator.reset();
while (iterator.hasNext()) {
Assert.assertEquals("After reset nr. " + j + 1 + " element " + count
+ " does not match expected value!", count++, iterator.next().getValue());
}
Assert.assertEquals("Too few elements were deserialzied after reset nr. " + j + 1 + "!", NUM_TESTRECORDS,
count);
}
iterator.close();
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("Test encountered an exception.");
}
} |
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package client
import (
"context"
pb "github.com/casbin/casbin-server/proto"
)
// AddPolicy adds an authorization rule to the current policy.
// If the rule already exists, the function returns false and the rule will not be added.
// Otherwise the function returns true by adding the new rule.
func (e *Enforcer) AddPolicy(ctx context.Context, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.AddPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: "p",
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// AddNamedPolicy adds an authorization rule to the current named policy.
// If the rule already exists, the function returns false and the rule will not be added.
// Otherwise the function returns true by adding the new rule.
func (e *Enforcer) AddNamedPolicy(ctx context.Context, ptype string, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.AddNamedPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// RemovePolicy removes an authorization rule from the current policy.
func (e *Enforcer) RemovePolicy(ctx context.Context, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.RemovePolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: "p",
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// RemoveNamedPolicy removes an authorization rule from the current named policy.
func (e *Enforcer) RemoveNamedPolicy(ctx context.Context, ptype string, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.RemoveNamedPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// RemoveFilteredPolicy removes an authorization rule from the current policy, field filters can be specified.
func (e *Enforcer) RemoveFilteredPolicy(ctx context.Context, fieldIndex int32, fieldValues ...string) (bool, error) {
res, err := e.client.remoteClient.RemoveFilteredPolicy(ctx, &pb.FilteredPolicyRequest{
EnforcerHandler: e.handler,
PType: "p",
FieldIndex: fieldIndex,
FieldValues: fieldValues,
})
if err != nil {
return false, err
}
return res.Res, nil
}
// RemoveFilteredNamedPolicy removes an authorization rule from the current named policy, field filters can be specified.
func (e *Enforcer) RemoveFilteredNamedPolicy(ctx context.Context, ptype string, fieldIndex int32, fieldValues ...string) (bool, error) {
res, err := e.client.remoteClient.RemoveFilteredNamedPolicy(ctx, &pb.FilteredPolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
FieldIndex: fieldIndex,
FieldValues: fieldValues,
})
if err != nil {
return false, err
}
return res.Res, nil
}
// GetPolicy gets all the authorization rules in the policy.
func (e *Enforcer) GetPolicy(ctx context.Context) ([][]string, error) {
res, err := e.client.remoteClient.GetPolicy(ctx, &pb.EmptyRequest{Handler: e.handler})
if err != nil {
return nil, err
}
return replyTo2DSlice(res), nil
}
// GetNamedPolicy gets all the authorization rules in the named policy.
func (e *Enforcer) GetNamedPolicy(ctx context.Context, ptype string) ([][]string, error) {
res, err := e.client.remoteClient.GetNamedPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
})
if err != nil {
return nil, err
}
return replyTo2DSlice(res), nil
}
// GetFilteredPolicy gets all the authorization rules in the policy, field filters can be specified.
func (e *Enforcer) GetFilteredPolicy(ctx context.Context, fieldIndex int32, fieldValues ...string) ([][]string, error) {
res, err := e.client.remoteClient.GetFilteredPolicy(ctx, &pb.FilteredPolicyRequest{
EnforcerHandler: e.handler,
PType: "p",
FieldIndex: fieldIndex,
FieldValues: fieldValues,
})
if err != nil {
return nil, err
}
return replyTo2DSlice(res), nil
}
// GetFilteredNamedPolicy gets all the authorization rules in the named policy, field filters can be specified.
func (e *Enforcer) GetFilteredNamedPolicy(ctx context.Context, ptype string, fieldIndex int32, fieldValues ...string) ([][]string, error) {
res, err := e.client.remoteClient.GetFilteredNamedPolicy(ctx, &pb.FilteredPolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
FieldIndex: fieldIndex,
FieldValues: fieldValues,
})
if err != nil {
return nil, err
}
return replyTo2DSlice(res), nil
}
// AddGroupingPolicy adds a role inheritance rule to the current policy.
// If the rule already exists, the function returns false and the rule will not be added.
// Otherwise the function returns true by adding the new rule.
func (e *Enforcer) AddGroupingPolicy(ctx context.Context, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.AddGroupingPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: "g",
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// AddNamedGroupingPolicy adds a named role inheritance rule to the current policy.
// If the rule already exists, the function returns false and the rule will not be added.
// Otherwise the function returns true by adding the new rule.
func (e *Enforcer) AddNamedGroupingPolicy(ctx context.Context, ptype string, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.AddNamedGroupingPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// RemoveGroupingPolicy removes a role inheritance rule from the current policy.
func (e *Enforcer) RemoveGroupingPolicy(ctx context.Context, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.RemoveGroupingPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: "g",
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// RemoveNamedGroupingPolicy removes a role inheritance rule from the current named policy.
func (e *Enforcer) RemoveNamedGroupingPolicy(ctx context.Context, ptype string, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.RemoveNamedGroupingPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// RemoveFilteredGroupingPolicy removes a role inheritance rule from the current policy, field filters can be specified.
func (e *Enforcer) RemoveFilteredGroupingPolicy(ctx context.Context, fieldIndex int32, fieldValues ...string) (bool, error) {
res, err := e.client.remoteClient.RemoveFilteredGroupingPolicy(ctx, &pb.FilteredPolicyRequest{
EnforcerHandler: e.handler,
PType: "g",
FieldIndex: fieldIndex,
FieldValues: fieldValues,
})
if err != nil {
return false, err
}
return res.Res, nil
}
// RemoveFilteredNamedGroupingPolicy removes a role inheritance rule from the current named policy,
// field filters can be specified.
func (e *Enforcer) RemoveFilteredNamedGroupingPolicy(ctx context.Context, ptype string, fieldIndex int32, fieldValues ...string) (bool, error) {
res, err := e.client.remoteClient.RemoveFilteredNamedGroupingPolicy(ctx, &pb.FilteredPolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
FieldIndex: fieldIndex,
FieldValues: fieldValues,
})
if err != nil {
return false, err
}
return res.Res, nil
}
// GetGroupingPolicy gets all the role inheritance rules in the policy.
func (e *Enforcer) GetGroupingPolicy(ctx context.Context) ([][]string, error) {
res, err := e.client.remoteClient.GetGroupingPolicy(ctx, &pb.EmptyRequest{Handler: e.handler})
if err != nil {
return nil, err
}
return replyTo2DSlice(res), nil
}
// GetNamedGroupingPolicy gets all the role inheritance rules in the policy.
func (e *Enforcer) GetNamedGroupingPolicy(ctx context.Context, ptype string) ([][]string, error) {
res, err := e.client.remoteClient.GetNamedGroupingPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
})
if err != nil {
return nil, err
}
return replyTo2DSlice(res), nil
}
// GetFilteredGroupingPolicy gets all the role inheritance rules in the policy, field filters can be specified.
func (e *Enforcer) GetFilteredGroupingPolicy(ctx context.Context, fieldIndex int32, fieldValues ...string) ([][]string, error) {
res, err := e.client.remoteClient.GetFilteredGroupingPolicy(ctx, &pb.FilteredPolicyRequest{
EnforcerHandler: e.handler,
PType: "g",
FieldIndex: fieldIndex,
FieldValues: fieldValues,
})
if err != nil {
return nil, err
}
return replyTo2DSlice(res), nil
}
// GetFilteredNamedGroupingPolicy gets all the role inheritance rules in the policy, field filters can be specified.
func (e *Enforcer) GetFilteredNamedGroupingPolicy(ctx context.Context, ptype string, fieldIndex int32, fieldValues ...string) ([][]string, error) {
res, err := e.client.remoteClient.GetFilteredNamedGroupingPolicy(ctx, &pb.FilteredPolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
FieldIndex: fieldIndex,
FieldValues: fieldValues,
})
if err != nil {
return nil, err
}
return replyTo2DSlice(res), nil
}
// GetAllSubjects gets the list of subjects that show up in the current policy.
func (e *Enforcer) GetAllSubjects(ctx context.Context) ([]string, error) {
res, err := e.client.remoteClient.GetAllSubjects(ctx, &pb.EmptyRequest{Handler: e.handler})
if err != nil {
return nil, err
}
return res.Array, nil
}
// GetAllNamedSubjects gets the list of subjects that show up in the current named policy.
func (e *Enforcer) GetAllNamedSubjects(ctx context.Context, ptype string) ([]string, error) {
res, err := e.client.remoteClient.GetAllNamedSubjects(ctx, &pb.SimpleGetRequest{
EnforcerHandler: e.handler,
PType: ptype,
})
if err != nil {
return nil, err
}
return res.Array, nil
}
// GetAllObjects gets the list of objects that show up in the current policy.
func (e *Enforcer) GetAllObjects(ctx context.Context) ([]string, error) {
res, err := e.client.remoteClient.GetAllObjects(ctx, &pb.EmptyRequest{Handler: e.handler})
if err != nil {
return nil, err
}
return res.Array, nil
}
// GetAllNamedObjects gets the list of objects that show up in the current named policy.
func (e *Enforcer) GetAllNamedObjects(ctx context.Context, ptype string) ([]string, error) {
res, err := e.client.remoteClient.GetAllNamedObjects(ctx, &pb.SimpleGetRequest{
EnforcerHandler: e.handler,
PType: ptype,
})
if err != nil {
return nil, err
}
return res.Array, nil
}
// GetAllActions gets the list of actions that show up in the current policy.
func (e *Enforcer) GetAllActions(ctx context.Context) ([]string, error) {
res, err := e.client.remoteClient.GetAllActions(ctx, &pb.EmptyRequest{Handler: e.handler})
if err != nil {
return nil, err
}
return res.Array, nil
}
// GetAllNamedActions gets the list of actions that show up in the current named policy.
func (e *Enforcer) GetAllNamedActions(ctx context.Context, ptype string) ([]string, error) {
res, err := e.client.remoteClient.GetAllNamedActions(ctx, &pb.SimpleGetRequest{
EnforcerHandler: e.handler,
PType: ptype,
})
if err != nil {
return nil, err
}
return res.Array, nil
}
// GetAllRoles gets the list of roles that show up in the current policy.
func (e *Enforcer) GetAllRoles(ctx context.Context) ([]string, error) {
res, err := e.client.remoteClient.GetAllRoles(ctx, &pb.EmptyRequest{Handler: e.handler})
if err != nil {
return nil, err
}
return res.Array, nil
}
// GetAllNamedRoles gets the list of roles that show up in the current named policy.
func (e *Enforcer) GetAllNamedRoles(ctx context.Context, ptype string) ([]string, error) {
res, err := e.client.remoteClient.GetAllNamedRoles(ctx, &pb.SimpleGetRequest{
EnforcerHandler: e.handler,
PType: ptype,
})
if err != nil {
return nil, err
}
return res.Array, nil
}
// HasPolicy determines whether an authorization rule exists.
func (e *Enforcer) HasPolicy(ctx context.Context, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.HasPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: "p",
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// HasNamedPolicy determines whether a named authorization rule exists.
func (e *Enforcer) HasNamedPolicy(ctx context.Context, ptype string, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.HasNamedPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// HasGroupingPolicy determines whether a role inheritance rule exists.
func (e *Enforcer) HasGroupingPolicy(ctx context.Context, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.HasGroupingPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: "g",
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// HasNamedGroupingPolicy determines whether a named role inheritance rule exists.
func (e *Enforcer) HasNamedGroupingPolicy(ctx context.Context, ptype string, params ...interface{}) (bool, error) {
res, err := e.client.remoteClient.HasNamedGroupingPolicy(ctx, &pb.PolicyRequest{
EnforcerHandler: e.handler,
PType: ptype,
Params: paramsToStrSlice(params),
})
if err != nil {
return false, err
}
return res.Res, nil
}
// paramsToStrSlice transforms params, which can either be one string slice or several seperate
// strings, into a slice of strings.
func paramsToStrSlice(params []interface{}) []string {
if slice, ok := params[0].([]string); len(params) == 1 && ok {
return slice
}
slice := make([]string, 0)
for _, param := range params {
slice = append(slice, param.(string))
}
return slice
}
// replyTo2DSlice transforms a Array2DReply to a 2d string slice.
func replyTo2DSlice(reply *pb.Array2DReply) [][]string {
result := make([][]string, 0)
for _, value := range reply.D2 {
result = append(result, value.D1)
}
return result
}
|
The Jakarta Post, 9 February 2010
By declaring 2010 to be the International Year of Biodiversity, the United Nations has demonstrated its strong commitment to saving threatened biodiversity around the world. The fact that the most diverse ecosystem on Earth is the tropics should make us those who live in tropical countries more aware about threats to biodiversity.
Tropical forests contribute to large portions of nature’s rich diversity, just as coral reefs are a major component of marine biodiversity. The massive destruction of these species’ rich ecosystems will lead to a global species extinction crisis. The question is then could we really save our biodiversity? I am pessimistic.
An ecosystem is an integrated living system. The loss of one species does not only mean that we just lose that species, but also means it is a decline for the ecosystem. Since humans are part of nature’s system, the loss will also affect human survival. The lost biodiversity may have medical importance or act as a biological control.
Habitat degradation is the major driver of extinctions of many tropical species. In many tropical countries, including Indonesia, deforestation is the major form of habitat loss. It is predicted that about 2 million hectares of Indonesian forest have vanished every year. As a consequence, thousands of plants and animals have disappeared. Some probably have not been identified yet.
It has been long recognized that the main factor of deforestation human population pressures. Brown and Pearce (1994), for example, in their book The Causes of Tropical Deforestation noted that deforestation rates are strongly linked to population growth. High population density means smaller areas of remaining forest in the tropics. The problem is not only high growth rates, but also badly distributed inhabitants.
Human population growth indeed affects biodiversity. However, over-exploitation of natural resources speeds up the disaster. Mining activities, timber extractions and land clearing for other purposes are main examples of direct impact of human economic activities. Unfortunately, this condition is not only due to the economic needs of local people, but it is much more related to the greed of industrialization. In fact, mining activities, for example, do not contribute significantly to local economies. They usually just cause environmental problems for the locals.
As the magnitude of human influence continues to grow, most tropical forests are predicted to become secondary forests (see 2006 article by Wright and Muller-Landau in Biotropica, “The Future of Tropical Forest Species”). Secondary forests are forests regenerating after clearing; hence, the species composition is not the original ones. Primary forests in the tropics, which contain original compositions of plants and animals, are projected to be more restricted to low population density areas, relatively low value agricultural lands and protected areas. Consequently, we are going to lose more and more biodiversity.
The increase in human density may not be avoided. However, more controlled population growth as well as managing its distribution is needed in order to save our ecosystems and biodiversity. Ecosystem degradation means more than just a biodiversity loss, but again this will directly affect human survival on Earth. We need to make extraordinary efforts to save nature’s rich diversity.
Biodiversity plays an important role in human life. It is the source of food and medicine. Nature’s diversity also has intrinsic values that provide services for our souls. Natural relaxation sometimes could provide us with unlimited energy. This is known as natural healing. Therefore, there should be strong connections between people and nature. Biodiversity is our life. The failure to acknowledge the important of nature biodiversity, or destroying them, is a failure to appreciate life itself.
However, more conservation areas do not always mean more protected species. There is still illegal hunting and trading of protected species. We need law enforcement for this. Besides, it is the time to educate people in order to appreciate biodiversity. We could start at schools. Children and teenagers should be taught that biodiversity is important part of life.
I sometimes wonder why we, as Indonesians, lack appreciation for other creatures. My own experience living in one city in Australia shows me how interesting it is to live together with wild animals. Birds play in our yards and on the parks. We just need to sit outside our home to hear them sing and to watch them play. There are more than dozens of species on our yards. When the turtle-breeding season comes, we play on the beach, while watching small turtles make their way to the sea. School kids come and watch and make sure that no predators catch the little turtles. These are activities that I never experienced even in my village on the Bukit Barisan Range, Sumatra.
Therefore, educating people about the importance of biodiversity is a very important step to saving our remaining biodiversity. It has to be taught since early years. We need to keep campaigning about this to the public.
Another important step has to be taken is to decrease the pressure to forest ecosystems. Wright and Muller-Landau (2006) offered policy by improving economic opportunity in urban centers, as well as creating more urban centers. This has to be followed by the quality of urban life throughout the tropics. If people move to urban centers and have more economic opportunities, the pressures to forest ecosystem may decrease. They also emphasized that policies which is designed to keep people living around forests have rarely preserved the areas. Of course this policy needs better regional planning.
Extra ordinary efforts are needed in order to save our environments and biodiversity. This is for our own future benefits. If we fail to do actions, we do not have any reason to be optimistic that we could save our biodiversity.
The writer is an ecologist at University of Bengkulu and an Australian Leadership Awards Fellow.
Advertisements |
def extract_events(filehandle):
reader = csv.reader(filehandle)
message_fields = {}
for row in reader:
if len(row) < 2:
continue
channel, message_type = row[:2]
if not channel:
message_fields[message_type] = row[2:]
elif message_type in message_fields:
fieldnames = message_fields[message_type]
fieldname_prefix = channel + "." + message_type + "."
event = {fieldname_prefix + fieldnames[i]: value
for (i, value) in enumerate(row[2:])}
timestamp_idx = fieldnames.index("timestamp")
try:
event["timestamp"] = row[timestamp_idx + 2]
yield event
except IndexError:
pass
else:
pass |
def imfil(fun, x0, *args, **options):
budget, bounds, options = _split_options(options)
result, history = skqopt.minimize(fun, x0, bounds=bounds, budget=budget, \
method='imfil', options=options)
return _res2scipy(result, history) |
<reponame>jce-caba/gtkQRmm
#ifndef GTKQR_HPP
#define GTKQR_HPP
#include <gtkmm.h>
#include "QrDefinitions.hpp"
#include "QrUtils.hpp"
namespace GtkQR
{
class PrivateClass;
/** \brief QR widget
*/
class QR : public Gtk::Widget
{
public:
/** \brief Creates a new empty widget GtkQR without any image
*/
QR();
/** \brief copy constructor
*
*/
QR(const QR &);
/** \brief move constructor
*
*/
QR(QR &&);
/** \brief Creates a new widget GtkQR with text
* \param text : text you want to encode
*/
QR(const char *text);
/** \brief Creates a new widget GtkQR with text and error correction level
* \param text : text you want to encode
* \param error_level_correction : #QRErrorCorrectionLevel for qr image
*/
QR(const char *text,QRErrorCorrectionLevel error_level_correction);
/** \brief destructor
*
*/
~QR();
/** \brief assignment operator
*
*/
QR& operator=(const QR &);
/** \brief move assignment operator
*
*/
QR& operator=(QR &&);
/** \brief set text of the widget and regenerates it
* \param text : text you want to encode
*/
void set_text(Glib::ustring &text);
/** \brief set text of the widget and regenerates it
* \param text : text you want to encode
*/
void set_text(const char *text);
/** \brief set text and error correction level of the widget and regenerates it
*
* \param text :text you want to encode
* \param error_level_correction : #QRErrorCorrectionLevel for qr image
*/
void set_text_and_correction(Glib::ustring &text,QRErrorCorrectionLevel error_level_correction);
/** \brief set text and error correction level of the widget and regenerates it
*
* \param text :text you want to encode
* \param error_level_correction : #QRErrorCorrectionLevel for qr image
*/
void set_text_and_correction(const char *text,QRErrorCorrectionLevel error_level_correction);
/** \brief the micro QR ,default:false
* \param set_micro :true to use Micro QR, false to use QR
*
*/
void set_micro(bool set_micro);
/** \brief Allows the encoding of characters in UTF8 ,default:true
* \param set_UTF8 :true to allow UTF8, false otherwise
* \details In <a href="https://en.wikipedia.org/wiki/Extended_Channel_Interpretation">Extended Channel Interpretation</a> allows the encoding of characters in <a href="https://en.wikipedia.org/wiki/UTF-8">UTF8</a> when using characters not included in <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-1">ISO/IEC 8859-1</a>,
* if you disable this option then it will use the following encoding :
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-2">ISO/IEC 8859-2</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-3">ISO/IEC 8859-3</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-4">ISO/IEC 8859-4</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-5">ISO/IEC 8859-5</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-6">ISO/IEC 8859-6</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-7">ISO/IEC 8859-7</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-8">ISO/IEC 8859-8</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-9">ISO/IEC 8859-9</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-10">ISO/IEC 8859-10</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-11">ISO/IEC 8859-11</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-13">ISO/IEC 8859-13</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-14">ISO/IEC 8859-14</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-15">ISO/IEC 8859-15</a>,
* <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-16">ISO/IEC 8859-16</a> or
* <a href="https://en.wikipedia.org/wiki/Shift_JIS"> JIS X 0201</a>
* \n.With UTF8 you will have all the characters but occupying more space for the encoding, in case of using ISO/IEC 8859-2 to JIS X 0201 the encoding uses less space but not all the characters are possible
*/
void set_UTF8(bool set_UTF8);
/** \brief Save text in GtkQR ,default:true
*
* \param set_save_text :true to save text, false otherwise
* \details Not saving the text in memory we save memory but it has the disadvantage that when using the
* \ref set_dynamic_margin(bool set_dynamic) "set_dynamic_margin" ,
* \ref set_extra_margin(unsigned short size_margin) "set_extra_margin" ,
* \ref set_micro(bool set_micro) "set_micro" or
* \ref set_UTF8(bool set_UTF8) "set_UTF8" or
* change color functions you have to re-enter the text to regenerate the image
*
*/
void set_save_text(bool set_save_text);
/** \brief sets whether the margin is always the same ,default:true
* \param set_dynamic: false is is always the same , true otherwise
* \details The QR standard establishes that at least 4 image margin modules are necessary
* ,but the number of modules varies from 21x21 in version 1 to 170x170 in version 40 .if the parameter is set to false the margin is calculated in the worst case 21x 21 ,
* if it is set to true the margin will depend on the number of modules or qr version
*
*/
void set_dynamic_margin(bool set_dynamic);
#if (GTKMM_MAJOR_VERSION >= 3 )
/** \brief change the background color
*
* \param color :
*
*/
void set_background_color(Gdk::RGBA color);
/** \brief change the foreground color
*
* \param color :
*
*/
void set_foreground_color(Gdk::RGBA color);
#else
/** \brief change the background color
*
* \param color :
*
*/
void set_background_color(Gdk::Color color);
/** \brief change the foreground color
*
* \param color :
*
*/
void set_foreground_color(Gdk::Color color);
#endif
/** \brief regenerate qr image
* \details Some functions like
* \ref set_dynamic_margin(bool set_dynamic) "set_dynamic_margin" ,
* \ref set_extra_margin(unsigned short size_margin) "set_extra_margin" ,
* \ref set_micro(bool set_micro) "set_micro" or
* \ref set_UTF8(bool set_UTF8) "set_UTF8",
* don't regenerate the image they only change options , if you use the above functions before
* \ref set_text(Glib::ustring &text) "set_text" ,
* \ref set_text(const char *text) "set_text",
* \ref set_text_and_correction(Glib::ustring &text,QRErrorCorrectionLevel error_level_correction) "set_text_and_correction" or
* \ref set_text_and_correction(const char *text,QRErrorCorrectionLevel error_level_correction) "set_text_and_correction"
* no need to regenerate the image
*/
void regenerate();
/** \brief Save the qr image to png
*
* \param filename : file name to save image
* \param _size : size of image
*/
void save_png_image(const Glib::ustring &filename,int _size);
/** \brief Get version enum for qr image
*
* \return #QRVersion
*
*/
QRVersion get_version();
/** \brief Get version number of the widget GtkQR according to the encrypted text
*
* \return version number
* \details Version number are 1 to 40 for QR and #QR_VERSION_NUMBER_M1 , #QR_VERSION_NUMBER_M2 ,
* #QR_VERSION_NUMBER_M3 and #QR_VERSION_NUMBER_M4 for micro QR
* .If QR can't render the image return #QR_NO_VERSION
*/
short get_version_number();
/** \brief Get mask pattern for qr image
*
* \return number 0 to 7
*
*/
unsigned short get_mask();
/** \brief Get type of data for qr image
*
* \return #QRData
*
*/
QRData get_data_coding();
/** \brief Get text of the widget
*
* \return text of widget GtkQR ,
* if you disable save text with function
* \ref set_save_text(bool set_save_text) "set_save_text"
* text of widget is empty
*/
std::string & get_text();
/** \brief extra space added to the margins ,default:0
* \param size_margin: extra margin to add
*
*/
void set_extra_margin(unsigned short size_margin);
/** \brief Get number character encoding
* \return number of character encoding
* \details Obtains the character encoding number, if the encodings
* that are default (NUMERIC,ALPHANUMERIC,ISO/IEC 8859-1 or KANJI) returns 0.
* Returning a number >=1 indicates that the <a href="https://en.wikipedia.org/wiki/Extended_Channel_Interpretation">Extended Channel Interpretation</a> is used
*/
int get_number_character_encoding();
/** \brief Get character encoding used in the QR
*
* \param position :position of character enconding ,starts with 0
* \return character encoding
* \details Get character encoding used in the QR starting position 0 to
* \ref get_number_character_encoding() "get_number_character_encoding" -1
* , if number of character_encoding is 0 always return QR_ECI_MODE_ISO_8859_1
*
*/
QREciMode get_character_encoding(int position);
/** \brief Get the character matrix representing the QR
* \return character matrix
* \details A QR image is made up of a series of rectangles called modules,
* each value of the matrix is a coordinate (X,Y) that represents the different modules, being value '1'
* for foreground color and '0' for background color.
* \see \ref QrMatrix::GetQrMatrix(std::string &text,QRDataContainer *data) "GetQrMatrix"
* \note the (0,0) coordinate is at the top left .
*/
QrMatrix get_qrmatrix();
protected:
#if (GTKMM_MAJOR_VERSION >= 3 )
/// @private
bool on_draw(const Cairo::RefPtr<Cairo::Context>& cr) override;
#else
/// @private
bool on_expose_event(GdkEventExpose* event) override;
#endif
/// @private
void on_realize() override;
private:
PrivateClass *privateclass;
void copyqr(const QR &);
void clear_variables();
void set_matrix();
void draworder();
Glib::RefPtr<Gdk::Window> m_refGdkWindow;
};
}
#endif // GTKQR++_HPP
|
def update_object(self, name: str) -> None:
try:
self.manager.update_object(name)
except TNSError as error:
log.error(str(error)) |
The following blog post, unless otherwise noted, was written by a member of Gamasutras community.
The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company.
These days quite a few games boast about their difficulty in their product descriptions. Subset Games for example promotes their indie hit FTL with the "constant threat of defeat". Cellar Door Games let us know that their platformer Rogue Legacy is "HARD" in mighty capital letters. Obviously Dark Souls became well-known for being "extremely deep, dark and difficult". And The Impossible Game carries its message right in its title. All these at first probably rather daunting statements have actually become suitable for promotional purposes. This development is not only based on the elitism of the so-called "hardcore" gaming crowd out there, but also indicative of a deficiency in today's gaming landscape that is severely missing a specific element that used to be core to the medium: challenging gameplay.
Gameplay Games
The following article is primarily concerned with games which, in trying to deliver value to their audience, rely on interactivity first and foremost. At the other end of the spectrum there are for example the so-called "Walking Simulators", such as Firewatch or Gone Home. These titles focus on the artistic arrangement of their elements and telling deeply meaningful stories. Their lack of challenging gameplay is based upon their very nature and thus cannot be held against them. The same is true for extremely story-heavy titles such as Heavy Rain or The Walking Dead.
The article is not concerned with this kind of "gameplay".
However, the bulk of the industry and especially modern AAA titles typically rely on game mechanics. Of course one can, without further ado, accuse Call of Duty or Assassin's Creed of focusing way too much on audiovisual spectacle without much gameplay depth, and rightfully so. But without their interactive component, these titles would not generate much interest at all. After all, Hollywood still outclasses games in terms of explosive shootouts and elegant murder orgies.
Asset Tourism
While in past days it was perfectly normal for games to challenge the player through the interaction with the gameplay system itself, and thus generate long-term motivation, this concept is not a given anymore these days. Typically most of the "big" games come down to being, more (God of War) or less (Shadow of Mordor) preplanned, round tours through all the content. And once all the tourist attractions were presented to the player, the game is "beaten". Of course many players do not even come close to that point, for example due to the hype quickly dying down when actually playing and also games often being heavily diluted just to stretch their content over more hours.
On rails through the content museum.
Those on the other hand who manage to get to the end, will often find pseudo replay value in the form of a "New Game Plus" mode. Typically the idea hiding behind this euphemism is performing the whole asset tour again, just to experience a few bonus pieces of content here and there. In almost all cases this is of course a horribly inefficient endeavor. And if the additional mode adds actual value to the game, this raises the question of why it was not integrated in the base game to begin with, and therefore will never be experienced by most of the players.
Why Challenge?
In contrast to that, true replay value in games lies in the iterative learning process every player traverses when mastering the gameplay mechanics. As long as there is depth to discover, interacting with the game stays interesting. To foster this learning process, the player has to be challenged depending on his current level of skill. Mostly automatic "Press X to win!" gameplay obviously does not encourage the player to further develop his skill and understanding of the system. It also does not help to present the game events in spectacular ways. What matters is what the player actually does and whether he has to think about his actions, and not just trigger their execution like pressing the play button of a DVD player.
Press X to slaughter hordes of enemies!
The same is true on the level of thematic meaning. A story can emphasize the importance of an event, a decision, or a character in all kinds of ways. However, if this element of the game does not matter just as much gameplay-wise, then it is completely irrelevant. The best example of this problem is probably the seemingly important but in the end completely trivial decision of whether to exploit the Little Sisters in Bioshock or not. Challenging interaction on the other hand, confronting the player with problems that are genuinely difficult to solve, is how games communicate to players that their participation is meaningful. Of course challenge alone does not guarantee a good gameplay experience. It still has to be integrated into the game in an enjoyable way and dodge many game design pitfalls.
The Problems of Linearity
However, the aforementioned content tours as well as narrative games often lack any challenge to begin with, and on top of that actively work against it. For a story to unfold its intended impact as the author had planned it, it has to progress steadily, ideally with a carefully chosen pacing. The same is true for an experience based upon traversing content piece after content piece. In both cases, progress and even closure has to be guaranteed. A game that is interesting and challenging in the ways described above on the other hand cannot do that. Otherwise it commits itself to triviality and irrelevance from the very start.
The solution to the "story vs game" problem: Eliminate one of the two.
That is the reason why many strongly cinematic games, that primarily generate value by telling a story, have recently started replacing their gameplay by merely letting the player choose which movie snippet should be played next. Effectively they have eliminated any gameplay and thus the above-mentioned conflict. And in the few cases when they try to clumsily introduce some actual gameplay back into the experience, they risk the consistency of their storytelling. A prominent example of this phenomenon is Telltale's The Walking Dead that regularly forces classic adventure tasks upon the player, even though they do not make a whole lot of sense in the context of the story and some characters even have to actively play dumb.
Gameplay First
Of course there are still many games that focus on providing interesting gameplay, wherein the abstract properties of the ruleset are placed at the very core of the experience. This includes multiplayer titles such as Counter-Strike, Starcraft or League of Legends, as well as match-based single-player games like Civilization or most roguelikes. While confronting the player with an appropriate opponent to support the feeling of flow is a well-established concept in competitive gaming though, this idea is far less common in the area of single-player games. A notable exception is Auro's pioneering solitaire Elo system.
There are too few games that take the player seriously as a thinking being.
Other examples of the "gameplay first" philosophy include sophisticated puzzle games, that thoroughly explore a single innovative core mechanism in all its emergent properties. Prime examples are Portal with its "portal gun" or Jonathan Blow's The Witness. The latter openly parades its respect for the player's time and intelligence on its Steam page. The fact that this is not a base standard but treated as a "unique feature" says a lot about the modern day gaming landscape, and relentlessly reveals its horrendous condition.
Art or Obstacle Course?
There are various reasons for the lack of challenging and sophisticated gameplay systems in today's gaming market. The craft of game design in its professional form is still a very young field, so the orientation towards the at first sight seemingly related and already way more mature medium of movies is understandable. On top of that, gameplay depth is usually not easily recognizable on the surface, especially compared to audiovisually impressive scenes or a passively consumable story. Challenging gameplay always means effort for the players and thus a potentially smaller audience. However, those "rough edges" are exactly what makes games special and potentially artistically relevant. If the medium wants to progress as an art form, shallow indulgence has to make way for the inconvenient misfits way more often.
Is it art? Just an obstacle course? Or even both?
Of course all the attitudes that follow directly from the horrendous condition of the medium are worthy of condemnation as well. One example is Phil Owen's book "WTF Is Wrong With Video Games?", and the excerpt Polygon published a while ago. In his opinion gameplay, for example in The Last of Us, is necessarily meaningless and nothing but a nuisance. Who should need a trivial "obstacle course" when the "art stuff" obviously lies in the visuals and the storytelling? Given the mechanical shallowness of most modern games, such an attitude is understandable, but still harmful. In the end, games do not function like other media at all. Gameplay is inherently abstract. It does not make concrete points about love or friendship. It does not have to paint a dystopian future to be relevant compared to other forms of art. The meaningfulness and beauty of games lies in allowing the player to take a peek at the inner workings of his mind. Games enable us to witness processes of thought, creativity and learning in the most complex part of the human organism. Meaningless? Unlikely. |
Boromir is a fictional character in J. R. R. Tolkien's legendarium. He appears in the first two volumes of The Lord of the Rings (The Fellowship of the Ring and The Two Towers), and is mentioned in the last volume, The Return of the King. He was the heir of Denethor II (the 26th Ruling Steward of Gondor) and the elder brother of Faramir. In the course of the story Boromir joined the Fellowship of the Ring.
Boromir is portrayed as a noble character who believed passionately in the greatness of his kingdom and fought indomitably for it. His great stamina and physical strength, together with a forceful and commanding personality, made him a widely admired commander in Gondor's army and the favorite of his father Denethor. As a member of the Fellowship, his desperation to save his country ultimately drove him to betray his companions and attempt to seize the Ring, but he was redeemed by his repentance and brave last stand.
Literature [ edit ]
Boromir, was born in the year 2978 of the Third Age to Denethor II and Finduilas, daughter of Adrahil of Dol Amroth. His younger brother Faramir was born in T.A. 2983. The following year, Denethor became Steward of Gondor, succeeding his father, Ecthelion II, and Boromir simultaneously became heir apparent, inheriting the Horn of Gondor.
Boromir was named after the son of Denethor I, who was Steward around 500 years before the War of the Ring. The first Boromir was known as a great captain who cleared Ithilien of orcs of Mordor and was feared even by the Witch-king himself, setting high expectations for his namesake.
When Boromir's mother Finduilas died in T.A. 2988, he was aged only 10. Denethor became sombre, cold and detached from his family, which drove the brothers Faramir and Boromir to confide and depend on each other. Denethor always favoured Boromir over Faramir—Denethor loved Boromir "too much, perhaps; the more so because they were unlike"[1]—but this caused no rivalry between the brothers. Boromir, more fearless and daring, always protected and helped Faramir.
Boromir was made Captain of the White Tower, and quickly became Captain-General, also bearing the title High Warden of the White Tower. He led many successful forays against Sauron's forces, bringing him great esteem in the eyes of his father.
In response to prophetic dreams that came to Faramir and later to himself, Boromir claimed the quest of riding to Rivendell from Minas Tirith in T.A. 3018. His journey lasted a hundred and eleven days, and he travelled through "roads forgotten" to reach Rivendell, though, as he said, "few knew where it lay".[2] Boromir lost his horse halfway along, while crossing the Greyflood at the ruined city of Tharbad where the bridge was broken. He had to travel the remaining way on foot[3] and barely arrived in time for the Council of Elrond. (Tolkien wrote of Boromir's journey that "the courage and hardihood required is not fully recognized in the narrative".)[4]
The Fellowship of the Ring [ edit ]
Boromir first appears in The Lord of the Rings arriving at Rivendell just as the Council of Elrond was commencing. There he told of Gondor's attempts to keep the power of Mordor at bay.[5] He attempted to persuade the Council to let him take the One Ring to defend Gondor, but he was told that it would corrupt and destroy its user, and alert Sauron to its presence. He accepted this for the moment. He agreed to accompany Aragorn to Minas Tirith, and their path lay with the Fellowship for the first of the journey, so he pledged as part of the Fellowship of the Ring to protect the Ring-bearer, Frodo.
Boromir accompanied Frodo south from Rivendell with the Fellowship. Before departing, he sounded the Horn of Gondor, saying he "would not go forth like a thief into the night". On the journey south, Boromir frequently questioned the wisdom of their leader, the Wizard Gandalf. Boromir did, however, prove himself a valuable companion on the Fellowship's attempt to pass over the Misty Mountains: he advised that firewood be collected before the attempt to climb Caradhras, and this saved them from freezing in a blizzard. In the retreat from Caradhras, Boromir proved his strength and stamina as he burrowed through shoulder-high snowbanks alongside Aragorn to clear the path back down the mountain.
The Fellowship then passed under the mountains through the caverns of Moria, where Gandalf was lost, and Aragorn became their new guide. At the borders of the Elven realm of Lothlórien, Boromir was unnerved by the thought of entering—he pleaded with Aragorn to find another way "though it led through a hedge of swords", citing stories of elvish witchcraft, and the "strange paths" they had been taking which had already caused them to lose Gandalf. Once in Lórien, Boromir was greatly disturbed by the Elven Lady Galadriel's testing of his mind; he told Aragorn "not to be too sure of this lady and her purposes." On parting, Galadriel gave Boromir a golden belt and an Elven-cloak.
Boromir had always planned to go to Minas Tirith, and despite the consensus reached at Rivendell that it must be destroyed in Mordor, he urged the Fellowship to accompany him to Minas Tirith before going on to Mordor. As Frodo pondered his course from Parth Galen, Boromir privately urged Frodo to use the Ring in Gondor's defence rather than to "throw it away". Finally, he succumbed to the temptation to take the Ring for himself, justifying this by his duty to his people and his belief in his own integrity.
“ True-hearted Men, they will not be corrupted. We of Minas Tirith have been staunch through long years of trial. We do not desire the power of wizard-lords, only strength to defend ourselves, strength in a just cause. And behold! In our need chance brings to light the Ring of Power. It is a gift, I say; a gift to the foes of Mordor. It is mad not to use it, to use the power of the Enemy against him. The fearless, the ruthless, these alone will achieve victory. What could not a warrior do in this hour, a great leader? What could not Aragorn do? Or if he refuses, why not Boromir? The Ring would give me power of Command. How I would drive the hosts of Mordor, and all men would flock to my banner![6] ”
After seeing that Frodo was unconvinced, Boromir half begged, half commanded him to at least lend the Ring, and when Frodo still refused, Boromir leaped to seize it. Frodo vanished by putting on the Ring and fled, intending to continue the quest alone. Boromir, realizing his betrayal, immediately repented his actions and wept. Searching unsuccessfully for Frodo, he told the Fellowship of Frodo's disappearance, though not of his own misdeeds. The hobbits in a frenzy scattered to look for Frodo. Aragorn, who suspected Boromir's part in Frodo's flight, ordered him to follow and protect Merry and Pippin, which he did without question. The Fellowship was then attacked by a band of orcs.
The Two Towers [ edit ]
During the scattered fighting against Orcs near Parth Galen, Boromir was mortally wounded by arrows while defending Merry and Pippin, redeeming himself for trying to take the Ring. The fighting is described through Pippin's eyes:
“ Then Boromir had come leaping through the trees. He had made them fight. He slew many of them and the rest fled. But they had not gone far on the way back when they were attacked again, by a hundred Orcs at least, some of them very large, and they shot a rain of arrows: always at Boromir. Boromir had blown his great horn till the woods rang, and at first the Orcs had been dismayed and had drawn back; but when no answer but the echoes came, they had attacked more fiercely than ever. Pippin did not remember much more. His last memory was of Boromir leaning against a tree, plucking out an arrow; then darkness fell suddenly.[7] ”
Blasts from Boromir's horn alerted Aragorn, but he came too late to prevent the hobbits' capture. As Boromir lay dying, he remorsefully confessed to attempting to take the Ring from Frodo, and accepted his own impending death as penance. He urged Aragorn to save Minas Tirith, as he himself had failed. Aragorn reassured him that he had not failed, that "few have gained such a victory". Aragorn, Gimli, and Legolas placed Boromir's body in one of their Elven boats, with his sword, belt, cloak, broken horn, and the weapons of his slain foes about him. They set the boat adrift in the river toward the Falls of Rauros, and sang a "Lament of the Winds" as his funeral song.
Boromir passed over Rauros on 26th 'February' T.A. 3019. Three days later, Faramir, to his and their father's great grief, found the boat bearing his dead brother floating down the River Anduin:
“ But in Gondor in after-days it long was said that the elven-boat rode the falls and the foaming pool, and bore him down through Osgiliath, and past the many mouths of Anduin, out into the Great Sea at night under the stars.[8] ”
Faramir later observed to Frodo that Boromir "died well, achieving some good thing. His face was more beautiful even than in life."
Characteristics [ edit ]
Tolkien describes Boromir's appearance as reflecting his Númenórean descent: tall (Tolkien wrote he was 6'4" or 193 cm) and sturdy (slightly shorter but stockier than Aragorn), fair, dark-haired, and grey-eyed. He was noted even beyond Gondor's borders for his bravery and skill in battle, and was accounted one of the greatest Captains of Gondor. He was noble and lordly, and at the same time deeply loyal, acting from strong love for his people and his family.
Boromir's character changes throughout Book II of The Fellowship Of The Ring, in line with the epic's progression towards the catastrophe that ends Book II. Boromir is shown as having the habit of command. According to his brother Faramir, even as a boy Boromir chafed under the notion that the Stewards were not kings, though they ruled in all but name.[9] He insisted on taking for himself the quest to Imladris, though the dreams had come first to Faramir. At Rivendell he, using what critic Tom Shippey describes as "slightly wooden magniloquence", sets forth Gondor's claim to primacy in the War of the Ring.[5]
As Book II continues, Boromir is shown as displaying increasing "bravado and recklessness."[10] The Captain of the White Tower craved honours, was irked at having to flee from orcs, resisted Aragorn's claim to leadership, and played a key role in the catastrophe that sundered the Fellowship of the Ring. In an opening scene of Book III, Boromir redeems himself. Fatally injured by orc-arrows, Boromir admits his failure, advises Aragorn, and urges him to lead Gondor and save its people. Boromir's loyalty to his native City is shown as redressing the catastrophe he had brought upon the Fellowship by assaulting Frodo in his madness.
Names and titles [ edit ]
Boromir was the son and heir apparent of Denethor, the ruling Steward of Gondor. Appendix A calls him "Captain of the White Tower",[11] while Faramir called him "High Warden of the White Tower" and "our Captain-General".[12]
Boromir was described by Tolkien as a name "of mixed form",[13] and possibly combines Sindarin bor(on)- 'steadfast' with either Sindarin mîr or Quenya míre 'jewel'.[14] But the Stewards of Gondor also often bore names "remembered in the songs and histories of the First Age",[13] regardless of meaning, and the name Boromir did appear during the First Age in The Silmarillion.[15] The eleventh steward of Gondor, Denethor I, had as well a son called Boromir who was described as a great warrior. This might have been an inspiration for Denethor II to name his first son.[16]
Interpretation of the character [ edit ]
Boromir's desire for the Ring has been described as well-intentioned but oblivious of the potential danger. His perception of Middle-earth is biased by a belief that divine powers have chosen Gondor to lead the fight against evil.[17] He is always eager to praise the great deeds of Gondor, including his own.[18] Boromir's hubris makes him prey to the malign power of the Ring, and he seals his own doom when he attacks Frodo to seize it.[17] He makes way thereby for Aragorn to become the future king of Gondor, in a manner similar to Virgil's character Turnus.[18]
Boromir has been compared to other Tolkien characters such as Fëanor or Túrin Turambar who display vainglorious excess, a trait in leaders that Tolkien himself despised.[19]
The character of Boromir has also been compared to the medieval legendary hero Roland. Both blow a horn in the distress of battle and both are eventually killed in the wilderness while defending their companions, although Roland is portrayed as blameless and heroic throughout.[20]
Portrayal in adaptations [ edit ]
In both Ralph Bakshi's 1978 animated film and in the subsequent BBC Radio serial, Boromir is played by Michael Graham Cox. In the former, he is dressed in barbarian garb, which is a total departure from Tolkien's text.
Boromir is played by Carl-Kristian Rundman in the 1993 Finnish miniseries Hobitit.
In Peter Jackson's The Lord of the Rings film trilogy, Boromir is played by Sean Bean. In a departure from the structure of Tolkien's book, Boromir's death is shown at the end of The Fellowship of the Ring (2001), instead of being related at the beginning of The Two Towers. In the film, Boromir is mortally wounded by three large arrows fired by the Uruk-hai leader Lurtz, a character created for the films, instead of by numerous arrows from orcs led by Uglúk. He is found by Aragorn, who slays Lurtz before the latter can deal a final blow to Boromir.
In The Two Towers (2002), Boromir appears in the theatrical version only briefly during the beginning flashback sequence of Gandalf's fight with the Balrog in Moria. The Extended Edition adds two additional flashbacks: first when Faramir remembers finding Boromir's body and his cloven horn in the elven boat washed up on shore; and in considerably longer flashback (the only scene of the film trilogy where Boromir and Faramir are seen speaking to each other), after Boromir's victory in Osgiliath and before his departure for Rivendell. The two brothers are seen celebrating and laughing before their father interrupts, asking him to go to Rivendell to seek the One Ring, and the scene ends as Boromir leaves, saying to Faramir, "Remember today, little brother". Here Boromir apparently knows that "Isildur's Bane" is the One Ring, and he is chosen specifically by his father, despite his reluctance to go, in response to a summons from Elrond. He is thus aware of the true meaning of the phrase "Isildur's Bane" when he arrives at Rivendell on horseback.
In The Return of the King (2003), Boromir appears in the theatrical version during a brief flashback as Pippin remembers his heroic self-sacrifice. Due to that scene alone, Sean Bean's name and portrait appears in the closing credits of the film. In the Extended Edition of the film, Boromir appears briefly when Denethor looks at Faramir and imagines for a moment that he sees Boromir walking towards him, smiling.
See also [ edit ]
Middle-earth portal
References [ edit ] |
AP Today the Supreme Court threw out Section 3 of the Defense of Marriage Act, which bars the federal government from recognizing same-sex marriages even if they are allowed under state law.
Justice Antonin Scalia filed a scathing dissent in which he called Anthony Kennedy's majority opinion "rootless and shifting," "confusing," and "perplexing."
He also said that it consists of "nonspecific hand-waving," and that it demonstrates "real cheek."
Antonin Scalia dissented from the decision on the grounds that the court did not have standing to take the case.
He wrote:
The Court is eager—hungry—to tell everyone its view of the legal question at the heart of this case... Yet the plaintiff and the Government agree entirely on what should happen in this lawsuit. They agree that the court below got it right; and they agreed in the court below that the court below that one got it right as well. What, then, are we doing here?
He also speculated that the majority justices are trying to hide their plan to issue a more sweeping ruling in the near future:
My guess is that the majority, while reluctant to suggest that defining the meaning of "marriage" in federal statutes is unsupported by any of the Federal Government's enumerated powers, nonetheless needs some rhetorical basis to support its pretense that today's prohibition of laws excluding same-sex marriage is confined to the Federal Government (leaving the second, state-law shoe to be dropped later, maybe next Term). But I am only guessing.
He criticized the majority for not fairly representing the views of Defense of Marriage Act supporters:
I imagine that this is because it is harder to maintain the illusion of the Act's supporters as unhinged members of a wild-eyed lynch mob when one first describes their views as they see them.
Then he got really angry:
To be sure (as the majority points out), the legislation is called the Defense of Marriage Act. But to defend traditional marriage is not to condemn, demean, or humiliate those who would prefer other arrangements, any more than to defend the Constitution of the United States is to condemn, demean, or humiliate other constitutions. To hurl such accusations so casually demeans this institution. In the majority's judgment, any resistance to its holding is beyond the pale of reasoned disagreement. To question its high-handed invalidation of a presumptively valid statute is to act (the majority is sure) with the purpose to "disparage," "injure," "degrade," "demean," and "humiliate" our fellow human beings, our fellow citizens, who are homosexual. All that, simply for supporting an Act that did no more than codify an aspect of marriage that had been unquestioned in our society for most of its existence—indeed, had been unquestioned in virtually all societies for virtually all of human history. It is one thing for a society to elect change; it is another for a court of law to impose change by adjudging those who oppose it hostes humani generis, enemies of the human race.
He ended with a bit of concern-trolling, saying today's decision on DOMA was bad for both supporters and opponents of same-sex marriage:
Some will rejoice in today's decision, and some will despair at it; that is the nature of a controversy that matters so much to so many. But the Court has cheated both sides, robbing the winners of an honest victory, and the losers of the peace that comes from a fair defeat. We owed both of them better. |
# django imports
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from brain import Scripts
from .models import *
# user imports
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm, UserCreationForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from .forms import *
def home(request):
urlEnc = ""
usuario = False if request.user.username=="" else True
if request.method == 'POST':
urlOrig = request.POST.get('urlOriginal')
# adicionar o protocolo na url original, se não possuir
if "http" not in urlOrig:
urlOrig = "http://" + urlOrig
# verificar se já possui algum dado com o usuario e a url original
if len(Url.objects.all().filter(usuario = request.user.username, urlOriginal = urlOrig)) == 0:
# gerar url encurtada / não permitir dados repetidos
while True:
urlEnc = Scripts.generateUrl()
urlQuerry = Url.objects.all().filter(urlEncurtada = urlEnc)
if(len(urlQuerry) == 0):
break
# salvar o registro
Url.objects.create(
urlOriginal = urlOrig,
urlEncurtada = urlEnc,
usuario = request.user.username if request.user.username != "" else ""
)
# caso ja possua url encurtada com esse usuario, retornar a url encurtada
else:
urlEnc = Url.objects.get(urlOriginal = urlOrig, usuario = request.user.username)
urlEnc = "enclink.herokuapp.com/r/" + str(urlEnc)
context = {'urlenc': urlEnc, 'user': usuario}
return render(request, 'index.html', context)
def redirecionar(request, link):
caminho = Url.objects.get(urlEncurtada=link)
return redirect(caminho.urlOriginal)
def encLinkUser(request):
messageLogin = ""
messageSignUp = ""
if request.method == "POST":
#login
if request.POST.get('type') == 'login':
username = request.POST.get('user')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request,'Identificação não encontrada')
return redirect('login')
#signup
elif request.POST.get('type') == 'sign':
username = request.POST.get('user-sign')
password1 = request.POST.get('<PASSWORD>')
password2 = request.POST.get('password2-sign')
if password1 == password2:
try:
user = User.objects.create_user(username, '', password1)
user.save()
messageSignUp = "Usuario cadastrado, entre no sistema"
except:
messageSignUp = "Ja existe um usuário com este nome"
else:
messageSignUp = "Senhas não correspondem"
context = {'messageLogin' : messageLogin, 'messageSignUp': messageSignUp}
return render(request, 'user.html', context)
@login_required(login_url='login')
def logoutUser(request):
logout(request)
return redirect('home')
@login_required(login_url='login')
def logs(request):
urls = Url.objects.all().filter(usuario = request.user.username)
return render(request, 'logs.html', {'logs': urls})
@login_required(login_url='login')
def deletar(request, id):
link = Url.objects.all().filter(urlEncurtada = id)
link.delete()
return redirect('logs')
def handlerErrorPage(request, exception):
return render(request, '404.html') |
// Loads the compact trie dictionary file into the CompactTrieNodes
private void loadBreakCTDictionary(DataInputStream in) throws IOException {
for (int i = 0; i < fData.nodeCount; i++) {
in.readInt();
}
nodes = new CompactTrieNodes[fData.nodeCount];
nodes[0] = new CompactTrieNodes();
for (int j = 1; j < fData.nodeCount; j++) {
nodes[j] = new CompactTrieNodes();
nodes[j].flagscount = in.readShort();
int count = nodes[j].flagscount & CompactTrieNodeFlags.kCountMask;
if (count != 0) {
boolean isVerticalNode = (nodes[j].flagscount & CompactTrieNodeFlags.kVerticalNode) != 0;
if (isVerticalNode) {
nodes[j].vnode = new CompactTrieVerticalNode();
nodes[j].vnode.equal = in.readShort();
nodes[j].vnode.chars = new char[count];
for (int l = 0; l < count; l++) {
nodes[j].vnode.chars[l] = in.readChar();
}
} else {
nodes[j].hnode = new CompactTrieHorizontalNode[count];
for (int n = 0; n < count; n++) {
nodes[j].hnode[n] = new CompactTrieHorizontalNode(in
.readChar(), in.readShort());
}
}
}
}
} |
import { NgModule, ValueProvider } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SmithchartSeriesDirective, SmithchartSeriesCollectionDirective } from './series.directive';
import { SmithchartComponent } from './smithchart.component';
import { SmithchartModule } from './smithchart.module';
import {SmithchartLegend, TooltipRender} from '@syncfusion/ej2-charts'
export const SmithchartLegendService: ValueProvider = { provide: 'ChartsSmithchartLegend', useValue: SmithchartLegend};
export const TooltipRenderService: ValueProvider = { provide: 'ChartsTooltipRender', useValue: TooltipRender};
/**
* NgModule definition for the Smithchart component with providers.
*/
@NgModule({
imports: [CommonModule, SmithchartModule],
exports: [
SmithchartModule
],
providers:[
SmithchartLegendService,
TooltipRenderService
]
})
export class SmithchartAllModule { } |
/*
Copyright (c) 2015, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of LielasDataloggerstudio nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lielas.dataloggerstudio.pc.gui.Panels.MenuPanels;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
import org.lielas.dataloggerstudio.lib.Dataset;
import org.lielas.dataloggerstudio.lib.Logger.UsbCube.UsbCube;
import org.lielas.dataloggerstudio.lib.LoggerManager;
import org.lielas.dataloggerstudio.lib.LoggerRecord;
import org.lielas.dataloggerstudio.lib.LoggerRecordManager;
import org.lielas.dataloggerstudio.pc.CommunicationInterface.UsbCube.UsbCubeSerialInterface;
import org.lielas.dataloggerstudio.pc.gui.BodyButton;
import org.lielas.dataloggerstudio.pc.gui.MainFrame;
import org.lielas.dataloggerstudio.pc.gui.MouseOverHintManager;
import org.lielas.dataloggerstudio.pc.gui.Panels.DataContentPanels.DataContentPanel;
import org.lielas.dataloggerstudio.pc.gui.Toast.Toast;
import org.lielas.dataloggerstudio.pc.language.LanguageManager;
import javax.swing.*;
import javax.swing.border.MatteBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.xml.crypto.Data;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
/**
* Created by Andi on 06.01.2015.
*/
public class LoggerRecordsMenuPanel extends MenuPanel{
JLabel lblHeader;
JTree treeLogfiles;
DefaultMutableTreeNode rootNode;
DefaultTreeModel treeModel;
BodyButton bttnLoadData;
private DataContentPanel dcp;
JLabel lblDownloadStatus;
JLabel lblDownloadStatusContent;
int lrCount;
public LoggerRecordsMenuPanel(MainFrame mainFrame){
super(mainFrame);
this.setOpaque(false);
this.setBorder(new MatteBorder(0, 0, 1, 0, (Color) Color.LIGHT_GRAY));
this.mainFrame = mainFrame;
dcp = null;
int row = 2;
lrCount = 0;
setLayout(new FormLayout(
new ColumnSpec[]{
ColumnSpec.decode("20px"),
FormFactory.PREF_COLSPEC,
ColumnSpec.decode("20px"),
FormFactory.PREF_COLSPEC,
ColumnSpec.decode("15px:grow"),},
new RowSpec[] {
RowSpec.decode("10px"),
FormFactory.PREF_ROWSPEC,
RowSpec.decode("20px"),
FormFactory.PREF_ROWSPEC,
RowSpec.decode("20px"),
FormFactory.PREF_ROWSPEC,
RowSpec.decode("20px"),
FormFactory.PREF_ROWSPEC,
RowSpec.decode("20px"),
FormFactory.PREF_ROWSPEC,
RowSpec.decode("20px:grow"),}));
lblHeader = new JLabel("");
lblHeader.setFont(fontBold);
add(lblHeader, getLayoutString(2, row, "left", "center"));
row += 2;
rootNode = new DefaultMutableTreeNode("Logfiles");
treeModel = new DefaultTreeModel(rootNode);
treeLogfiles = new JTree(treeModel);
treeLogfiles.setOpaque(false);
treeLogfiles.setCellRenderer(new TreeCellRenderer());
treeLogfiles.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
TreeSelectionChanged(e);
}
});
add(treeLogfiles, "2, " + Integer.toString(row) + ", 3, 1, left, top");
row += 2;
bttnLoadData = new BodyButton("");
bttnLoadData.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
BttnLoadDataPressed();
}
});
bttnLoadData.setFont(fontBttn);
add(bttnLoadData, getLayoutString(4, row, "right", "center"));
row += 2;
lblDownloadStatus = new JLabel("");
add(lblDownloadStatus, getLayoutString(2, row, "left", "center"));
lblDownloadStatusContent = new JLabel("");
add(lblDownloadStatusContent, getLayoutString(4, row, "left", "center"));
}
@Override
public void updateLanguage(LanguageManager lm, MouseOverHintManager hintManager) {
lblHeader.setText(lm.getString(986));
bttnLoadData.setText(lm.getString(988));
lblDownloadStatus.setText(lm.getString(1091));
rootNode.setUserObject(lm.getString(1090));
}
@Override
public void updateUIContent() {
UsbCube logger = (UsbCube)LoggerManager.getInstance().getActiveLogger();
LoggerRecord lr;
DefaultMutableTreeNode loggerTreeNode;
if(logger != null) {
if(logger.getRecordCount() == 0){
rootNode.removeAllChildren();
treeModel.reload();
}
for (int index = 0; index < logger.getRecordCount(); index++) {
try {
loggerTreeNode = (DefaultMutableTreeNode) rootNode.getChildAt(index);
}catch(Exception e){
loggerTreeNode = null;
}
if(loggerTreeNode == null){
//create new entry
lr = logger.getRecordset(index);
if (lr != null) {
loggerTreeNode = new DefaultMutableTreeNode(lr);
DefaultMutableTreeNode start = new DefaultMutableTreeNode("Start: " + lr.getDatetimeString());
loggerTreeNode.add(start);
DefaultMutableTreeNode end = new DefaultMutableTreeNode("End: " + lr.getEndDatetimeString());
loggerTreeNode.add(end);
DefaultMutableTreeNode samplerate = new DefaultMutableTreeNode("Samplerate: " + lr.getSampleRateString());
loggerTreeNode.add(samplerate);
DefaultMutableTreeNode samples = new DefaultMutableTreeNode("Samples: " + Long.toString(lr.getEndIndex() - lr.getStartIndex() + 1));
loggerTreeNode.add(samples);
} else {
loggerTreeNode = new DefaultMutableTreeNode("logfile" + Integer.toString(index));
}
rootNode.add(loggerTreeNode);
treeModel.reload();
treeLogfiles.expandPath(new TreePath(rootNode.getPath()));
}
}
}
}
private void BttnLoadDataPressed(){
LoggerRecord lr;
LoggerRecordManager lrm = LoggerRecordManager.getInstance();
//get selected loggerrecord
DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeLogfiles.getLastSelectedPathComponent();
if(node == null){
Toast t = new Toast(mainFrame, "You have to select a logfile to download its data");
return;
}
if(node.getChildCount() == 0){
node = (DefaultMutableTreeNode)node.getParent();
}
try {
lr = (LoggerRecord) node.getUserObject();
lr = lrm.get(lr.getIndex());
}catch (Exception e){
return;
}
if(lr == null){
return;
}
LoadDataWorker loadDataWorker = new LoadDataWorker(this, lr);
loadDataWorker.execute();
}
public void setDataContentPanel(DataContentPanel dcp){
this.dcp = dcp;
}
private void TreeSelectionChanged(TreeSelectionEvent e){
LoggerRecord lr;
DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeLogfiles.getLastSelectedPathComponent();
if(node == null){
return;
}
if(node.getChildCount() == 0){
node = (DefaultMutableTreeNode)node.getParent();
}
try {
lr = (LoggerRecord) node.getUserObject();
}catch (Exception ex){
return;
}
if(lr != null){
LoggerRecordManager.getInstance().select(lr.getIndex());
}
mainFrame.updateUIContent();
}
private class SampleProgress{
public final long samples;
public final long maxSamples;
SampleProgress(long samples, long maxSamples){
this.samples = samples;
this.maxSamples = maxSamples;
}
}
class LoadDataWorker extends SwingWorker<LoggerRecord, SampleProgress>{
JPanel parent;
LoggerRecord lr;
public LoadDataWorker(JPanel panel, LoggerRecord lr){
parent = panel;
this.lr = lr;
}
@Override
protected LoggerRecord doInBackground() throws Exception {
long id = 0, tmpId;
long start = new Date().getTime();
LoggerManager loggerManager = LoggerManager.getInstance();
UsbCubeSerialInterface com = (UsbCubeSerialInterface) loggerManager.getActiveLogger().getCommunicationInterface();
com.getLastError();
com.flush();
//get each dataset through lsp
/*for(id = lr.getStartIndex(); id <= lr.getEndIndex(); id++){
for(j = 0; j < tries; j++) {
if (com.getLogfileDataset((UsbCube) loggerManager.getActiveLogger(), lr, id)) {
if (com.getLastError() != null && com.getLastError().equals(LanguageManager.getInstance().getString(1066))) {
break;
}
}
if (j == tries) {
return null;
}
double dur = (new Date().getTime() - start);
System.out.println("Duration: " + Double.toString(dur) + "ms");
SampleProgress progress = new SampleProgress(id - lr.getStartIndex(), lr.getEndIndex() - lr.getStartIndex());
publish(progress);
}
}*/
lr.clearData();
tmpId = com.getLdpPaket((UsbCube)loggerManager.getActiveLogger(), lr, true);
while(tmpId > 0){
id += tmpId;
tmpId = com.getLdpPaket((UsbCube)loggerManager.getActiveLogger(), lr, false);
SampleProgress progress = new SampleProgress(id, lr.getEndIndex() - lr.getStartIndex());
publish(progress);
}
//all pakets received, check if data is missing
id = lr.get(0).getId();
for(int i = 1; i < (lr.getEndIndex() - lr.getStartIndex() + 1); i++){
if(lr.get(i) == null || lr.get(i).getId() != (id + 1)){
//missing a dataset, try to get it via settings manager
com.getLogfileDataset((UsbCube) loggerManager.getActiveLogger(), lr, id+1);
lr.sort();
SampleProgress progress = new SampleProgress(id+1, lr.getEndIndex() - lr.getStartIndex());
publish(progress);
}
id = lr.get(i).getId();
}
double duration = (new Date().getTime() - start)/1000.;
System.out.println("Duration: " + Double.toString(duration) + "s");
return lr;
}
@Override
public void done(){
if(dcp != null && lr != null){
dcp.setLoggerRecord(lr);
}
mainFrame.updateUIContent();
}
@Override
protected void process (java.util.List<SampleProgress> samples){
SampleProgress progress = samples.get(samples.size()-1);
long loaded = progress.samples + 1;
long max = progress.maxSamples + 1;
if(loaded > max){
loaded = max;
}
lblDownloadStatusContent.setText(loaded + "/" + max);
}
}
}
|
Design of the Instrument Soft Panel Using Windows Presentation Foundation
In order to meet new demands on software designing in the field of testing instrument, this paper implements an instrument soft panel by WPF programming method using Microsoft Visual Studio. The appearance of the soft panel embodies WPF applications' advantages and the soft panel has the utility of controlling HITPE101 data acquisition module through hardware drivers based on VISA. Finally an auto-test system is built to verify the soft panel operates correctly in the design. |
def create_root(self, name, external_id=None):
root_leafs = self.dbm.get_all_label_trees(global_only=True)
if root_leafs is not None:
for leaf in root_leafs:
if name == leaf.name:
return None
self.root = model.LabelLeaf(name=name,
external_id=external_id, is_root=True)
self.dbm.add(self.root)
self.dbm.commit()
self.tree[self.root.idx] = self.root
self.logger.info('Created root leaf: {}'.format(name))
return self.root |
class FunctionTaskFactory:
"""
This is essentially a factory that allows us to implement tasks for a session
"""
func: Callable[[Any], Any]
is_always_eager: bool = False
description: Optional[str] = None
def __call__(self, *args, **kwargs) -> "SessionTaskSpec":
"""
Create a SessionTaskSpec from this function and the given arguments
"""
return SessionTaskSpec(
func=self.func,
args=args,
kwargs=kwargs,
is_always_eager=self.is_always_eager,
description=self.description,
) |
def _fullname_length_exceeds(first_name, last_name):
return len(first_name) + len(last_name) > FULLNAME_MAX_LENGTH |
/**
* Copyright (c) 2015-2016 VisionStar Information Technology (Shanghai) Co., Ltd. All Rights Reserved.
* EasyAR is the registered trademark or trademark of VisionStar Information Technology (Shanghai) Co., Ltd in China
* and other countries for the augmented reality technology developed by VisionStar Information Technology (Shanghai) Co., Ltd.
*/
#ifndef __EASYAR_TARGET_HPP__
#define __EASYAR_TARGET_HPP__
#include "easyar/base.hpp"
#include "easyar/storage.hpp"
#include "easyar/matrix.hpp"
namespace EasyAR {
class ImageList;
class TargetList;
class Target : public RefBase
{
public:
Target();
virtual ~Target();
//! load named target if name is not empty, otherwise load the first target
virtual bool load(const char* path, int storageType, const char* name = 0);
//! id is valid (non-zero) only after a successfull load
int id() const;
const char* uid() const;
const char* name() const;
const char* metaData() const;
//! data will be copied as string
bool setMetaData(const char* data);
ImageList images();
};
class TargetList : public RefBase
{
public:
TargetList();
virtual ~TargetList();
int size() const;
Target operator [](int idx);
Target at(int idx);
bool insert(const Target& target);
bool erase(const Target& target);
};
class AugmentedTarget : public RefBase
{
public:
enum Status
{
kTargetStatusUnknown,
kTargetStatusUndefined,
kTargetStatusDetected,
kTargetStatusTracked,
};
AugmentedTarget();
virtual ~AugmentedTarget();
virtual Status status() const;
virtual Target target() const;
virtual Matrix34F pose() const;
};
class AugmentedTargetList : public RefBase
{
public:
AugmentedTargetList();
virtual ~AugmentedTargetList();
int size() const;
AugmentedTarget operator [](int idx);
AugmentedTarget at(int idx);
};
}
#endif
|
import { GetStaticProps } from "next";
import React, { FC } from "react";
import Container from "@/components/Container";
import Page from "@/components/Page";
import TagsList from "@/components/TagsList";
import { getAllTags } from "@/utils";
import { Tag } from "@/types";
type Props = {
tags: Tag[];
};
const TagsPage: FC<Props> = ({ tags }) => {
return (
<Page title="Tags">
<Container className="space-y-16 my-16 min-h-[600px]">
<div className="text-center space-y-2">
<h1 className="text-4xl font-bold">All Tags</h1>
<p className="space-x-2 text-lg text-gray-600 dark:text-gray-400">
<span>{tags.length}</span>
<span>Tags</span>
</p>
</div>
{tags?.length > 0 ? (
<TagsList tags={tags} />
) : (
<div className="text-center py-48 text-gray-600 dark:text-gray-400">
<p>Empty</p>
</div>
)}
</Container>
</Page>
);
};
export default TagsPage;
export const getStaticProps: GetStaticProps<Props> = async () => {
return {
props: {
tags: await getAllTags(),
},
};
};
|
/**
* Created by jamescscott on 11/22/14.
*/
public class JavaMergeSort implements IMergeSortable{
public JavaMergeSort() {}
private static int[] JavaMerge(int[] left, int[] right, boolean ascending) {
int leftMaxIndex = left.length - 1;
int rightMaxIndex = right.length - 1;
int leftIndex = 0, rightIndex = 0;
int totalLength = leftMaxIndex + 1 + rightMaxIndex + 1;
int[] mergedArray = new int[totalLength];
for (int i = 0; i < totalLength; i++) {
if (leftIndex <= leftMaxIndex && rightIndex > rightMaxIndex) {
// Only elements in the left array.
mergedArray[i] = left[leftIndex];
leftIndex++;
} else if (rightIndex <= rightMaxIndex && leftIndex > leftMaxIndex) {
// Only elements in the right array.
mergedArray[i] = right[rightIndex];
rightIndex++;
} else if (left[leftIndex] < right[rightIndex]) {
if (ascending) {
mergedArray[i] = left[leftIndex];
leftIndex++;
} else {
mergedArray[i] = right[rightIndex];
rightIndex++;
}
} else {
if (ascending) {
mergedArray[i] = right[rightIndex];
rightIndex++;
} else {
mergedArray[i] = left[leftIndex];
leftIndex++;
}
}
}
return mergedArray;
}
public static int[] JavaMergeSortFn(int[] array, boolean ascending) {
if (array.length <= 1) {
return array;
}
int middleIndex = array.length / 2;
// Create the left and right arrays.
int[] left = Arrays.copyOfRange(array, 0, middleIndex);
int[] right = Arrays.copyOfRange(array, middleIndex, array.length);
// Sort the individual left and right arrays.
left = JavaMergeSortFn(left, ascending);
right = JavaMergeSortFn(right, ascending);
// Merge the two arrays.
int[] result = JavaMerge(left, right, ascending);
return result;
}
@Override
public long MergeSortEntry(int size, int ascending, int[] randomArray) {
long beginTime = System.currentTimeMillis();
JavaMergeSortFn(randomArray, ascending != 0);
return System.currentTimeMillis() - beginTime;
}
@Override
public String getSortLanguage() {
return "Java";
}
} |
//
// csmstlimporter.hxx
// rGWB
//
// Created by <NAME> on 29/10/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
#ifndef csmstlimporter_hxx
#define csmstlimporter_hxx
enum csmstlimporter_result_t
{
CSMSTLIMPORTER_RESULT_OK = 0,
CSMSTLIMPORTER_RESULT_FILE_NOT_FOUND = 1,
CSMSTLIMPORTER_RESULT_INCORRECT_FORMAT = 2,
CSMSTLIMPORTER_RESULT_EMPTY_SOLID = 3,
CSMSTLIMPORTER_RESULT_NON_MANIFOLD_FACETED_BREP = 4,
CSMSTLIMPORTER_RESULT_MALFORMED_FACETED_BREP = 5,
CSMSTLIMPORTER_RESULT_INCONSISTENT_INNER_LOOP_ORIENTATION = 6,
CSMSTLIMPORTER_RESULT_INCONSISTENT_IMPROPER_INTERSECTIONS = 7
};
#endif /* csmstlimporter_hxx */
|
An assessment of the use of anthropometric measures for predicting low birth weight.
We report results of an evaluation of two anthropometric surrogates, viz chest circumference and mid-arm circumference, of birth weight. Optimal criteria for predicting birth weight below 2000 g and below 2500 g were provided by use of chest circumference alone. However, even the best criterion was not very sensitive indicating that use of anthropometric surrogates may have a limited practical value. |
Structural and electronic properties of C60.
We present pseudopotential local-density calculations of the electronic and structural properties of solid C 60 (fullerite). The calculated molecular bond lengths, lattice constant, bulk modulus, enthalpy of formation, and the equation of state for compression are in good agreement with experiment. The shape of the theoretical density of states is in excellent agreement with the experimental photoemission and inverse photoemission spectra. We also present the calculated band structure for the states near the fundamental gap |
Etiology and therapy of community-acquired pneumonia.
The Authors report the data of a retrospective study performed on 520 patients admitted to the Institute of Respiratory Diseases, University of Sassari, Italy, for community acquired pneumonia (CAP) from 1980 to 1995. The aim of this study was to investigate: the frequency of risk factors and their impact on severity of pneumonia; the frequency of pathogens and their correlation with the severity of the illness; antibiotic treatments. One or more risk factors were found in 86% of patients, while 14% had none. In 286 patients (55%) no etiological diagnosis was possible, while in 234 patients (45%) the pathogen was identified. Of the latter, 73% suffered from pneumonia caused by Gram-negative bacilli, 24% by Gram-positive organisms, 0.8% by Mycoplasma pneumoniae and 1.7% by respiratory viruses and endemic fungi. The mortality rate found was 2.69%. In this study, pneumonia caused by Gram-negative bacilli showed a plurilobar and often bilateral involvement, frequent resistance to the most common antibiotics, which required longer hospitalization (> 30 days). The high prevalence of pneumonia caused by Gram-negative bacilli can be explained by the presence in most of the patients, of serious and numerous risk factors. |
#include<bits/stdc++.h>
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
using namespace std;
int main()
{
fast;
ll b,g,n,cntb=0,cntg=0,ans=0,i,j;
cin>>b>>g>>n;
if(b>=n&&g>=n)
{
ans+=n+1;
}
else if(b>=n&&g<n)
{
ans+=g+1;
}
else if(b<n&&g>=n)
{
ans+=b+1;
}
else
{
if(b>=g)
{
for(i=b,j=n-b;j<=g;i--,j++)
{
ans++;
}
}
else
{
for(i=g,j=n-g;j<=b;i--,j++)
{
ans++;
}
}
}
cout<<ans<<endl;
return 0;
}
|
"""
Flask-Classy
------------
Class based views for the Flask microframework.
:copyright: (c) 2013 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
__version__ = "0.6.8"
import sys
import functools
import inspect
from werkzeug.routing import parse_rule
from flask import request, Response, make_response
import re
_py2 = sys.version_info[0] == 2
def route(rule, **options):
"""A decorator that is used to define custom routes for methods in
FlaskView subclasses. The format is exactly the same as Flask's
`@app.route` decorator.
"""
def decorator(f):
# Put the rule cache on the method itself instead of globally
if not hasattr(f, '_rule_cache') or f._rule_cache is None:
f._rule_cache = {f.__name__: [(rule, options)]}
elif not f.__name__ in f._rule_cache:
f._rule_cache[f.__name__] = [(rule, options)]
else:
f._rule_cache[f.__name__].append((rule, options))
return f
return decorator
class FlaskView(object):
"""Base view for any class based views implemented with Flask-Classy. Will
automatically configure routes when registered with a Flask app instance.
"""
decorators = []
route_base = None
route_prefix = None
trailing_slash = True
@classmethod
def register(cls, app, route_base=None, subdomain=None, route_prefix=None,
trailing_slash=None):
"""Registers a FlaskView class for use with a specific instance of a
Flask app. Any methods not prefixes with an underscore are candidates
to be routed and will have routes registered when this method is
called.
:param app: an instance of a Flask application
:param route_base: The base path to use for all routes registered for
this class. Overrides the route_base attribute if
it has been set.
:param subdomain: A subdomain that this registration should use when
configuring routes.
:param route_prefix: A prefix to be applied to all routes registered
for this class. Precedes route_base. Overrides
the class' route_prefix if it has been set.
"""
if cls is FlaskView:
raise TypeError("cls must be a subclass of FlaskView, not FlaskView itself")
if route_base:
cls.orig_route_base = cls.route_base
cls.route_base = route_base
if route_prefix:
cls.orig_route_prefix = cls.route_prefix
cls.route_prefix = route_prefix
if not subdomain:
if hasattr(app, "subdomain") and app.subdomain is not None:
subdomain = app.subdomain
elif hasattr(cls, "subdomain"):
subdomain = cls.subdomain
if trailing_slash is not None:
cls.orig_trailing_slash = cls.trailing_slash
cls.trailing_slash = trailing_slash
members = get_interesting_members(FlaskView, cls)
special_methods = ["get", "put", "patch", "post", "delete", "index"]
for name, value in members:
proxy = cls.make_proxy_method(name)
route_name = cls.build_route_name(name)
try:
if hasattr(value, "_rule_cache") and name in value._rule_cache:
for idx, cached_rule in enumerate(value._rule_cache[name]):
rule, options = cached_rule
rule = cls.build_rule(rule)
sub, ep, options = cls.parse_options(options)
if not subdomain and sub:
subdomain = sub
if ep:
endpoint = ep
elif len(value._rule_cache[name]) == 1:
endpoint = route_name
else:
endpoint = "%s_%d" % (route_name, idx,)
app.add_url_rule(rule, endpoint, proxy, subdomain=subdomain, **options)
elif name in special_methods:
if name in ["get", "index"]:
methods = ["GET"]
else:
methods = [name.upper()]
rule = cls.build_rule("/", value)
if not cls.trailing_slash:
rule = rule.rstrip("/")
app.add_url_rule(rule, route_name, proxy, methods=methods, subdomain=subdomain)
else:
route_str = '/%s/' % name
if not cls.trailing_slash:
route_str = route_str.rstrip('/')
rule = cls.build_rule(route_str, value)
app.add_url_rule(rule, route_name, proxy, subdomain=subdomain)
except DecoratorCompatibilityError:
raise DecoratorCompatibilityError("Incompatible decorator detected on %s in class %s" % (name, cls.__name__))
if hasattr(cls, "orig_route_base"):
cls.route_base = cls.orig_route_base
del cls.orig_route_base
if hasattr(cls, "orig_route_prefix"):
cls.route_prefix = cls.orig_route_prefix
del cls.orig_route_prefix
if hasattr(cls, "orig_trailing_slash"):
cls.trailing_slash = cls.orig_trailing_slash
del cls.orig_trailing_slash
@classmethod
def parse_options(cls, options):
"""Extracts subdomain and endpoint values from the options dict and returns
them along with a new dict without those values.
"""
options = options.copy()
subdomain = options.pop('subdomain', None)
endpoint = options.pop('endpoint', None)
return subdomain, endpoint, options,
@classmethod
def make_proxy_method(cls, name):
"""Creates a proxy function that can be used by Flasks routing. The
proxy instantiates the FlaskView subclass and calls the appropriate
method.
:param name: the name of the method to create a proxy for
"""
i = cls()
view = getattr(i, name)
if cls.decorators:
for decorator in cls.decorators:
view = decorator(view)
@functools.wraps(view)
def proxy(**forgettable_view_args):
# Always use the global request object's view_args, because they
# can be modified by intervening function before an endpoint or
# wrapper gets called. This matches Flask's behavior.
del forgettable_view_args
if hasattr(i, "before_request"):
response = i.before_request(name, **request.view_args)
if response is not None:
return response
before_view_name = "before_" + name
if hasattr(i, before_view_name):
before_view = getattr(i, before_view_name)
response = before_view(**request.view_args)
if response is not None:
return response
response = view(**request.view_args)
if not isinstance(response, Response):
response = make_response(response)
after_view_name = "after_" + name
if hasattr(i, after_view_name):
after_view = getattr(i, after_view_name)
response = after_view(response)
if hasattr(i, "after_request"):
response = i.after_request(name, response)
return response
return proxy
@classmethod
def build_rule(cls, rule, method=None):
"""Creates a routing rule based on either the class name (minus the
'View' suffix) or the defined `route_base` attribute of the class
:param rule: the path portion that should be appended to the
route base
:param method: if a method's arguments should be considered when
constructing the rule, provide a reference to the
method here. arguments named "self" will be ignored
"""
rule_parts = []
if cls.route_prefix:
rule_parts.append(cls.route_prefix)
route_base = cls.get_route_base()
if route_base:
rule_parts.append(route_base)
rule_parts.append(rule)
ignored_rule_args = ['self']
if hasattr(cls, 'base_args'):
ignored_rule_args += cls.base_args
if method:
args = get_true_argspec(method)[0]
for arg in args:
if arg not in ignored_rule_args:
rule_parts.append("<%s>" % arg)
result = "/%s" % "/".join(rule_parts)
return re.sub(r'(/)\1+', r'\1', result)
@classmethod
def get_route_base(cls):
"""Returns the route base to use for the current class."""
if cls.route_base is not None:
route_base = cls.route_base
base_rule = parse_rule(route_base)
cls.base_args = [r[2] for r in base_rule]
else:
if cls.__name__.endswith("View"):
route_base = cls.__name__[:-4].lower()
else:
route_base = cls.__name__.lower()
return route_base.strip("/")
@classmethod
def build_route_name(cls, method_name):
"""Creates a unique route name based on the combination of the class
name with the method name.
:param method_name: the method name to use when building a route name
"""
return cls.__name__ + ":%s" % method_name
def get_interesting_members(base_class, cls):
"""Returns a list of methods that can be routed to"""
base_members = dir(base_class)
predicate = inspect.ismethod if _py2 else inspect.isfunction
all_members = inspect.getmembers(cls, predicate=predicate)
return [member for member in all_members
if not member[0] in base_members
and ((hasattr(member[1], "__self__") and not member[1].__self__ in inspect.getmro(cls)) if _py2 else True)
and not member[0].startswith("_")
and not member[0].startswith("before_")
and not member[0].startswith("after_")]
def get_true_argspec(method):
"""Drills through layers of decorators attempting to locate the actual argspec for the method."""
argspec = inspect.getargspec(method)
args = argspec[0]
if args and args[0] == 'self':
return argspec
if hasattr(method, '__func__'):
method = method.__func__
if not hasattr(method, '__closure__') or method.__closure__ is None:
raise DecoratorCompatibilityError
closure = method.__closure__
for cell in closure:
inner_method = cell.cell_contents
if inner_method is method:
continue
if not inspect.isfunction(inner_method) \
and not inspect.ismethod(inner_method):
continue
true_argspec = get_true_argspec(inner_method)
if true_argspec:
return true_argspec
class DecoratorCompatibilityError(Exception):
pass
|
<gh_stars>1-10
# -*- coding: utf-8 -*-
from scipy.stats import multinomial
from ..base import Property
from ..models.measurement.categorical import MarkovianMeasurementModel
from ..sensor.sensor import Sensor
from ..types.array import StateVector
from ..types.detection import TrueCategoricalDetection
class HMMSensor(Sensor):
r"""Sensor model that observes a categorical state space and returns categorical measurements.
Measurements are categorical distributions over a finite set of categories
:math:`Z = \{\zeta^n|n\in \mathbf{N}, n\le N\}` (for some finite :math:`N`).
"""
measurement_model: MarkovianMeasurementModel = Property(
doc="Measurement model to generate detection vectors from"
)
@property
def ndim_state(self):
return self.measurement_model.ndim_state
@property
def ndim_meas(self):
return self.measurement_model.ndim_meas
def measure(self, ground_truths, noise: bool = True, **kwargs):
r"""Generate a categorical measurement for a given set of true categorical state.
Parameters
----------
ground_truths: Set[:class:`~.CategoricalGroundTruthState`]
A set of :class:`~.CategoricalGroundTruthState`.
noise: bool
Indicates whether measurement vectors are sampled from and the resultant measurement
categories returned instead. These are discrete categories instead of a distribution
over the measurement space. They are represented by N-tuples, with all components
equal to 0, except at an index corresponding to the relevant category.
For example :math:`e^k` indicates that the measurement category is :math:`\zeta^k`.
If `False`, the resultant distribution is returned.
Returns
-------
Set[:class:`~.TrueCategoricalDetection`]
A set of measurements generated from the given states. The timestamps of the
measurements are set equal to that of the corresponding states that they were
calculated from. Each measurement stores the ground truth path that it was produced
from.
"""
detections = set()
for truth in ground_truths:
timestamp = truth.timestamp
detection_vector = self.measurement_model.function(truth, noise=noise, **kwargs)
if noise:
# Sample from resultant distribution
rv = multinomial(n=1, p=detection_vector.flatten())
detection_vector = StateVector(rv.rvs(size=1, random_state=None))
detection = TrueCategoricalDetection(
state_vector=detection_vector,
timestamp=timestamp,
categories=self.measurement_model.measurement_categories,
measurement_model=self.measurement_model,
groundtruth_path=truth
)
detections.add(detection)
return detections
|
<gh_stars>1-10
import 'mocha'
import { spawn, ChildProcess } from 'child_process'
import concat from 'concat-stream'
const sendInput = (inputs: string[], child: ChildProcess, timeout: number) => {
if (!inputs.length) {
return child.stdin.end()
}
const [firstInput, ...remainingInputs] = inputs
setTimeout(() => {
child.stdin.write(firstInput)
sendInput(remainingInputs, child, timeout)
}, timeout)
}
const createProcess = (processPath: string, args: string[]): ChildProcess => {
args = [processPath].concat(args)
return spawn('ts-node', args)
}
export const execute = (
processPath: string,
args: string[],
input: string[]
) => {
const childProcess = createProcess(processPath, args)
childProcess.stdout.setEncoding('utf-8')
sendInput(input, childProcess, 1200)
return new Promise((resolve, reject) => {
childProcess.stderr.once('data', err => {
reject(err.toString())
})
childProcess.on('error', err => {
reject(err)
})
childProcess.stdout.pipe(
concat(result => {
resolve(result.toString())
})
)
childProcess.on('close', () => {})
})
}
|
// Update the description when you apply this power. (i.e. add or remove an "s" in keyword(s))
@Override
public void updateDescription() {
StringBuilder sb = new StringBuilder();
int i = NormaHelper.getDenominator(AbstractDungeon.player) - NormaHelper.getNumerator(AbstractDungeon.player);
boolean skillsOnly = NormaHelper.getSkillsOnly(AbstractDungeon.player);
if (!broken) {
sb.append(DESCRIPTIONS[0]).append(DESCRIPTIONS[2]);
sb.append(i);
sb.append(i == 1 ? (skillsOnly ? DESCRIPTIONS[3] : DESCRIPTIONS[5])
: (skillsOnly ? DESCRIPTIONS[4] : DESCRIPTIONS[6]));
} else {
sb.append("#r").append(getRandomString(AbstractDungeon.cardRandomRng.random(18, 18)));
}
description = sb.toString();
} |
D'oh! Senate GOP staffers wince at Simpsons SCHIP 'joke'
Perhaps Friday afternoon boredom got the best of some House Republican staffers, or maybe whoever wrote this press release just came off an 18-hour Simpsons marathon.
Whatever the case, the use of fictional Springfield's Montgomery Burns and Mayor Joe Quimby to sell GOP talking points on a critical healthcare bill is being panned in the blogosphere. Even some Republican staffers on the other side of Capitol Hill winced at the stilted Simpsons joke.
The House Energy and Commerce Committee minority staff imagined a fictional press conference featuring "Republican businessman" Burns and Quimby, "D-Springfield," supporting the "Senate's gazillion-dollar SCHIP bill." (Congress and President Bush are fighting over the reauthorization of the State Children's Health Insurance Program.)
"Somehow they managed to look bitter instead of funny," one Senate GOP aide told Roll Call's Heard on the Hill column. That took a lot of talent.
Wonkette called the GOP attempt a humor a "mindfuck of a press release," and Ryan Powers, blogging at The Body Politik, said the satire has "absolutely no basis in reality."
The GOP release also took some pot-shots at MoveOn.org, a favorite GOP target, and it included a disclaimer in case anyone would confuse the yellow-hued Springfieldians for actual politicians.
"*Actual facts and events may vary," it says, "but really, how much?" |
<gh_stars>1-10
import type { GuildEntity } from '../entities/GuildEntity';
import { codeBlock, isNullish, toTitleCase } from '@sapphire/utilities';
import { Collection } from 'discord.js';
import type { TFunction } from 'i18next';
import type { SchemaKey } from './SchemaKey';
export type NonEmptyArray<T> = [T, ...T[]];
export class SchemaGroup extends Collection<string, ISchemaValue> {
public readonly parent: SchemaGroup | null;
public readonly name: string;
public readonly dashboardOnly = false;
public readonly type = 'Group';
public constructor(name = 'Root', parent: SchemaGroup | null = null) {
super();
this.name = name;
this.parent = parent;
}
public add([key, ...tail]: NonEmptyArray<string>, value: SchemaKey): SchemaGroup {
if (tail.length === 0) {
this.set(key, value);
return this;
}
const previous = this.get(key);
if (previous) {
if (previous instanceof SchemaGroup) {
return previous.add(tail as NonEmptyArray<string>, value);
}
throw new Error(`You cannot add '${key}' to a non-group entry.`);
}
const group = new SchemaGroup(`${this.name} / ${toTitleCase(key)}`, this);
group.add(tail as NonEmptyArray<string>, value);
this.set(key, group);
return group;
}
public *childKeys() {
for (const [key, entry] of this) {
if (entry.type !== 'Group') yield key;
}
}
public *childValues() {
for (const entry of this.values()) {
if (entry.type !== 'Group') yield entry;
}
}
public getPathArray([key, ...tail]: NonEmptyArray<string>): ISchemaValue | null {
if (tail.length === 0) {
return key === '' || key === '.' ? this : this.get(key) ?? null;
}
const value = this.get(key);
if (isNullish(value)) return null;
if (value instanceof SchemaGroup) return value.getPathArray(tail as NonEmptyArray<string>);
return null;
}
public getPathString(key: string): ISchemaValue | null {
return this.getPathArray(key.split('.') as NonEmptyArray<string>);
}
public display(settings: GuildEntity, language: TFunction) {
const folders: string[] = [];
const sections = new Map<string, string[]>();
let longest = 0;
for (const [key, value] of this.entries()) {
if (value.dashboardOnly) continue;
if (value.type === 'Group') {
folders.push(`// ${key}`);
} else {
const values = sections.get(value.type) ?? [];
values.push(key);
if (key.length > longest) longest = key.length;
if (values.length === 1) sections.set(value.type, values);
}
}
const array: string[] = [];
if (folders.length) array.push('= Folders =', ...folders.sort(), '');
if (sections.size) {
for (const keyType of [...sections.keys()].sort()) {
array.push(
`= ${toTitleCase(keyType)}s =`,
...sections
.get(keyType)!
.sort()
.map(key => `${key.padEnd(longest)} :: ${this.get(key)!.display(settings, language)}`),
''
);
}
}
return codeBlock('asciidoc', array.join('\n'));
}
}
export interface ISchemaValue {
readonly type: string;
readonly name: string;
readonly dashboardOnly: boolean;
readonly parent: SchemaGroup | null;
display(settings: GuildEntity, language: TFunction): string;
}
|
import { ProfileDocument, UpdateProfileParams } from '@dereekb/demo-firebase';
import { DemoUpdateModelfunction } from '../function';
import { profileForUser } from './profile.util';
export const updateProfile: DemoUpdateModelfunction<UpdateProfileParams> = async (nest, data, context) => {
const updateProfile = await nest.profileActions.updateProfile(data);
const uid = context.auth.uid;
let profileDocument: ProfileDocument;
if (updateProfile.params.key != null) {
profileDocument = await nest.useModel('profile', {
context,
key: updateProfile.params.key,
roles: 'read',
use: (x) => x.document
});
// Alternative way using model() chain
/*
profileDocument = await nest.model(context)('profile')(updateProfile.params.key)('read')((x) => {
return x.document;
});
*/
} else {
profileDocument = profileForUser(nest, uid);
}
await updateProfile(profileDocument);
};
|
// sherpa_41's Canvas renderer, licensed under MIT. (c) hafiz, 2018
#ifndef RENDERER_CANVAS_HPP
#define RENDERER_CANVAS_HPP
#include "display.hpp"
#include "renderer/renderer.hpp"
#include <array>
/**
* The Canvas is a rendering scheme designed for image rasterization,
* particularly into PNG or JPG formats. It renders a Layout tree hierarchically
* into an array of pixels, each pixel composed of an RGBA color value.
*/
class Canvas : public Renderer {
public:
/**
* Creates blank canvas of a width and height
* @param width canvas width
* @param height canvas height
*/
Canvas(uint64_t width, uint64_t height);
/**
* Creates a canvas from a root box and a specified frame width/height
* @param root box to start drawing from
* @param frame width and height to draw in
*/
Canvas(const Layout::BoxPtr & root, const Layout::Rectangle & frame);
/**
* Default dtor
*/
~Canvas() override = default;
/**
* Renders a Rectangle Command
* @param cmd command to paint
*/
void render(const Display::RectangleCmd & cmd) override;
/**
* Returns vector of RGBA pixels representing the Canvas
* @return pixels
*/
std::vector<uint8_t> getPixels() const;
private:
/**
* A ColorValue-like struct that only deals with channels in [0, 1] for
* blending purposes.
*/
struct RGBA {
RGBA() = default;
/**
* Creates an RGBA from color channels
* @param r red channel
* @param g green channel
* @param b blue channel
* @param a alpha channel
*/
RGBA(double r, double g, double b, double a);
/**
* Creates an RGBA from a ColorValue
* @param color ColorValue to convert
*/
explicit RGBA(const CSS::ColorValue & color);
/**
* Returns an array of RGBA channels
* @return RGBA color channels
*/
std::array<double, 4> channels() const;
double r, g, b, a;
};
typedef std::vector<RGBA> PxVector;
/**
* Sets a pixel by blending a color with the background
* @param location pixel to color
* @param fg foreground color to apply to pixel
*/
void setPixel(uint64_t location, const RGBA & fg);
/**
* Converts a start location to a pixel position on the canvas
* @param x location to convert
* @param min min bound
* @param max max bound
* @return converted location, bounded by canvas size
*/
uint64_t toPx(double x, uint64_t min, uint64_t max);
uint64_t width, height;
PxVector pixels;
};
#endif |
def start():
setup_logging()
logger = logging.getLogger("main")
try:
datastore_choices = get_datastore_choices()
except Exception as e:
logger.exception("Failed to instantiate datastore")
sys.exit(1)
if not datastore_choices :
logger.error("No datastores found! Exiting...")
sys.exit(1)
parser = get_base_argparser('Analyze the given URI. An URI can be a checked out directory. If URI is omitted, '
'the current working directory will be used as a checked out directory.', '1.0.0')
parser.add_argument('-D', '--db-driver', help='Output database driver. Currently only mongoDB is supported',
default='mongo', choices=datastore_choices)
parser.add_argument('-d', '--log-level', help='Debug level', choices=['INFO', 'DEBUG', 'WARNING', 'ERROR'],
default='INFO')
parser.add_argument('-n', '--project-name', help='Name of the project, that is analyzed', required=True)
parser.add_argument('--path', help='Path to the checked out repository directory', default=os.getcwd(),
type=readable_dir)
parser.add_argument('--cores-per-job', help='Number of cores to use', default=4, type=int)
logger.info("Reading out config from command line")
try:
args = parser.parse_args()
except Exception as e:
logger.error(e)
sys.exit(1)
read_config = Config(args)
logger.debug('Read the following config: %s' % read_config)
Application(read_config) |
Bryan Price doesn’t believe in limiting pitchers. That much is clear based on his response to a question I posed during last week’s Winter Meetings. I asked the Cincinnati Reds manager — and former minor- and major-league pitching coach — if there are any changes he’d like to see in the way the organization develops pitchers.
I expected a more cautious answer than I received. Rather than pussyfoot, Price proffered a strong opinion. The way he sees it, babying pitchers in the minor leagues compromises their ability to work deep into games once they reach Cincinnati. Not only that, it can hinder their chances of becoming a top-notch starter.
Note: Price’s comments, which were delivered in a group setting, have been edited for clarity and continuity.
———
Bryan Price on developing pitchers: “The big challenge for me, personally, is a world where we want pitchers to throw less. I think they need to throw more. And not just necessarily bulk innings; I think pitchers need to throw more on the side. We have pitchers come through our system who throw bullpen sides of 25 to 30 pitches when we get them. I would like to see them have a bigger workload on their side days. I would like to see some of them throw twice between starts. I would like to see us build our starting pitchers to where they can carry a heavier workload in the minor leagues.
“We had Anthony DeSclafani complete a game in Arizona, in August. It was his first complete game in professional baseball. That, to me, is unheard of. And it’s not his fault. It’s the fault of this whole group of people that feel like we have to put these kids in a bubble.
“The injury rates aren’t going down with the amount of pitches, and innings, being lessened. That’s not happening. We’re still having our best pitchers have surgeries and miss time. It has not been proven that workload is a direct factor. I’d like to see our guys take on more of a workload.
“We have always used our common sense in this game. If you’ve got a minor-league pitcher who goes out and throws a 120-pitch complete game, you’re not going to let him throw another 120-pitch complete game the next time out. You might cut him back to five or six innings and 80 or 85 pitches. But we pay these guys a lot of money to play baseball — as a starting pitcher you’re going to make $8 million or $10 million or $12 million or $20 million — so you better be out there a lot.
“That was the beauty of Johnny Cueto — he pitched until the game was over if he was throwing the ball well. I would like to see more of that in the game because eventually the relievers are going to be the guys that are eating up all the innings. Those career spans are going to shorten. You can’t ask relievers to throw 125-150 innings, which is the way the game is headed if we start using these multiple-inning closers and setup guys with too much frequency.
“I understand the numbers going up [each time a pitcher goes through the order]. I understand that. But in my opinion, until you allow your young guys to pitch in innings seven, eight and nine, they will never be able to do that. You have to allow them to go through that order.
“Clayton Kershaw isn’t Clayton Kershaw because the Dodgers said, ‘You know what, the third time through the lineup we have to get him out of there.’ He doesn’t become Clayton Kershaw unless he’s allowed to become Clayton Kershaw.
“There are going to be guys that are 90-pitch, five- or six-inning starters. No question about that. The game defines that, an organization defines that. But we’re putting too many limitations on the young pitcher to ever define if he’s capable of being Clayton Kershaw, or the next version of him. Or any other pitcher, like an Adam Wainwright —guys that have logged innings. We’re turning them all into six-inning pitchers and I don’t agree with it. Doesn’t mean I’m right, but I can tell you, I don’t agree with it.” |
#pragma once
#include "VGMInstrSet.h"
#include "VGMSampColl.h"
#include "VGMRgn.h"
#include "NinSnesFormat.h"
// ****************
// NinSnesInstrSet
// ****************
class NinSnesInstrSet:
public VGMInstrSet {
public:
NinSnesInstrSet(RawFile *file,
NinSnesVersion ver,
uint32_t offset,
uint32_t spcDirAddr,
const std::wstring &name = L"NinSnesInstrSet");
virtual ~NinSnesInstrSet(void);
virtual bool GetHeaderInfo();
virtual bool GetInstrPointers();
NinSnesVersion version;
uint16_t konamiTuningTableAddress;
uint8_t konamiTuningTableSize;
protected:
uint32_t spcDirAddr;
std::vector<uint8_t> usedSRCNs;
};
// *************
// NinSnesInstr
// *************
class NinSnesInstr
: public VGMInstr {
public:
NinSnesInstr(VGMInstrSet *instrSet,
NinSnesVersion ver,
uint32_t offset,
uint32_t theBank,
uint32_t theInstrNum,
uint32_t spcDirAddr,
const std::wstring &name = L"NinSnesInstr");
virtual ~NinSnesInstr(void);
virtual bool LoadInstr();
static bool IsValidHeader
(RawFile *file, NinSnesVersion version, uint32_t addrInstrHeader, uint32_t spcDirAddr, bool validateSample);
static uint32_t ExpectedSize(NinSnesVersion version);
NinSnesVersion version;
uint16_t konamiTuningTableAddress;
uint8_t konamiTuningTableSize;
protected:
uint32_t spcDirAddr;
};
// ***********
// NinSnesRgn
// ***********
class NinSnesRgn
: public VGMRgn {
public:
NinSnesRgn(NinSnesInstr *instr,
NinSnesVersion ver,
uint32_t offset,
uint16_t konamiTuningTableAddress = 0,
uint8_t konamiTuningTableSize = 0);
virtual ~NinSnesRgn(void);
virtual bool LoadRgn();
NinSnesVersion version;
};
|
/**
* Calculate consumes produces.
*
* @param method the method
*/
public void calculateConsumesProduces(Method method) {
PostMapping reqPostMappingMethod = AnnotatedElementUtils.findMergedAnnotation(method, PostMapping.class);
if (reqPostMappingMethod != null) {
fillMethods(reqPostMappingMethod.produces(), reqPostMappingMethod.consumes(), reqPostMappingMethod.headers());
return;
}
GetMapping reqGetMappingMethod = AnnotatedElementUtils.findMergedAnnotation(method, GetMapping.class);
if (reqGetMappingMethod != null) {
fillMethods(reqGetMappingMethod.produces(), reqGetMappingMethod.consumes(), reqGetMappingMethod.headers());
return;
}
DeleteMapping reqDeleteMappingMethod = AnnotatedElementUtils.findMergedAnnotation(method, DeleteMapping.class);
if (reqDeleteMappingMethod != null) {
fillMethods(reqDeleteMappingMethod.produces(), reqDeleteMappingMethod.consumes(), reqDeleteMappingMethod.headers());
return;
}
PutMapping reqPutMappingMethod = AnnotatedElementUtils.findMergedAnnotation(method, PutMapping.class);
if (reqPutMappingMethod != null) {
fillMethods(reqPutMappingMethod.produces(), reqPutMappingMethod.consumes(), reqPutMappingMethod.headers());
return;
}
RequestMapping reqMappingMethod = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
RequestMapping reqMappingClass = AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), RequestMapping.class);
if (reqMappingMethod != null && reqMappingClass != null) {
fillMethods(ArrayUtils.addAll(reqMappingMethod.produces(), reqMappingClass.produces()), ArrayUtils.addAll(reqMappingMethod.consumes(), reqMappingClass.consumes()), reqMappingMethod.headers());
}
else if (reqMappingMethod != null) {
fillMethods(reqMappingMethod.produces(), reqMappingMethod.consumes(), reqMappingMethod.headers());
}
else if (reqMappingClass != null) {
fillMethods(reqMappingClass.produces(), reqMappingClass.consumes(), reqMappingClass.headers());
}
else
fillMethods(methodProduces, methodConsumes, null);
} |
/**
* @author Ravi Mohan
*
*/
public class EightPuzzleBoardMoveTest extends TestCase {
EightPuzzleBoard board;
@Override
public void setUp() {
board = new EightPuzzleBoard(new int[] { 0, 5, 4, 6, 1, 8, 7, 3, 2 });
}
// Position 1
public void testPosition1Movabilty() {
assertEquals(false, board.canMoveGap(EightPuzzleBoard.UP));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.DOWN));
assertEquals(false, board.canMoveGap(EightPuzzleBoard.LEFT));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.RIGHT));
}
public void testPosition1MoveUp() {
board.moveGapUp();
assertEquals(new EightPuzzleBoard(
new int[] { 0, 5, 4, 6, 1, 8, 7, 3, 2 }), board);
}
public void testPosition1MoveDown() {
board.moveGapDown();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 0, 1, 8, 7, 3, 2 }), board);
}
public void testPosition1MoveLeft() {
board.moveGapLeft();
assertEquals(new EightPuzzleBoard(
new int[] { 0, 5, 4, 6, 1, 8, 7, 3, 2 }), board);
}
public void testPosition1MoveRight() {
board.moveGapRight();
assertEquals(new EightPuzzleBoard(
new int[] { 5, 0, 4, 6, 1, 8, 7, 3, 2 }), board);
}
// Position 2
public void testPosition2Movabilty() {
setGapToPosition2();
assertEquals(false, board.canMoveGap(EightPuzzleBoard.UP));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.DOWN));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.LEFT));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.RIGHT));
}
public void testPosition2MoveUp() {
// { 5, 0, 4, 6, 1, 8, 7, 3, 2 }
setGapToPosition2();
board.moveGapUp();
assertEquals(new EightPuzzleBoard(
new int[] { 5, 0, 4, 6, 1, 8, 7, 3, 2 }), board);
}
public void testPosition2MoveDown() {
// { 5, 0, 4, 6, 1, 8, 7, 3, 2 }
setGapToPosition2();
board.moveGapDown();
assertEquals(new EightPuzzleBoard(
new int[] { 5, 1, 4, 6, 0, 8, 7, 3, 2 }), board);
}
public void testPosition2MoveLeft() {
// { 5, 0, 4, 6, 1, 8, 7, 3, 2 }
setGapToPosition2();
board.moveGapLeft();
assertEquals(new EightPuzzleBoard(
new int[] { 0, 5, 4, 6, 1, 8, 7, 3, 2 }), board);
}
public void testPosition2MoveRight() {
// { 5, 0, 4, 6, 1, 8, 7, 3, 2 }
setGapToPosition2();
board.moveGapRight();
assertEquals(new EightPuzzleBoard(
new int[] { 5, 4, 0, 6, 1, 8, 7, 3, 2 }), board);
}
// Position 3
public void testPosition3Movabilty() {
setGapToPosition3();
assertEquals(false, board.canMoveGap(EightPuzzleBoard.UP));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.DOWN));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.LEFT));
assertEquals(false, board.canMoveGap(EightPuzzleBoard.RIGHT));
}
public void testPosition3MoveUp() {
// { 5, 4, 0, 6, 1, 8, 7, 3, 2 }
setGapToPosition3();
board.moveGapUp();
assertEquals(new EightPuzzleBoard(
new int[] { 5, 4, 0, 6, 1, 8, 7, 3, 2 }), board);
}
public void testPosition3MoveDown() {
// { 5, 4, 0, 6, 1, 8, 7, 3, 2 }
setGapToPosition3();
board.moveGapDown();
assertEquals(new EightPuzzleBoard(
new int[] { 5, 4, 8, 6, 1, 0, 7, 3, 2 }), board);
}
public void testPosition3MoveLeft() {
// { 5, 4, 0, 6, 1, 8, 7, 3, 2 }
setGapToPosition3();
board.moveGapLeft();
assertEquals(new EightPuzzleBoard(
new int[] { 5, 0, 4, 6, 1, 8, 7, 3, 2 }), board);
}
public void testPosition3MoveRight() {
// { 5, 4, 0, 6, 1, 8, 7, 3, 2 }
setGapToPosition3();
board.moveGapRight();
assertEquals(new EightPuzzleBoard(
new int[] { 5, 4, 0, 6, 1, 8, 7, 3, 2 }), board);
}
// Position 4
public void testPosition4Movabilty() {
setGapToPosition4();
assertEquals(true, board.canMoveGap(EightPuzzleBoard.UP));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.DOWN));
assertEquals(false, board.canMoveGap(EightPuzzleBoard.LEFT));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.RIGHT));
}
public void testPosition4MoveUp() {
// { 6, 5, 4, 0, 1, 8, 7, 3, 2 }
setGapToPosition4();
board.moveGapUp();
assertEquals(new EightPuzzleBoard(
new int[] { 0, 5, 4, 6, 1, 8, 7, 3, 2 }), board);
}
public void testPosition4MoveDown() {
// { 6, 5, 4, 0, 1, 8, 7, 3, 2 }
setGapToPosition4();
board.moveGapDown();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 0, 3, 2 }), board);
}
public void testPosition4MoveLeft() {
// { 6, 5, 4, 0, 1, 8, 7, 3, 2 }
setGapToPosition4();
board.moveGapLeft();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 0, 1, 8, 7, 3, 2 }), board);
}
public void testPosition4MoveRight() {
// { 6, 5, 4, 0, 1, 8, 7, 3, 2 }
setGapToPosition4();
board.moveGapRight();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 1, 0, 8, 7, 3, 2 }), board);
}
// Position 5
public void testPosition5Movabilty() {
setGapToPosition5();
assertEquals(true, board.canMoveGap(EightPuzzleBoard.UP));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.DOWN));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.LEFT));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.RIGHT));
}
public void testPosition5MoveUp() {
// { 6, 5, 4, 1, 0, 8, 7, 3, 2 }
setGapToPosition5();
board.moveGapUp();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 0, 4, 1, 5, 8, 7, 3, 2 }), board);
}
public void testPosition5MoveDown() {
// { 6, 5, 4, 1, 0, 8, 7, 3, 2 }
setGapToPosition5();
board.moveGapDown();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 1, 3, 8, 7, 0, 2 }), board);
}
public void testPosition5MoveLeft() {
// { 6, 5, 4, 1, 0, 8, 7, 3, 2 }
setGapToPosition5();
board.moveGapLeft();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 0, 1, 8, 7, 3, 2 }), board);
}
public void testPosition5MoveRight() {
// { 6, 5, 4, 1, 0, 8, 7, 3, 2 }
setGapToPosition5();
board.moveGapRight();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 1, 8, 0, 7, 3, 2 }), board);
}
// Position 6
public void testPosition6Movabilty() {
setGapToPosition6();
assertEquals(true, board.canMoveGap(EightPuzzleBoard.UP));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.DOWN));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.LEFT));
assertEquals(false, board.canMoveGap(EightPuzzleBoard.RIGHT));
}
public void testPosition6MoveUp() {
// { 6, 5, 4, 1, 8, 0, 7, 3, 2 }
setGapToPosition6();
board.moveGapUp();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 0, 1, 8, 4, 7, 3, 2 }), board);
}
public void testPosition6MoveDown() {
// { 6, 5, 4, 1, 8, 0, 7, 3, 2 }
setGapToPosition6();
board.moveGapDown();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 1, 8, 2, 7, 3, 0 }), board);
}
public void testPosition6MoveLeft() {
// { 6, 5, 4, 1, 8, 0, 7, 3, 2 }
setGapToPosition6();
board.moveGapLeft();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 1, 0, 8, 7, 3, 2 }), board);
}
public void testPosition6MoveRight() {
// { 6, 5, 4, 1, 8, 0, 7, 3, 2 }
setGapToPosition6();
board.moveGapRight();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 1, 8, 0, 7, 3, 2 }), board);
}
// Position 7
public void testPosition7Movabilty() {
setGapToPosition7();
assertEquals(true, board.canMoveGap(EightPuzzleBoard.UP));
assertEquals(false, board.canMoveGap(EightPuzzleBoard.DOWN));
assertEquals(false, board.canMoveGap(EightPuzzleBoard.LEFT));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.RIGHT));
}
public void testPosition7MoveUp() {
// { 6, 5, 4, 7, 1, 8, 0, 3, 2 }
setGapToPosition7();
board.moveGapUp();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 0, 1, 8, 7, 3, 2 }), board);
}
public void testPosition7MoveDown() {
// { 6, 5, 4, 7, 1, 8, 0, 3, 2 }
setGapToPosition7();
board.moveGapDown();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 0, 3, 2 }), board);
}
public void testPosition7MoveLeft() {
// { 6, 5, 4, 7, 1, 8, 0, 3, 2 }
setGapToPosition7();
board.moveGapLeft();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 0, 3, 2 }), board);
}
public void testPosition7MoveRight() {
// { 6, 5, 4, 7, 1, 8, 0, 3, 2 }
setGapToPosition7();
board.moveGapRight();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 3, 0, 2 }), board);
}
// Position 8
public void testPosition8Movabilty() {
setGapToPosition8();
assertEquals(true, board.canMoveGap(EightPuzzleBoard.UP));
assertEquals(false, board.canMoveGap(EightPuzzleBoard.DOWN));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.LEFT));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.RIGHT));
}
public void testPosition8MoveUp() {
// { 6, 5, 4, 7, 1, 8, 3, 0, 2 }
setGapToPosition8();
board.moveGapUp();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 0, 8, 3, 1, 2 }), board);
}
public void testPosition8MoveDown() {
// { 6, 5, 4, 7, 1, 8, 3, 0, 2 }
setGapToPosition8();
board.moveGapDown();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 3, 0, 2 }), board);
}
public void testPosition8MoveLeft() {
// { 6, 5, 4, 7, 1, 8, 3, 0, 2 }
setGapToPosition8();
board.moveGapLeft();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 0, 3, 2 }), board);
}
public void testPosition8MoveRight() {
// { 6, 5, 4, 7, 1, 8, 3, 0, 2 }
setGapToPosition8();
board.moveGapRight();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 3, 2, 0 }), board);
}
// Position 9
public void testPosition9Movabilty() {
setGapToPosition9();
assertEquals(true, board.canMoveGap(EightPuzzleBoard.UP));
assertEquals(false, board.canMoveGap(EightPuzzleBoard.DOWN));
assertEquals(true, board.canMoveGap(EightPuzzleBoard.LEFT));
assertEquals(false, board.canMoveGap(EightPuzzleBoard.RIGHT));
}
public void testPosition9MoveUp() {
// { 6, 5, 4, 7, 1, 8, 3, 2, 0 }
setGapToPosition9();
board.moveGapUp();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 0, 3, 2, 8 }), board);
}
public void testPosition9MoveDown() {
// { 6, 5, 4, 7, 1, 8, 3, 2, 0 }
setGapToPosition9();
board.moveGapDown();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 3, 2, 0 }), board);
}
public void testPosition9MoveLeft() {
// { 6, 5, 4, 7, 1, 8, 3, 2, 0 }
setGapToPosition9();
board.moveGapLeft();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 3, 0, 2 }), board);
}
public void testPosition9MoveRight() {
// { 6, 5, 4, 7, 1, 8, 3, 2, 0 }
setGapToPosition9();
board.moveGapRight();
assertEquals(new EightPuzzleBoard(
new int[] { 6, 5, 4, 7, 1, 8, 3, 2, 0 }), board);
}
public void setGapToPosition2() {
board.moveGapRight();
}
public void setGapToPosition3() {
board.moveGapRight();
board.moveGapRight();
}
public void setGapToPosition4() {
board.moveGapDown();
}
public void setGapToPosition5() {
// { 6, 5, 4, 1, 0, 8, 7, 3, 2 }
board.moveGapDown();
board.moveGapRight();
}
public void setGapToPosition6() {
// { 6, 5, 4, 1, 8, 0, 7, 3, 2 }
board.moveGapDown();
board.moveGapRight();
board.moveGapRight();
}
public void setGapToPosition7() {
// { 6, 5, 4, 7, 1, 8, 0, 3, 2 }
board.moveGapDown();
board.moveGapDown();
}
public void setGapToPosition8() {
// { 6, 5, 4, 7, 1, 8, 3, 0, 2 }
board.moveGapDown();
board.moveGapDown();
board.moveGapRight();
}
public void setGapToPosition9() {
// { 6, 5, 4, 7, 1, 8, 3, 2, 0 }
board.moveGapDown();
board.moveGapDown();
board.moveGapRight();
board.moveGapRight();
}
} |
<filename>Biz.WebApp/Scripts/App/Calendar/Mediator.ts
namespace Biz.WebApp.ThreePane {
export class Mediator {
}
} |
package marcguillem.dev.Commands;
import marcguillem.dev.Services.ConfigurationService;
import marcguillem.dev.Services.MessageService;
import org.json.JSONArray;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import java.util.concurrent.Callable;
@Command(
name = "set-configuration",
description = "Set the access and secret AWS keys. For more information use set-configuration --help"
)
public class SetConfigurationCommand implements Callable<Integer> {
private static final String[] regions = {"us-east-1", "us-east-2", "us-west-1", "us-west-2", "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "ap-northeast-1", "ap-northeast-2", "ap-southeast-1", "ap-southeast-2", "ap-south-1", "ca-central-1", "sa-east-1"};
@Option(
names = "--awsAccessKey",
description = "AWS Access Key."
)
private String awsAccessKey;
@Option(
names = "--awsSecretKey",
description = "AWS Secret Key."
)
private String awsSecretKey;
@Option(
names = "--awsRegion",
description = "AWS Region."
)
private String awsRegion;
@Option(
names = {"-h", "--help"},
description = "Display help message",
usageHelp = true
)
private boolean usageHelp;
@Override
public Integer call() throws Exception {
try {
if (awsAccessKey != null) {
ConfigurationService.saveConfiguration(awsAccessKey, null, null);
MessageService.displayGreenMessage("AWS Access Key saved!", true);
}
if (awsSecretKey != null) {
ConfigurationService.saveConfiguration(null, awsSecretKey, null);
MessageService.displayGreenMessage("AWS Secret Key saved!", true);
}
if (awsRegion != null) {
if (!isValidRegion(awsRegion)) {
MessageService.displayRedMessage("AWS Region " + awsRegion + " is not present in the list of valid regions. Please check the AWS documentation. ", true);
MessageService.displayYellowMessage("Valid regions are: ", false);
MessageService.displayGreenMessage(new JSONArray(regions).toString(), true);
MessageService.displayYellowMessage("Saving the AWS Region anyway...", true);
}
ConfigurationService.saveConfiguration(null, null, awsRegion);
MessageService.displayGreenMessage("AWS Region saved!", true);
}
if (awsSecretKey == null && awsAccessKey == null && awsRegion == null) {
MessageService.displayYellowMessage("No options specified, exiting with no changes...", true);
}
return 0;
} catch (Exception error) {
MessageService.displayRedMessage(error.getMessage(), true);
return 1;
}
}
// Check if given string is a valid AWS Region
private static boolean isValidRegion(String region) {
for (String r : regions) {
if (r.equalsIgnoreCase(region)) {
return true;
}
}
return false;
}
}
|
def _smesolve_generic(sso, options, progress_bar):
if debug:
logger.debug(inspect.stack()[0][3])
sso.N_store = len(sso.times)
sso.N_substeps = sso.nsubsteps
sso.dt = (sso.times[1] - sso.times[0]) / sso.N_substeps
nt = sso.ntraj
data = Result()
data.solver = "smesolve"
data.times = sso.times
data.expect = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex)
data.ss = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex)
data.noise = []
data.measurement = []
sso.L = liouvillian(sso.H, sso.c_ops)
sso.A_ops = sso.generate_A_ops(sso.sc_ops, sso.L.data, sso.dt)
sso.s_e_ops = [spre(e) for e in sso.e_ops]
if sso.m_ops:
sso.s_m_ops = [[spre(m) if m else None for m in m_op]
for m_op in sso.m_ops]
else:
sso.s_m_ops = [[spre(c) for _ in range(sso.d2_len)]
for c in sso.sc_ops]
map_kwargs = {'progress_bar': progress_bar}
map_kwargs.update(sso.map_kwargs)
task = _smesolve_single_trajectory
task_args = (sso,)
task_kwargs = {}
results = sso.map_func(task, list(range(sso.ntraj)),
task_args, task_kwargs, **map_kwargs)
for result in results:
states_list, dW, m, expect, ss = result
data.states.append(states_list)
data.noise.append(dW)
data.measurement.append(m)
data.expect += expect
data.ss += ss
if options.average_states and np.any(data.states):
data.states = [sum([data.states[mm][n] for mm in range(nt)]).unit()
for n in range(len(data.times))]
data.expect = data.expect / nt
if nt > 1:
data.se = (data.ss - nt * (data.expect ** 2)) / (nt * (nt - 1))
else:
data.se = None
data.expect = [np.real(data.expect[n, :])
if e.isherm else data.expect[n, :]
for n, e in enumerate(sso.e_ops)]
return data |
package org.broadinstitute.dropseqrna.utils;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.testng.annotations.Test;
import junit.framework.Assert;
public class ObjectCounterTest {
@Test
public void test() {
ObjectCounter<String> o = new ObjectCounter<>();
o.increment("FOO");
o.incrementByCount("BAR", 4);
ObjectCounter<String> o2 = new ObjectCounter<>();
o2.increment("ZOO");
o2.incrementByCount("ZAR", 4);
ObjectCounter<String> both = new ObjectCounter<>(o);
both.increment(o2);
both.decrement("BAR"); // now 3.
both.decrementByCount("ZAR", 2); // now 2.
Set<String> expectedKeys = new HashSet<>(Arrays.asList("FOO", "BAR", "ZOO", "ZAR"));
Assert.assertEquals(expectedKeys, both.getKeys());
List<String> expectedOrderedKeys = Arrays.asList("BAR", "ZAR", "FOO", "ZOO");
List<String> orderedKeys = both.getKeysOrderedByCount(true);
Assert.assertEquals(expectedOrderedKeys, orderedKeys);
// notice keys are ordered by natural order when there are ties to counts in FOO and ZOO.
List<String> expectedOrderedKeys2 = Arrays.asList( "FOO", "ZOO", "ZAR", "BAR");
List<String> orderedKeys2 = both.getKeysOrderedByCount(false);
Assert.assertEquals(expectedOrderedKeys2, orderedKeys2);
Assert.assertSame(4, both.getSize());
Assert.assertSame(3, both.getCountForKey("BAR"));
Assert.assertSame(7, both.getTotalCount());
Assert.assertSame(2, both.getNumberOfSize(1));
Assert.assertEquals("BAR", both.getMode()); // bar is the most common, AKA the highest count.
both.increment("ZOO");
Assert.assertEquals("FOO", both.getMin());
both.filterByMinCount(2);
Assert.assertSame(3, both.getSize());
Assert.assertTrue (both.hasKey("ZOO"));
Assert.assertFalse (both.hasKey("ZOOPPP"));
both.setCount("ZOOPPP", 8);
Assert.assertSame(8, both.getCountForKey("ZOOPPP"));
both.remove("ZOOPPP");
Assert.assertSame(0, both.getCountForKey("ZOOPPP"));
String expected = "{BAR=3, ZAR=2, ZOO=2}";
String actual = both.toString();
Assert.assertEquals(expected, actual);
both.clear();
Assert.assertSame(0, both.getCounts().size());
}
@Test
public void testSubset () {
ObjectCounter<String> o = new ObjectCounter<>();
o.increment("FOO");
o.incrementByCount("BAR", 4);
o.increment("ZOO");
o.incrementByCount("ZAR", 4);
Set<String> subsetKeys = new HashSet<> (Arrays.asList("FOO", "ZOO", "MOO"));
o.subset(subsetKeys);
for (String k: o.getKeys())
Assert.assertTrue(subsetKeys.contains(k));
}
}
|
/**
* Code to populate a global Gui object with all the widgets
* of Guichan.
*/
namespace widgets
{
gcn::ImageFont* font;
gcn::Container* top;
gcn::Label* label;
gcn::Icon* icon;
gcn::Button* button;
gcn::TextField* textField;
gcn::TextBox* textBox;
gcn::ScrollArea* textBoxScrollArea;
gcn::ListBox* listBox;
gcn::DropDown* dropDown;
gcn::CheckBox* checkBox1;
gcn::CheckBox* checkBox2;
gcn::RadioButton* radioButton1;
gcn::RadioButton* radioButton2;
gcn::RadioButton* radioButton3;
gcn::Slider* slider;
gcn::Image *image;
gcn::Window *window;
gcn::Image *darkbitsImage;
gcn::Icon* darkbitsIcon;
gcn::TabbedArea* tabbedArea;
gcn::Button* tabOneButton;
gcn::CheckBox* tabTwoCheckBox;
/*
* List boxes and drop downs need an instance of a list model
* in order to display a list.
*/
class DemoListModel : public gcn::ListModel
{
public:
int getNumberOfElements()
{
return 5;
}
std::string getElementAt(int i)
{
switch(i)
{
case 0:
return std::string("zero");
case 1:
return std::string("one");
case 2:
return std::string("two");
case 3:
return std::string("three");
case 4:
return std::string("four");
default: // Just to keep warnings away
return std::string("");
}
}
};
DemoListModel demoListModel;
/**
* Initialises the widgets example by populating the global Gui
* object.
*/
void init()
{
// We first create a container to be used as the top widget.
// The top widget in Guichan can be any kind of widget, but
// in order to make the Gui contain more than one widget we
// make the top widget a container.
top = new gcn::Container();
// We set the dimension of the top container to match the screen.
top->setDimension(gcn::Rectangle(0, 0, 640, 480));
// Finally we pass the top widget to the Gui object.
globals::gui->setTop(top);
// Now we load the font used in this example.
font = new gcn::ImageFont("fixedfont.bmp", " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
// Widgets may have a global font so we don't need to pass the
// font object to every created widget. The global font is static.
gcn::Widget::setGlobalFont(font);
// Now we create the widgets
label = new gcn::Label("Label");
image = gcn::Image::load("gui-chan.bmp");
icon = new gcn::Icon(image);
button = new gcn::Button("Button");
textField = new gcn::TextField("Text field");
textBox = new gcn::TextBox("Multiline\nText box");
textBoxScrollArea = new gcn::ScrollArea(textBox);
textBoxScrollArea->setWidth(200);
textBoxScrollArea->setHeight(100);
textBoxScrollArea->setFrameSize(1);
listBox = new gcn::ListBox(&demoListModel);
listBox->setFrameSize(1);
dropDown = new gcn::DropDown(&demoListModel);
checkBox1 = new gcn::CheckBox("Checkbox 1");
checkBox2 = new gcn::CheckBox("Checkbox 2");
radioButton1 = new gcn::RadioButton("RadioButton 1", "radiogroup", true);
radioButton2 = new gcn::RadioButton("RadioButton 2", "radiogroup");
radioButton3 = new gcn::RadioButton("RadioButton 3", "radiogroup");
slider = new gcn::Slider(0, 10);
slider->setSize(100, 10);
window = new gcn::Window("I am a window Drag me");
window->setBaseColor(gcn::Color(255, 150, 200, 190));
darkbitsImage = gcn::Image::load("darkbitslogo_by_haiko.bmp");
darkbitsIcon = new gcn::Icon(darkbitsImage);
window->add(darkbitsIcon);
window->resizeToContent();
tabbedArea = new gcn::TabbedArea();
tabbedArea->setSize(200, 100);
tabOneButton = new gcn::Button("A button in tab 1");
tabbedArea->addTab("Tab 1", tabOneButton);
tabTwoCheckBox = new gcn::CheckBox("A check box in tab 2");
tabbedArea->addTab("Tab 2", tabTwoCheckBox);
// Now it's time to add the widgets to the top container
// so they will be conected to the GUI.
top->add(label, 10, 10);
top->add(icon, 10, 30);
top->add(button, 200, 10);
top->add(textField, 250, 10);
top->add(textBoxScrollArea, 200, 50);
top->add(listBox, 200, 200);
top->add(dropDown, 500, 10);
top->add(checkBox1, 500, 130);
top->add(checkBox2, 500, 150);
top->add(radioButton1, 500, 200);
top->add(radioButton2, 500, 220);
top->add(radioButton3, 500, 240);
top->add(slider, 500, 300);
top->add(window, 50, 350);
top->add(tabbedArea, 400, 350);
}
/**
* Halts the widgets example.
*/
void halt()
{
delete font;
delete top;
delete label;
delete icon;
delete button;
delete textField;
delete textBox;
delete textBoxScrollArea;
delete listBox;
delete dropDown;
delete checkBox1;
delete checkBox2;
delete radioButton1;
delete radioButton2;
delete radioButton3;
delete slider;
delete window;
delete darkbitsIcon;
delete darkbitsImage;
delete tabbedArea;
delete tabOneButton;
delete tabTwoCheckBox;
}
}
|
package notifychannel
import (
"fmt"
"os"
)
// StdOutNotifyChannel is a notify channel that prints out every
// notification to stdout. Mostly used for debugging
type StdOutNotifyChannel struct {
}
func (StdOutNotifyChannel) Send(person string) error {
_, err := fmt.Fprintln(os.Stdout, person)
return err
}
func (StdOutNotifyChannel) Shutdown() error {
return os.Stdout.Close()
}
|
Marc Jacobs Beauty Holiday 2014 Collection
Availability: Early access at Marc Jacobs Beauty; coming soon to Sephora
La Coquette Collection ($55.00) (Limited Edition)
Create a classic Parisienne look with this set of Marc’s most covetable items. With a Magic Marc’er liquid eyeliner in Blacquer, the perfect nude nail polish, and a shimmering lip gloss for pink pout, you’ll be ready for a night of magic. This set also contains a signature mirror contained in a Marc Jacobs-designed pochette. The perfect gift for someone special or for yourself.
Blacquer (Magic Mar’cer Precision Pen Eyeliner)
(Magic Mar’cer Precision Pen Eyeliner) Kissability (Lust for Lacquer Sheer Lip Vinyl)
(Lust for Lacquer Sheer Lip Vinyl) Madame (Hi-Shine Nail Lacquer)
(Hi-Shine Nail Lacquer) Mirror (in a Pochette)
The Sky Liner Petite Highliner Collection ($45.00) (Limited Edition)
Line your eyes like never before with this dazzling assortment of 7 petite highliner gel eyeliners. Cased in a limited-edition collectible box, these perfect petites include 5 best-selling shades and 2 new limited-edition eyeliner shades. This set is centered around the signature shade of the season, “Midnight in Paris.” 7 x 0.01 oz Highliner gel crayons in O(vert) (forest green), Brown(out) (bronze with shimmer), Th(ink) (deep navy), (Plum)age (vivid purple), Blacquer (black), Sunset (golden bronze shimmer), Midnight in Paris (inky indigo blue).
O(vert)
Brown(out)
Th(ink)
(Plum)age
Blacquer
Sunset (Exclusive)
Midnight in Paris (Exclusive)
Blacquer and Bleu Eye Essentials Collection ($79.00) (Limited Edition)
Satisfy your love of dramatic eye looks with Marc’s must-haves in eyeliner and mascara, in shades of blacquer and bleu. This decadent collection inspired by the glamour of Paris and its midnight sky features 3 best-selling products contained in a makeup bag designed by Marc Jacobs. The ultimate gift for the girl who loves to shine.
Blacquer (Magic Mar’cer Precision Pen Eyeliner)
(Magic Mar’cer Precision Pen Eyeliner) Blacquer (O!Mega Lash Volumizing Mascara)
(O!Mega Lash Volumizing Mascara) Th(ink) (Highliner Gel Eyeliner Crayon)
(Highliner Gel Eyeliner Crayon) Makeup Bag by Marc Jacobs
Style Eye-Con No. 7 ($59.00)
Featuring the Limited Edition Holiday 2014 eyeshadow palette, The Parisienne. Become captivated with the super skinny, sleek design of these iconic, harmonized eyeshadows. Discover the mystery of the girl who believes in finding magic at all hours.
The Parisienne Inspired by the City of Lights (Limited Edition)
Enamored Hi-Shine Nail Lacquer ($18.00)
Midnight in Paris Inky indigo blue (Limited Edition)
LoveMarc Collection Lip Gel Set ($350.00) (Limited Edition) (Repromote)
Experience true luxury when you open the stylishly sleek Lovemarc Lipstick Collection, a collector’s edition. Enclosed in a lacquered jewelry box, you’ll find 12 shiny-black Lovemarc lipsticks aligned like piano keys, and the center of attention, Marc’s realized vision of the perfect red—Showstopper. From the mysterious Moody Margot, to provocative Little Pretty, discover the variety of true glamour and fall in love with a new lipstick shade each day.
Availability: Early access at Marc Jacobs Beauty; coming soon to Sephora
See more photos!
Marc Jacobs Beauty Holiday 2014 Collection
Marc Jacobs Beauty Holiday 2014 Collection
Marc Jacobs Beauty Holiday 2014 Collection
Marc Jacobs Beauty Holiday 2014 Collection
Marc Jacobs Beauty Holiday 2014 Collection
Marc Jacobs Beauty Holiday 2014 Collection
Marc Jacobs Beauty Holiday 2014 Collection |
/*
* Copyright (c) 2012 ASMlover. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list ofconditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materialsprovided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <string.h>
#include "../inc/config.h"
#include "../inc/assert.h"
#include "../inc/memory.h"
#include "../inc/array.h"
struct lArray {
void** elements;
void** begin;
void** end;
void** end_of_storage;
};
void* array_create(int storage)
{
struct lArray* object;
NEW0(object);
if (NULL != object)
{
if (0 != storage)
{
object->elements = (void**)CALLOC(storage, sizeof(void*));
object->begin = object->elements;
object->end = object->elements + storage;
object->end_of_storage = object->end;
}
}
return object;
}
void array_release(void** A)
{
array_clear(*A);
FREE(*A);
}
int array_size(void* A)
{
return (NULL != A ? (((struct lArray*)A)->end - ((struct lArray*)A)->begin) : ERROR_LEN);
}
int array_empty(void* A)
{
return (array_begin(A) == array_end(A));
}
void array_clear(void* A)
{
if (NULL != A)
{
FREE(((struct lArray*)A)->elements);
((struct lArray*)A)->begin = ((struct lArray*)A)->elements;
((struct lArray*)A)->end = ((struct lArray*)A)->elements;
((struct lArray*)A)->end_of_storage = ((struct lArray*)A)->elements;
}
}
int array_push_back(void* A, void* x)
{
return (NULL != array_insert(A, array_end(A), x) ? RESULT_OK : RESULT_FAIL);
}
void* array_pop_back(void* A)
{
void* pop_data;
if (NULL == A)
return NULL;
--((struct lArray*)A)->end;
pop_data = *((struct lArray*)A)->end;
*((struct lArray*)A)->end = NULL;
return pop_data;
}
void* array_set(void* A, int i, void* x)
{
void* old_x;
assert(NULL != A && i >= 0 && i < array_size(A));
old_x = ((struct lArray*)A)->elements[i];
((struct lArray*)A)->elements[i] = x;
return old_x;
}
void* array_get(void* A, int i)
{
assert(NULL != A && i >= 0 && i < array_size(A));
return ((struct lArray*)A)->elements[i];
}
void* array_insert(void* A, lArrayIter pos, void* x)
{
assert(NULL != A);
if (((struct lArray*)A)->end < ((struct lArray*)A)->end_of_storage && pos == array_end(A))
{
*((struct lArray*)A)->end = x;
++((struct lArray*)A)->end;
}
else
{
if (((struct lArray*)A)->end < ((struct lArray*)A)->end_of_storage)
{
memmove(pos + 1, pos, (array_end(A) - pos) * sizeof(void*));
++((struct lArray*)A)->end;
*pos = x;
}
else
{
int old_size = ((struct lArray*)A)->end - ((struct lArray*)A)->begin;
int new_size = (0 != old_size ? 2 * old_size : 1);
void** new_elements = (void**)CALLOC(new_size, sizeof(void*));
memcpy(new_elements, ((struct lArray*)A)->elements, (pos - ((struct lArray*)A)->begin) * sizeof(void*));
*(void**)((char*)new_elements + (pos - ((struct lArray*)A)->begin) * sizeof(void*)) = x;
memcpy((char*)new_elements + (pos - ((struct lArray*)A)->begin + 1) * sizeof(void*),
((struct lArray*)A)->elements + (pos - ((struct lArray*)A)->begin) * sizeof(void*),
(((struct lArray*)A)->end - pos) * sizeof(void*));
FREE(((struct lArray*)A)->elements);
((struct lArray*)A)->elements = new_elements;
((struct lArray*)A)->begin = new_elements;
((struct lArray*)A)->end = new_elements + old_size + 1;
((struct lArray*)A)->end_of_storage = new_elements + new_size;
}
}
return x;
}
void* array_erase(void* A, lArrayIter pos)
{
void* erase_data;
assert(NULL != A && NULL != pos);
erase_data = (pos == array_end(A) ? *(pos - 1) : *pos);
if (pos + 1 < array_end(A))
memmove(pos, pos + 1, (((struct lArray*)A)->end - (pos + 1)) * sizeof(void*));
--((struct lArray*)A)->end;
*((struct lArray*)A)->end = NULL;
return erase_data;
}
void* array_remove(void* A, int i)
{
void* remove_data;
assert(NULL != A && i >= 0 && i < array_size(A));
remove_data = ((struct lArray*)A)->elements[i];
memmove(((struct lArray*)A)->begin + i, ((struct lArray*)A)->begin + i + 1,
(array_size(A) - (i + 1)) * sizeof(void*));
--((struct lArray*)A)->end;
*((struct lArray*)A)->end = NULL;
return remove_data;
}
void* array_front(void* A)
{
lArrayIter beg = array_begin(A);
return (NULL != beg ? *beg : NULL);
}
void* array_back(void* A)
{
lArrayIter end = array_end(A);
return (NULL != end ? *(end - 1) : NULL);
}
lArrayIter array_begin(void* A)
{
return (NULL != A ? (lArrayIter)(((struct lArray*)A)->begin) : NULL);
}
lArrayIter array_end(void* A)
{
return (NULL != A ? (lArrayIter)(((struct lArray*)A)->end) : NULL);
}
lArrayIter array_iter_next(lArrayIter iter)
{
return (NULL != iter ? ++iter : NULL);
}
void array_for_each(void* A, void (*visit)(void*, void*), void* arg)
{
lArrayIter beg = array_begin(A), end = array_end(A);
if (NULL == A || NULL == visit || NULL == beg)
return;
for ( ; beg != end; ++beg)
visit(*beg, arg);
}
void* array_copy(void* A, int copy_len)
{
void* copy_A;
int src_size, dest_size;
assert(NULL != A && copy_len >= 0);
copy_A = array_create(copy_len);
src_size = array_size(A);
dest_size = array_size(copy_A);
if (dest_size >= src_size && src_size > 0)
memcpy(((struct lArray*)copy_A)->elements, ((struct lArray*)A)->elements, src_size * sizeof(void*));
else if (src_size > dest_size && dest_size > 0)
memcpy(((struct lArray*)copy_A)->elements, ((struct lArray*)A)->elements, dest_size * sizeof(void*));
return copy_A;
}
void array_resize(void* A, int storage)
{
assert(NULL != A && storage >= 0);
if (0 == storage)
FREE(((struct lArray*)A)->elements);
else if (0 == array_size(A))
((struct lArray*)A)->elements = CALLOC(storage, sizeof(void*));
else
{
int n = array_size(A);
((struct lArray*)A)->elements = REALLOC(((struct lArray*)A)->elements, storage * sizeof(void*));
memset(((struct lArray*)A)->elements + n, 0, (storage - n) * sizeof(void*));
}
((struct lArray*)A)->begin = ((struct lArray*)A)->elements;
((struct lArray*)A)->end = ((struct lArray*)A)->elements + storage;
((struct lArray*)A)->end_of_storage = ((struct lArray*)A)->elements + storage;
}
|
//
// Kit's Java Utils.
//
package com.github.ewbankkit;
import org.apache.commons.lang3.mutable.MutableBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
/**
* Represents a SQL data source.
*/
public final class SqlDataSource {
private static final Logger LOGGER = LoggerFactory.getLogger(SqlDataSource.class);
private final DataSource jdbcDataSource;
public SqlDataSource(DataSource jdbcDataSource) {
this.jdbcDataSource = Objects.requireNonNull(jdbcDataSource);
}
/**
* Return whether or not the data source is valid.
*/
public boolean isValid(final int timeout) {
final MutableBoolean valid = new MutableBoolean();
ConnectionConsumer cc = connection -> {
valid.setValue(connection.isValid(timeout));
};
try {
withConnection(cc);
}
catch (SQLException ignore) {}
return valid.booleanValue();
}
/**
* Invoke the specified function with a connection.
*/
public void withConnection(final ConnectionConsumer consumer) throws SQLException {
try (Connection connection = getConnection()) {
try {
consumer.accept(connection);
}
catch (Throwable t) {
throw sqlException(t);
}
}
}
/**
* Invoke the specified function with a transaction.
*/
public void withTransaction(final ConnectionConsumer consumer) throws SQLException {
try (Connection connection = getConnection()) {
try {
consumer.accept(connection);
if (!connection.getAutoCommit()) {
connection.commit();
}
}
catch (Throwable t) {
if (!connection.getAutoCommit()) {
try {
connection.rollback();
}
catch (SQLException ex) {
LOGGER.error("Could not rollback transaction.", ex);
}
}
throw sqlException(t);
}
}
}
private Connection getConnection() throws SQLException {
return jdbcDataSource.getConnection();
}
private static SQLException sqlException(Throwable t) {
if (t instanceof SQLException) {
return (SQLException)t;
}
Throwable cause = t.getCause();
return (cause instanceof SQLException) ? (SQLException)cause : new SQLException(t);
}
@FunctionalInterface
public interface ConnectionConsumer {
void accept(Connection connection) throws SQLException;
}
}
|
<reponame>mvo5/a1fbox
#!/usr/bin/python3
# This very basic example listens to the call monitor of the Fritz!Box.
# It does not need to utilize FritzConn(ection), just the ip address is enough.
# REQUIRED: To enable call monitor dial #96*5* and to disable dial #96*4.
# To see some action e.g. call from intern phone 1 to phone 2,
# or use your mobile phone to call the landline. This will print and log the calls.
from a1fbox.callmonitor import CallMonitor, CallMonitorLog
from config import FRITZ_IP_ADDRESS
if __name__ == "__main__":
print("To stop enter '!' (exclamation mark) followed by ENTER key..")
cm_log = CallMonitorLog(daily=True, anonymize=False)
cm = CallMonitor(host=FRITZ_IP_ADDRESS, logger=cm_log.log_line)
key = ""
while key != "!":
key = input()
cm.stop()
|
Find Your Next Car New
Used Select a Make Acura Aston Martin Audi Bentley BMW Bugatti Buick Cadillac Chevrolet Chrysler Dodge Ferrari Ford GMC Honda HUMMER Hyundai Infiniti Isuzu Jaguar Jeep Kia Lamborghini Land Rover Lexus Lincoln Lotus Maserati Maybach Mazda Mercedes-Benz Mercury MINI Mitsubishi Morgan Nissan Panoz Pontiac Porsche Rolls-Royce Saab Saleen Saturn Scion smart Spyker Subaru Suzuki Toyota Volkswagen Volvo Select a Make Acura American Motors Aston Martin Audi BMW Bentley Buick Cadillac Chevrolet Chrysler Dodge Eagle Ferrari Ford GMC Geo Honda Hummer Hyundai Infiniti Isuzu Jaguar Jeep Kia Lamborghini Land Rover Lexus Lincoln Lotus MG Maserati Mazda Mercedes Mercury Mini Mitsubishi Nissan Oldsmobile Plymouth Pontiac Porsche Rolls-Royce Saab Saturn Scion Subaru Suzuki Toyota Volkswagen Volvo Map Where does your state rank? View map Americans everywhere are feeling the recession's pain � some more than others. Quick Vote How much money will the government get back from troubled automakers GM and Chrysler? None
Some, but not all
All
All, plus a profit or View results
NEW YORK (CNNMoney.com) -- The rising price of gasoline is putting pressure on cash-strapped motorists and throwing barricades into the path of a speedy economic recovery.
The national average price for a gallon of regular unleaded gas edged up to $2.488 on Saturday, from $2.467 the day before, according to motorist group AAA.
That marks the 32nd consecutive increase. In that one-month period, the average price of gas jumped more than 20%.
That surge is causing concern for drivers as the summer driving season gets underway.
Americans are already dealing with high unemployment and a collapsing housing market. If gas prices continue to climb at their heady rates, Americans who are living "paycheck to paycheck" could put the brakes on their plans to tool around this summer, crimping some of the government's efforts to pull the economy out of recession, said Tom Kloza, chief oil analyst for the Oil Price Information Service.
"There's way too much optimism about a driving season lift," said Kloza, who believes that higher prices, in conjunction with the recession, will dampen the typical summer travel surge.
Kloza said the impact will be especially painful in economic "sore spots" like California, Florida, Arizona and the rural South.
Gas is particularly expensive in California, where the average price is $2.725 a gallon. In Arizona, the average price is less expensive, at $2.341 a gallon.
Currently, the highest gas prices are in Alaska, where prices average $2.752 per gallon. The cheapest gas can be found in South Carolina, where the average is $2.299 a gallon.
Despite the recent surge, the average price of a gallon of gas remains 40% below its all-time peak of $4.114 on July 17, 2008. But the repercussions of that peak are still being felt.
Kloza said that drivers are more likely to focus on the recent increases, than to feel relieved that gas prices are off their 2008 peak.
"People are crazy when it comes to the price of gasoline," he said. "Nothing has quite the emotional component than gas prices do."
Last year's gas price spike also severely hampered demand for SUVs and trucks, hastening the downward spiral for the Big Three automakers.
Chrysler filed for bankruptcy on April 30 and is awaiting a ruling from a federal judge as to whether it may sell its assets and form a new company. General Motors (GM, Fortune 500) is expected to file for bankruptcy next week and its stock price is trading below $1 a share for the first time since the Great Depression. |
def main():
S = input()
N = len(S)
def solve(S):
from collections import deque
cur = deque([S[0]], maxlen=1)
ans = 1
i = 1
plus = 1
while i+plus <= N:
if S[i:i+plus] in cur:
plus += 1
else:
ans += 1
cur.append(S[i:i+plus])
i = i+plus
plus = 1
return ans
print(solve(S))
if __name__ == '__main__':
main()
|
""" Testing of the Decision Tree Classifier.
"""
# Author: <NAME> (TM)
# (C) Copyright 2019, AI Werkstatt (TM) www.aiwerkstatt.com. All rights reserved.
import pytest
import numpy as np
import pickle
import graphviz
from sklearn.datasets import load_iris
from sklearn.utils.estimator_checks import check_estimator
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.exceptions import NotFittedError
from koho.sklearn import DecisionTreeClassifier
precision = 1e-7 # used for floating point "==" test
# iris dataset
@pytest.fixture
def iris():
return load_iris()
# sklearn compatible
# ==================
# sklearn's check_estimator()
def test_sklearn_check_estimator():
check_estimator(DecisionTreeClassifier)
# sklearn's pipeline
def test_sklearn_pipeline(iris):
X, y = iris.data, iris.target
pipe = make_pipeline(DecisionTreeClassifier(random_state=0))
pipe.fit(X, y)
pipe.predict(X)
pipe.predict_proba(X)
score = pipe.score(X, y)
assert score > 1.0 - precision and score < 1.0 + precision
# sklearn's grid search
def test_sklearn_grid_search(iris):
X, y = iris.data, iris.target
parameters = [{'class_balance': ['balanced'],
'max_depth': [1, 3, 5]}]
grid_search = GridSearchCV(DecisionTreeClassifier(random_state=0), parameters, cv=3)
grid_search.fit(X, y)
assert grid_search.best_params_['class_balance'] == 'balanced'
assert grid_search.best_params_['max_depth'] == 5
clf = DecisionTreeClassifier(random_state=0)
clf.set_params(**grid_search.best_params_)
assert clf.class_balance == 'balanced'
assert clf.max_depth == 5
assert clf.max_features is None
assert clf.max_thresholds is None
assert clf.random_state == 0
clf.fit(X, y)
score = clf.score(X, y)
assert score > 1.0 - precision and score < 1.0 + precision
# sklearn's persistence
def test_sklearn_persistence(iris):
X, y = iris.data, iris.target
clf = DecisionTreeClassifier(random_state=0)
clf.fit(X, y)
with open("clf_dtc.pkl", "wb") as f:
pickle.dump(clf, f)
with open("clf_dtc.pkl", "rb") as f:
clf2 = pickle.load(f)
score = clf2.score(X, y)
assert score > 1.0 - precision and score < 1.0 + precision
# iris dataset
# ============
def test_iris(iris):
X, y = iris.data, iris.target
clf = DecisionTreeClassifier(max_depth=3, random_state=0)
assert clf.class_balance == 'balanced'
assert clf.max_depth == 3
assert clf.max_features is None
assert clf.max_thresholds is None
assert clf.random_state == 0
# Training
clf.fit(X, y)
# Feature Importances
feature_importances = clf.feature_importances_
feature_importances_target = [0., 0., 0.58561555, 0.41438445]
for i1, i2 in zip(feature_importances, feature_importances_target):
assert i1 > i2 - precision and i1 < i2 + precision
# Visualize Tree
dot_data = clf.export_graphviz(
feature_names=iris.feature_names,
class_names=iris.target_names,
rotate=True)
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'rankdir=LR ;' '\n' \
r'0 [label="petal length (cm) <= 2.45\np(class) = [0.33, 0.33, 0.33]\nclass, n = 150", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=3.333333, headlabel="True", labeldistance=2.5, labelangle=-45] ;' '\n' \
r'0 -> 2 [penwidth=6.666667] ;' '\n' \
r'1 [label="[1, 0, 0]\nsetosa", fillcolor="#FF0000FF"] ;' '\n' \
r'2 [label="petal width (cm) <= 1.75\n[0, 0.5, 0.5]", fillcolor="#00FF003F"] ;' '\n' \
r'2 -> 3 [penwidth=3.600000] ;' '\n' \
r'2 -> 6 [penwidth=3.066667] ;' '\n' \
r'3 [label="petal length (cm) <= 4.95\n[0, 0.91, 0.09]", fillcolor="#00FF00BE"] ;' '\n' \
r'3 -> 4 [penwidth=3.200000] ;' '\n' \
r'3 -> 5 [penwidth=0.400000] ;' '\n' \
r'4 [label="[0, 0.98, 0.02]\nversicolor", fillcolor="#00FF00EF"] ;' '\n' \
r'5 [label="[0, 0.33, 0.67]\nvirginica", fillcolor="#0000FF55"] ;' '\n' \
r'6 [label="petal length (cm) <= 4.85\n[0, 0.02, 0.98]", fillcolor="#0000FFEE"] ;' '\n' \
r'6 -> 7 [penwidth=0.200000] ;' '\n' \
r'6 -> 8 [penwidth=2.866667] ;' '\n' \
r'7 [label="[0, 0.33, 0.67]\nvirginica", fillcolor="#0000FF55"] ;' '\n' \
r'8 [label="[0, 0, 1]\nvirginica", fillcolor="#0000FFFF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# Export textual format
t = clf.export_text()
t_target = r'0 X[2]<=2.45 [50, 50, 50]; 0->1; 0->2; 1 [50, 0, 0]; 2 X[3]<=1.75 [0, 50, 50]; 2->3; 2->6; 3 X[2]<=4.95 [0, 49, 5]; 3->4; 3->5; 4 [0, 47, 1]; 5 [0, 2, 4]; 6 X[2]<=4.85 [0, 1, 45]; 6->7; 6->8; 7 [0, 1, 2]; 8 [0, 0, 43]; '
assert t == t_target
# Persistence
with open("iris_dtc.pkl", "wb") as f:
pickle.dump(clf, f)
with open("iris_dtc.pkl", "rb") as f:
clf2 = pickle.load(f)
assert clf2.export_text() == clf.export_text()
# Classification
c = clf2.predict(X)
assert sum(c) == 152
cp = clf2.predict_proba(X)
assert sum(sum(cp)) > 150 - precision and sum(sum(cp)) < 150 + precision
# Testing
score = clf2.score(X, y)
assert score > 0.9733333333333334 - precision and score < 0.9733333333333334 + precision
# simple example (User's Guide C++)
# =================================
classes = ['A', 'B']
features = ['a', 'b', 'c']
X = np.array([
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[0, 1, 1],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 1, 1]]).astype(np.double)
y = np.array([0, 0, 1, 1, 1, 1, 1, 1, 1, 1])
X_test = np.array([[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]]).astype(np.double)
y_test = np.array([0, 0, 1, 1, 1, 1, 1, 1])
def test_simple_example():
clf = DecisionTreeClassifier(max_depth=3, random_state=0)
assert clf.class_balance == 'balanced'
assert clf.max_depth == 3
assert clf.max_features is None
assert clf.max_thresholds is None
assert clf.random_state == 0
# Training
clf.fit(X, y)
# Feature Importances
feature_importances = clf.feature_importances_
feature_importances_target = [0.45454545, 0.54545455, 0.]
for i1, i2 in zip(feature_importances, feature_importances_target):
assert i1 > i2 - precision and i1 < i2 + precision
# Visualize Tree
dot_data = clf.export_graphviz(
feature_names=features,
class_names=classes,
rotate=True)
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'rankdir=LR ;' '\n' \
r'0 [label="a <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=-45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="b <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\nA", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# Export textual format
t = clf.export_text()
t_target = r'0 X[0]<=0.5 [5, 5]; 0->1; 0->4; 1 X[1]<=0.5 [5, 1.88]; 1->2; 1->3; 2 [5, 0]; 3 [0, 1.88]; 4 [0, 3.12]; '
assert t == t_target
# Persistence
with open("simple_example_dtc.pkl", "wb") as f:
pickle.dump(clf, f)
with open("simple_example_dtc.pkl", "rb") as f:
clf2 = pickle.load(f)
assert clf2.export_text() == clf.export_text()
# Classification
c = clf2.predict(X)
c_target = [0, 0, 1, 1, 1, 1, 1, 1, 1, 1]
for i1, i2 in zip(c, c_target):
assert i1 > i2 - precision and i1 < i2 + precision
# Testing
score = clf2.score(X, y)
assert score > 1.0 - precision and score < 1.0 + precision
# simple multi-output example
# ===========================
# multi-output fed with single-output
# -----------------------------------
def test_simple_multi_output_example_with_single_output():
classes = [['0', '1', '2', '3', '4', '5', '6', '7']]
features = ['2^2', '2^1', '2^0']
X_mo = np.array([[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]]).astype(np.double)
y_mo = np.array([[0],
[1],
[2],
[3],
[4],
[5],
[6],
[7]]).astype(np.long)
clf = DecisionTreeClassifier(max_depth=3, random_state=0)
# Training
clf.fit(X_mo, y_mo)
# Feature Importances
feature_importances = clf.feature_importances_
feature_importances_target = [0.57142857, 0.14285714, 0.28571429]
for i1, i2 in zip(feature_importances, feature_importances_target):
assert i1 > i2 - precision and i1 < i2 + precision
# Visualize Tree
dot_data = clf.export_graphviz(
feature_names=features,
class_names=classes,
rotate=True)
# filename = "simple_example_multi_output_with_single_output_dtc"
# graph = graphviz.Source(dot_data)
# graph.render(filename, format='pdf')
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'rankdir=LR ;' '\n' \
r'0 [label="2^1 <= 0.5\np(class) = [0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12]\nclass, n = 8", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=5.000000, headlabel="True", labeldistance=2.5, labelangle=-45] ;' '\n' \
r'0 -> 8 [penwidth=5.000000] ;' '\n' \
r'1 [label="2^0 <= 0.5\n[0.25, 0.25, 0, 0, 0.25, 0.25, 0, 0]", fillcolor="#FF000024"] ;' '\n' \
r'1 -> 2 [penwidth=2.500000] ;' '\n' \
r'1 -> 5 [penwidth=2.500000] ;' '\n' \
r'2 [label="2^2 <= 0.5\n[0.5, 0, 0, 0, 0.5, 0, 0, 0]", fillcolor="#FF00006D"] ;' '\n' \
r'2 -> 3 [penwidth=1.250000] ;' '\n' \
r'2 -> 4 [penwidth=1.250000] ;' '\n' \
r'3 [label="[1, 0, 0, 0, 0, 0, 0, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'4 [label="[0, 0, 0, 0, 1, 0, 0, 0]\n4", fillcolor="#00FFFFFF"] ;' '\n' \
r'5 [label="2^2 <= 0.5\n[0, 0.5, 0, 0, 0, 0.5, 0, 0]", fillcolor="#00FF006D"] ;' '\n' \
r'5 -> 6 [penwidth=1.250000] ;' '\n' \
r'5 -> 7 [penwidth=1.250000] ;' '\n' \
r'6 [label="[0, 1, 0, 0, 0, 0, 0, 0]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'7 [label="[0, 0, 0, 0, 0, 1, 0, 0]\n5", fillcolor="#FF00FFFF"] ;' '\n' \
r'8 [label="2^0 <= 0.5\n[0, 0, 0.25, 0.25, 0, 0, 0.25, 0.25]", fillcolor="#0000FF24"] ;' '\n' \
r'8 -> 9 [penwidth=2.500000] ;' '\n' \
r'8 -> 12 [penwidth=2.500000] ;' '\n' \
r'9 [label="2^2 <= 0.5\n[0, 0, 0.5, 0, 0, 0, 0.5, 0]", fillcolor="#0000FF6D"] ;' '\n' \
r'9 -> 10 [penwidth=1.250000] ;' '\n' \
r'9 -> 11 [penwidth=1.250000] ;' '\n' \
r'10 [label="[0, 0, 1, 0, 0, 0, 0, 0]\n2", fillcolor="#0000FFFF"] ;' '\n' \
r'11 [label="[0, 0, 0, 0, 0, 0, 1, 0]\n6", fillcolor="#FF8000FF"] ;' '\n' \
r'12 [label="2^2 <= 0.5\n[0, 0, 0, 0.5, 0, 0, 0, 0.5]", fillcolor="#FFFF006D"] ;' '\n' \
r'12 -> 13 [penwidth=1.250000] ;' '\n' \
r'12 -> 14 [penwidth=1.250000] ;' '\n' \
r'13 [label="[0, 0, 0, 1, 0, 0, 0, 0]\n3", fillcolor="#FFFF00FF"] ;' '\n' \
r'14 [label="[0, 0, 0, 0, 0, 0, 0, 1]\n7", fillcolor="#00FF80FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# Export textual format
t = clf.export_text()
t_target = r'0 X[1]<=0.5 [1, 1, 1, 1, 1, 1, 1, 1]; 0->1; 0->8; 1 X[2]<=0.5 [1, 1, 0, 0, 1, 1, 0, 0]; 1->2; 1->5; 2 X[0]<=0.5 [1, 0, 0, 0, 1, 0, 0, 0]; 2->3; 2->4; 3 [1, 0, 0, 0, 0, 0, 0, 0]; 4 [0, 0, 0, 0, 1, 0, 0, 0]; 5 X[0]<=0.5 [0, 1, 0, 0, 0, 1, 0, 0]; 5->6; 5->7; 6 [0, 1, 0, 0, 0, 0, 0, 0]; 7 [0, 0, 0, 0, 0, 1, 0, 0]; 8 X[2]<=0.5 [0, 0, 1, 1, 0, 0, 1, 1]; 8->9; 8->12; 9 X[0]<=0.5 [0, 0, 1, 0, 0, 0, 1, 0]; 9->10; 9->11; 10 [0, 0, 1, 0, 0, 0, 0, 0]; 11 [0, 0, 0, 0, 0, 0, 1, 0]; 12 X[0]<=0.5 [0, 0, 0, 1, 0, 0, 0, 1]; 12->13; 12->14; 13 [0, 0, 0, 1, 0, 0, 0, 0]; 14 [0, 0, 0, 0, 0, 0, 0, 1]; '
assert t == t_target
# Persistence
with open("simple_example_multi_output_with_single_output_dtc.pkl", "wb") as f:
pickle.dump(clf, f)
with open("simple_example_multi_output_with_single_output_dtc.pkl", "rb") as f:
clf2 = pickle.load(f)
assert clf2.export_text() == clf.export_text()
# Classification
c = clf2.predict(X_mo)
for i1, i2 in zip(c, y_mo):
assert i1 > i2 - precision and i1 < i2 + precision
# Testing
score = clf2.score(X_mo, y_mo)
assert score > 1.0 - precision and score < 1.0 + precision
# multi-output
# ------------
def test_simple_multi_output_example():
classes = [['0', '1', '2', '3', '4', '5', '6', '7'],
['0', '4'],
['0', '2'],
['0', '1']]
features = ['2^2', '2^1', '2^0']
X_mo = np.array([[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]]).astype(np.double)
y_mo = np.array([[0, 0, 0, 0],
[1, 0, 0, 1],
[2, 0, 1, 0],
[3, 0, 1, 1],
[4, 1, 0, 0],
[5, 1, 0, 1],
[6, 1, 1, 0],
[7, 1, 1, 1]]).astype(np.long)
clf = DecisionTreeClassifier(max_depth=3, random_state=0)
# Training
clf.fit(X_mo, y_mo)
# Feature Importances
feature_importances = clf.feature_importances_
feature_importances_target = [0.42105263, 0.26315789, 0.31578947]
for i1, i2 in zip(feature_importances, feature_importances_target):
assert i1 > i2 - precision and i1 < i2 + precision
# Visualize Tree
dot_data = clf.export_graphviz(
feature_names=features,
class_names=classes,
rotate=True)
# filename = "simple_example_multi_output_dtc"
# graph = graphviz.Source(dot_data)
# graph.render(filename, format='pdf')
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'rankdir=LR ;' '\n' \
r'0 [label="2^1 <= 0.5\np(class) = [0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12]\n[0.5, 0.5]\n[0.5, 0.5]\n[0.5, 0.5]\nclass, n = 8", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=5.000000, headlabel="True", labeldistance=2.5, labelangle=-45] ;' '\n' \
r'0 -> 8 [penwidth=5.000000] ;' '\n' \
r'1 [label="2^0 <= 0.5\n[0.25, 0.25, 0, 0, 0.25, 0.25, 0, 0]\n[0.5, 0.5]\n[1, 0]\n[0.5, 0.5]\n", fillcolor="#FF000043"] ;' '\n' \
r'1 -> 2 [penwidth=2.500000] ;' '\n' \
r'1 -> 5 [penwidth=2.500000] ;' '\n' \
r'2 [label="2^2 <= 0.5\n[0.5, 0, 0, 0, 0.5, 0, 0, 0]\n[0.5, 0.5]\n[1, 0]\n[1, 0]\n", fillcolor="#FF000093"] ;' '\n' \
r'2 -> 3 [penwidth=1.250000] ;' '\n' \
r'2 -> 4 [penwidth=1.250000] ;' '\n' \
r'3 [label="[1, 0, 0, 0, 0, 0, 0, 0]\n[1, 0]\n[1, 0]\n[1, 0]\n0\n0\n0\n0\n", fillcolor="#FF0000FF"] ;' '\n' \
r'4 [label="[0, 0, 0, 0, 1, 0, 0, 0]\n[0, 1]\n[1, 0]\n[1, 0]\n4\n4\n0\n0\n", fillcolor="#FF4000FF"] ;' '\n' \
r'5 [label="2^2 <= 0.5\n[0, 0.5, 0, 0, 0, 0.5, 0, 0]\n[0.5, 0.5]\n[1, 0]\n[0, 1]\n", fillcolor="#FFFF0093"] ;' '\n' \
r'5 -> 6 [penwidth=1.250000] ;' '\n' \
r'5 -> 7 [penwidth=1.250000] ;' '\n' \
r'6 [label="[0, 1, 0, 0, 0, 0, 0, 0]\n[1, 0]\n[1, 0]\n[0, 1]\n1\n0\n0\n1\n", fillcolor="#FFFF00FF"] ;' '\n' \
r'7 [label="[0, 0, 0, 0, 0, 1, 0, 0]\n[0, 1]\n[1, 0]\n[0, 1]\n5\n4\n0\n1\n", fillcolor="#BFFF00FF"] ;' '\n' \
r'8 [label="2^0 <= 0.5\n[0, 0, 0.25, 0.25, 0, 0, 0.25, 0.25]\n[0.5, 0.5]\n[0, 1]\n[0.5, 0.5]\n", fillcolor="#00FFFF43"] ;' '\n' \
r'8 -> 9 [penwidth=2.500000] ;' '\n' \
r'8 -> 12 [penwidth=2.500000] ;' '\n' \
r'9 [label="2^2 <= 0.5\n[0, 0, 0.5, 0, 0, 0, 0.5, 0]\n[0.5, 0.5]\n[0, 1]\n[1, 0]\n", fillcolor="#00FFFF93"] ;' '\n' \
r'9 -> 10 [penwidth=1.250000] ;' '\n' \
r'9 -> 11 [penwidth=1.250000] ;' '\n' \
r'10 [label="[0, 0, 1, 0, 0, 0, 0, 0]\n[1, 0]\n[0, 1]\n[1, 0]\n2\n0\n2\n0\n", fillcolor="#00FFFFFF"] ;' '\n' \
r'11 [label="[0, 0, 0, 0, 0, 0, 1, 0]\n[0, 1]\n[0, 1]\n[1, 0]\n6\n4\n2\n0\n", fillcolor="#00BFFFFF"] ;' '\n' \
r'12 [label="2^2 <= 0.5\n[0, 0, 0, 0.5, 0, 0, 0, 0.5]\n[0.5, 0.5]\n[0, 1]\n[0, 1]\n", fillcolor="#00FF8093"] ;' '\n' \
r'12 -> 13 [penwidth=1.250000] ;' '\n' \
r'12 -> 14 [penwidth=1.250000] ;' '\n' \
r'13 [label="[0, 0, 0, 1, 0, 0, 0, 0]\n[1, 0]\n[0, 1]\n[0, 1]\n3\n0\n2\n1\n", fillcolor="#00FF80FF"] ;' '\n' \
r'14 [label="[0, 0, 0, 0, 0, 0, 0, 1]\n[0, 1]\n[0, 1]\n[0, 1]\n7\n4\n2\n1\n", fillcolor="#00FFC0FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# Export textual format
t = clf.export_text()
t_target = r'0 X[1]<=0.5 [1, 1, 1, 1, 1, 1, 1, 1][4, 4][4, 4][4, 4]; 0->1; 0->8; 1 X[2]<=0.5 [1, 1, 0, 0, 1, 1, 0, 0][2, 2][4, 0][2, 2]; 1->2; 1->5; 2 X[0]<=0.5 [1, 0, 0, 0, 1, 0, 0, 0][1, 1][2, 0][2, 0]; 2->3; 2->4; 3 [1, 0, 0, 0, 0, 0, 0, 0][1, 0][1, 0][1, 0]; 4 [0, 0, 0, 0, 1, 0, 0, 0][0, 1][1, 0][1, 0]; 5 X[0]<=0.5 [0, 1, 0, 0, 0, 1, 0, 0][1, 1][2, 0][0, 2]; 5->6; 5->7; 6 [0, 1, 0, 0, 0, 0, 0, 0][1, 0][1, 0][0, 1]; 7 [0, 0, 0, 0, 0, 1, 0, 0][0, 1][1, 0][0, 1]; 8 X[2]<=0.5 [0, 0, 1, 1, 0, 0, 1, 1][2, 2][0, 4][2, 2]; 8->9; 8->12; 9 X[0]<=0.5 [0, 0, 1, 0, 0, 0, 1, 0][1, 1][0, 2][2, 0]; 9->10; 9->11; 10 [0, 0, 1, 0, 0, 0, 0, 0][1, 0][0, 1][1, 0]; 11 [0, 0, 0, 0, 0, 0, 1, 0][0, 1][0, 1][1, 0]; 12 X[0]<=0.5 [0, 0, 0, 1, 0, 0, 0, 1][1, 1][0, 2][0, 2]; 12->13; 12->14; 13 [0, 0, 0, 1, 0, 0, 0, 0][1, 0][0, 1][0, 1]; 14 [0, 0, 0, 0, 0, 0, 0, 1][0, 1][0, 1][0, 1]; '
assert t == t_target
# Persistence
with open("simple_example_multi_output_dtc.pkl", "wb") as f:
pickle.dump(clf, f)
with open("simple_example_multi_output_dtc.pkl", "rb") as f:
clf2 = pickle.load(f)
assert clf2.export_text() == clf.export_text()
# Classification
c = clf2.predict(X_mo)
for i1, i2 in zip(c.ravel(), y_mo.ravel()):
assert i1 > i2 - precision and i1 < i2 + precision
# Testing
score = clf2.score(X_mo, y_mo)
assert score > 1.0 - precision and score < 1.0 + precision
# DecisionTreeClassifier.fit()
# ============================
def test_fit():
clf = DecisionTreeClassifier(random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [5, 5]; 0->1; 0->4; 1 X[1]<=0.5 [5, 1.88]; 1->2; 1->3; 2 [5, 0]; 3 [0, 1.88]; 4 [0, 3.12]; '
assert data == data_target
# max_depth
# ---------
def test_fit_maxdepth():
clf = DecisionTreeClassifier(class_balance=None, max_depth='abc', random_state=0)
with pytest.raises(TypeError):
clf.fit(X, y)
clf = DecisionTreeClassifier(class_balance=None, max_depth=-999, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_depth' in str(excinfo.value)
clf = DecisionTreeClassifier(class_balance=None, max_depth=0, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_depth' in str(excinfo.value)
clf = DecisionTreeClassifier(class_balance=None, max_depth=1, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [2, 8]; 0->1; 0->2; 1 [2, 3]; 2 [0, 5]; '
assert data == data_target
clf = DecisionTreeClassifier(class_balance=None, max_depth=2, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [2, 8]; 0->1; 0->4; 1 X[1]<=0.5 [2, 3]; 1->2; 1->3; 2 [2, 0]; 3 [0, 3]; 4 [0, 5]; '
assert data == data_target
clf = DecisionTreeClassifier(class_balance=None, max_depth=999, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [2, 8]; 0->1; 0->4; 1 X[1]<=0.5 [2, 3]; 1->2; 1->3; 2 [2, 0]; 3 [0, 3]; 4 [0, 5]; '
assert data == data_target
# class_balance
# -------------
def test_fit_classbalance():
clf = DecisionTreeClassifier(class_balance=0, random_state=0)
with pytest.raises(TypeError):
clf.fit(X, y)
clf = DecisionTreeClassifier(class_balance='auto', random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'class_balance' in str(excinfo.value)
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [5, 5]; 0->1; 0->4; 1 X[1]<=0.5 [5, 1.88]; 1->2; 1->3; 2 [5, 0]; 3 [0, 1.88]; 4 [0, 3.12]; '
assert data == data_target
# max_depth + class_balance
# -------------------------
def test_fit_maxdepth_classbalance():
clf = DecisionTreeClassifier(max_depth=2, class_balance='balanced', random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [5, 5]; 0->1; 0->4; 1 X[1]<=0.5 [5, 1.88]; 1->2; 1->3; 2 [5, 0]; 3 [0, 1.88]; 4 [0, 3.12]; '
assert data == data_target
# max_features
# ------------
def test_fit_maxfeatures():
clf = DecisionTreeClassifier(max_features=None, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [5, 5]; 0->1; 0->4; 1 X[1]<=0.5 [5, 1.88]; 1->2; 1->3; 2 [5, 0]; 3 [0, 1.88]; 4 [0, 3.12]; '
assert data == data_target
# integers
clf = DecisionTreeClassifier(max_features=-1, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_features' in str(excinfo.value)
clf = DecisionTreeClassifier(max_features=0, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_features' in str(excinfo.value)
clf = DecisionTreeClassifier(max_features=1, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[1]<=0.5 [5, 5]; 0->1; 0->6; 1 X[2]<=0.5 [5, 2.5]; 1->2; 1->5; 2 X[0]<=0.5 [2.5, 2.5]; 2->3; 2->4; 3 [2.5, 0]; 4 [0, 2.5]; 5 [2.5, 0]; 6 [0, 2.5]; '
assert data == data_target
clf = DecisionTreeClassifier(max_features=2, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[1]<=0.5 [5, 5]; 0->1; 0->6; 1 X[2]<=0.5 [5, 2.5]; 1->2; 1->5; 2 X[0]<=0.5 [2.5, 2.5]; 2->3; 2->4; 3 [2.5, 0]; 4 [0, 2.5]; 5 [2.5, 0]; 6 [0, 2.5]; '
assert data == data_target
clf = DecisionTreeClassifier(max_features=4, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_features' in str(excinfo.value)
# floats
clf = DecisionTreeClassifier(max_features=-1.0, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_features' in str(excinfo.value)
clf = DecisionTreeClassifier(max_features=0.0, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_features' in str(excinfo.value)
clf = DecisionTreeClassifier(max_features=0.1, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[1]<=0.5 [5, 5]; 0->1; 0->6; 1 X[2]<=0.5 [5, 2.5]; 1->2; 1->5; 2 X[0]<=0.5 [2.5, 2.5]; 2->3; 2->4; 3 [2.5, 0]; 4 [0, 2.5]; 5 [2.5, 0]; 6 [0, 2.5]; '
assert data == data_target
clf = DecisionTreeClassifier(max_features=0.67, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[1]<=0.5 [5, 5]; 0->1; 0->6; 1 X[2]<=0.5 [5, 2.5]; 1->2; 1->5; 2 X[0]<=0.5 [2.5, 2.5]; 2->3; 2->4; 3 [2.5, 0]; 4 [0, 2.5]; 5 [2.5, 0]; 6 [0, 2.5]; '
assert data == data_target
clf = DecisionTreeClassifier(max_features=1.0, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [5, 5]; 0->1; 0->4; 1 X[1]<=0.5 [5, 1.88]; 1->2; 1->3; 2 [5, 0]; 3 [0, 1.88]; 4 [0, 3.12]; '
assert data == data_target
clf = DecisionTreeClassifier(max_features=1.1, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_features' in str(excinfo.value)
# strings
clf = DecisionTreeClassifier(max_features='xxx', random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_features' in str(excinfo.value)
clf = DecisionTreeClassifier(max_features='auto', random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[1]<=0.5 [5, 5]; 0->1; 0->6; 1 X[2]<=0.5 [5, 2.5]; 1->2; 1->5; 2 X[0]<=0.5 [2.5, 2.5]; 2->3; 2->4; 3 [2.5, 0]; 4 [0, 2.5]; 5 [2.5, 0]; 6 [0, 2.5]; '
assert data == data_target
clf = DecisionTreeClassifier(max_features='sqrt', random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[1]<=0.5 [5, 5]; 0->1; 0->6; 1 X[2]<=0.5 [5, 2.5]; 1->2; 1->5; 2 X[0]<=0.5 [2.5, 2.5]; 2->3; 2->4; 3 [2.5, 0]; 4 [0, 2.5]; 5 [2.5, 0]; 6 [0, 2.5]; '
assert data == data_target
clf = DecisionTreeClassifier(max_features='log2', random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[1]<=0.5 [5, 5]; 0->1; 0->6; 1 X[2]<=0.5 [5, 2.5]; 1->2; 1->5; 2 X[0]<=0.5 [2.5, 2.5]; 2->3; 2->4; 3 [2.5, 0]; 4 [0, 2.5]; 5 [2.5, 0]; 6 [0, 2.5]; '
assert data == data_target
# misc
clf = DecisionTreeClassifier(max_features=[], random_state=0)
with pytest.raises(TypeError) as excinfo:
clf.fit(X, y)
assert 'max_features' in str(excinfo.value)
# max_thresholds
# --------------
def test_fit_maxthresholds():
# None
clf = DecisionTreeClassifier(max_thresholds=None, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [5, 5]; 0->1; 0->4; 1 X[1]<=0.5 [5, 1.88]; 1->2; 1->3; 2 [5, 0]; 3 [0, 1.88]; 4 [0, 3.12]; '
assert data == data_target
# integers
clf = DecisionTreeClassifier(max_thresholds=0, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_thresholds' in str(excinfo.value)
clf = DecisionTreeClassifier(max_thresholds=99, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'max_thresholds' in str(excinfo.value)
# misc
clf = DecisionTreeClassifier(max_thresholds=[], random_state=0)
with pytest.raises(TypeError) as excinfo:
clf.fit(X, y)
assert 'max_thresholds' in str(excinfo.value)
# max_features and max_thresholds
# -------------------------------
def test_fit_maxfeatures_maxthresholds():
# decision tree: max_features=None, max_thresholds=None ... covered before
# random tree: max_features<n_features, max_thresholds=None ... covered before
# extreme randomized tree: max_features<n_features, max_thresholds=1
clf = DecisionTreeClassifier(max_depth=2, max_features=2, max_thresholds=1, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[1]<=0.715 [5, 5]; 0->1; 0->4; 1 X[2]<=0.624 [5, 2.5]; 1->2; 1->3; 2 [2.5, 2.5]; 3 [2.5, 0]; 4 [0, 2.5]; '
assert data == data_target
# totally randomized tree: max_features=1, max_thresholds=1
clf = DecisionTreeClassifier(max_depth=2, max_features=1, max_thresholds=1, random_state=0)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[1]<=0.715 [5, 5]; 0->1; 0->4; 1 X[2]<=0.858 [5, 2.5]; 1->2; 1->3; 2 [2.5, 2.5]; 3 [2.5, 0]; 4 [0, 2.5]; '
assert data == data_target
# missing_values
# --------------
def test_fit_missingvalues():
# training
clf = DecisionTreeClassifier(missing_values='abc', random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X, y)
assert 'unsupported string' in str(excinfo.value)
clf = DecisionTreeClassifier(missing_values=0, random_state=0)
with pytest.raises(TypeError) as excinfo:
clf.fit(X, y)
assert 'not supported' in str(excinfo.value)
# - no NaN in y ever
X_train_mv = np.array([
[np.NaN],
[np.NaN]
]).astype(np.double)
y_train_mv = np.array([0, np.NaN])
clf = DecisionTreeClassifier(missing_values=None, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X_train_mv, y_train_mv)
assert 'NaN' in str(excinfo.value)
clf = DecisionTreeClassifier(missing_values='NMAR', random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X_train_mv, y_train_mv)
assert 'NaN' in str(excinfo.value)
# - no NaN in X when missing values None
y_train_mv = np.array([0, 1])
clf = DecisionTreeClassifier(missing_values=None, random_state=0)
with pytest.raises(ValueError) as excinfo:
clf.fit(X_train_mv, y_train_mv)
assert 'NaN' in str(excinfo.value)
# - only NaN(s)
y_train_mv = np.array([0, 1])
clf = DecisionTreeClassifier(missing_values='NMAR', random_state=0)
clf.fit(X_train_mv, y_train_mv)
data = clf.export_text()
data_target = r'0 [1, 1]; '
assert data == data_target
dot_data = clf.export_graphviz()
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="[0.5, 0.5]\n0", fillcolor="#FF000000"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# - 1 value : 0, 1 NaN : 1
X_train_mv = np.array([
[0],
[np.NaN]
]).astype(np.double)
y_train_mv = np.array([0, 1])
clf = DecisionTreeClassifier(missing_values='NMAR', random_state=0)
clf.fit(X_train_mv, y_train_mv)
data = clf.export_text()
data_target = r'0 X[0] NA [1, 1]; 0->1; 0->2; 1 [0, 1]; 2 [1, 0]; '
assert data == data_target
dot_data = clf.export_graphviz()
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="X[0] not NA\np(class) = [0.5, 0.5]\nclass, n = 2", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 2 [penwidth=5.000000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 1 [penwidth=5.000000] ;' '\n' \
r'2 [label="[1, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'1 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# - 1 value : 0, 1 value and 1 NaN : 1
X_train_mv = np.array([
[0],
[1],
[np.NaN]
]).astype(np.double)
y_train_mv = np.array([0, 1, 1])
clf = DecisionTreeClassifier(missing_values='NMAR', random_state=0)
clf.fit(X_train_mv, y_train_mv)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 not NA [1.5, 1.5]; 0->1; 0->2; 1 [1.5, 0]; 2 [0, 1.5]; '
assert data == data_target
dot_data = clf.export_graphviz()
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="X[0] <= 0.5 not NA\np(class) = [0.5, 0.5]\nclass, n = 3", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=5.000000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 [label="[1, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'2 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# testing
# - simple dataset - no NaN(s) in training, all 1s are NaN(s) in testing
X_train_mv = np.array([
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]
]).astype(np.double)
y_train_mv = np.array([0, 1, 2, 3, 4, 5, 6, 7])
X_test_mv = np.array([
[0, 0, 0],
[0, 0, np.NaN],
[0, np.NaN, 0],
[0, np.NaN, np.NaN],
[np.NaN, 0, 0],
[np.NaN, 0, np.NaN],
[np.NaN, np.NaN, 0],
[np.NaN, np.NaN, np.NaN]
]).astype(np.double)
clf = DecisionTreeClassifier(missing_values='NMAR', random_state=11)
clf.fit(X_train_mv, y_train_mv)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [1, 1, 1, 1, 1, 1, 1, 1]; 0->1; 0->8; 1 X[1]<=0.5 [1, 1, 1, 1, 0, 0, 0, 0]; 1->2; 1->5; 2 X[2]<=0.5 [1, 1, 0, 0, 0, 0, 0, 0]; 2->3; 2->4; 3 [1, 0, 0, 0, 0, 0, 0, 0]; 4 [0, 1, 0, 0, 0, 0, 0, 0]; 5 X[2]<=0.5 [0, 0, 1, 1, 0, 0, 0, 0]; 5->6; 5->7; 6 [0, 0, 1, 0, 0, 0, 0, 0]; 7 [0, 0, 0, 1, 0, 0, 0, 0]; 8 X[1]<=0.5 [0, 0, 0, 0, 1, 1, 1, 1]; 8->9; 8->12; 9 X[2]<=0.5 [0, 0, 0, 0, 1, 1, 0, 0]; 9->10; 9->11; 10 [0, 0, 0, 0, 1, 0, 0, 0]; 11 [0, 0, 0, 0, 0, 1, 0, 0]; 12 X[2]<=0.5 [0, 0, 0, 0, 0, 0, 1, 1]; 12->13; 12->14; 13 [0, 0, 0, 0, 0, 0, 1, 0]; 14 [0, 0, 0, 0, 0, 0, 0, 1]; '
assert data == data_target
predict_proba = clf.predict_proba(X_test_mv)
predict_proba_target = [
[ 1., 0., 0., 0., 0., 0., 0., 0. ],
[ 0.5, 0.5, 0., 0., 0., 0., 0., 0. ],
[ 0.5, 0., 0.5, 0., 0., 0., 0., 0. ],
[ 0.25, 0.25, 0.25, 0.25, 0., 0., 0., 0. ],
[ 0.5, 0., 0., 0., 0.5, 0., 0., 0. ],
[ 0.25, 0.25, 0., 0., 0.25, 0.25, 0., 0. ],
[ 0.25, 0., 0.25, 0., 0.25, 0., 0.25, 0. ],
[ 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125]
]
for a, b in zip(predict_proba, predict_proba_target):
for ai, bi in zip(a, b):
assert ai > bi - precision and ai < bi + precision
# - simple dataset - NaN(s) in training replacing some 1s, all 1s are NaN(s) in testing
X_train_mv = np.array([
[0, 0, 0],
[0, 0, np.NaN],
[0, np.NaN, 0],
[0, np.NaN, np.NaN],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]
]).astype(np.double)
y_train_mv = np.array([0, 1, 2, 3, 4, 5, 6, 7])
X_test_mv = np.array([
[0, 0, 0],
[0, 0, np.NaN],
[0, np.NaN, 0],
[0, np.NaN, np.NaN],
[np.NaN, 0, 0],
[np.NaN, 0, np.NaN],
[np.NaN, np.NaN, 0],
[np.NaN, np.NaN, np.NaN]
]).astype(np.double)
clf = DecisionTreeClassifier(missing_values='NMAR', random_state=11)
clf.fit(X_train_mv, y_train_mv)
data = clf.export_text()
data_target = r'0 X[0]<=0.5 [1, 1, 1, 1, 1, 1, 1, 1]; 0->1; 0->8; 1 X[1] NA [1, 1, 1, 1, 0, 0, 0, 0]; 1->2; 1->5; 2 X[2] NA [0, 0, 1, 1, 0, 0, 0, 0]; 2->3; 2->4; 3 [0, 0, 0, 1, 0, 0, 0, 0]; 4 [0, 0, 1, 0, 0, 0, 0, 0]; 5 X[2] NA [1, 1, 0, 0, 0, 0, 0, 0]; 5->6; 5->7; 6 [0, 1, 0, 0, 0, 0, 0, 0]; 7 [1, 0, 0, 0, 0, 0, 0, 0]; 8 X[1]<=0.5 [0, 0, 0, 0, 1, 1, 1, 1]; 8->9; 8->12; 9 X[2]<=0.5 [0, 0, 0, 0, 1, 1, 0, 0]; 9->10; 9->11; 10 [0, 0, 0, 0, 1, 0, 0, 0]; 11 [0, 0, 0, 0, 0, 1, 0, 0]; 12 X[2]<=0.5 [0, 0, 0, 0, 0, 0, 1, 1]; 12->13; 12->14; 13 [0, 0, 0, 0, 0, 0, 1, 0]; 14 [0, 0, 0, 0, 0, 0, 0, 1]; '
assert data == data_target
predict_proba = clf.predict_proba(X_test_mv)
predict_proba_target = [
[ 1., 0., 0., 0., 0., 0., 0., 0. ],
[ 0., 1., 0., 0., 0., 0., 0., 0. ],
[ 0., 0., 1., 0., 0., 0., 0., 0. ],
[ 0., 0., 0., 1., 0., 0., 0., 0. ],
[ 0.5, 0., 0., 0., 0.5, 0., 0., 0. ],
[ 0., 0.5, 0., 0., 0.25, 0.25, 0., 0. ],
[ 0., 0., 0.5, 0., 0.25, 0., 0.25, 0. ],
[ 0., 0., 0., 0.5, 0.125, 0.125, 0.125, 0.125]
]
for a, b in zip(predict_proba, predict_proba_target):
for ai, bi in zip(a, b):
assert ai > bi - precision and ai < bi + precision
# random_state
# ------------
def test_fit_randomstate():
# integers
clf = DecisionTreeClassifier(max_features='auto', random_state=-1)
with pytest.raises(OverflowError) as excinfo:
clf.fit(X, y)
clf = DecisionTreeClassifier(max_depth=2, max_features=1, max_thresholds=1, random_state=999)
clf.fit(X, y)
data = clf.export_text()
data_target = r'0 X[2]<=0.528 [5, 5]; 0->1; 0->4; 1 X[0]<=0.64 [2.5, 3.12]; 1->2; 1->3; 2 [2.5, 0.62]; 3 [0, 2.5]; 4 X[0]<=0.187 [2.5, 1.88]; 4->5; 4->6; 5 [2.5, 1.25]; 6 [0, 0.62]; '
assert data == data_target
# misc
clf = DecisionTreeClassifier(max_features='auto', random_state=[])
with pytest.raises(TypeError) as excinfo:
clf.fit(X, y)
# DecisionTreeClassifier.predict_proba()
# ======================================
def test_predict_proba():
clf = DecisionTreeClassifier(random_state=0)
clf.fit(X, y)
predict_proba = clf.predict_proba(X_test)
predict_proba_target = [
[1., 0.],
[1., 0.],
[0., 1.],
[0., 1.],
[0., 1.],
[0., 1.],
[0., 1.],
[0., 1.]
]
for a, b in zip(predict_proba, predict_proba_target):
for ai, bi in zip(a, b):
assert ai > bi - precision and ai < bi + precision
# not fitted
clf = DecisionTreeClassifier(random_state=0)
with pytest.raises(NotFittedError):
predict_proba = clf.predict_proba(X_test)
# class_balance
# -------------
def test_predict_proba_classbalance():
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
predict_proba = clf.predict_proba(X_test)
predict_proba_target = [
[1., 0.],
[1., 0.],
[0., 1.],
[0., 1.],
[0., 1.],
[0., 1.],
[0., 1.],
[0., 1.]
]
for a, b in zip(predict_proba, predict_proba_target):
for ai, bi in zip(a, b):
assert ai > bi - precision and ai < bi + precision
# DecisionTreeClassifier.predict()
# ================================
def test_predict():
clf = DecisionTreeClassifier(random_state=0)
clf.fit(X, y)
predict = clf.predict(X_test)
predict_target = [0, 0, 1, 1, 1, 1, 1, 1]
for a, b in zip(predict, predict_target):
assert a > b - precision and a < b + precision
# not fitted
clf = DecisionTreeClassifier()
with pytest.raises(NotFittedError):
predict = clf.predict(X_test)
# class_balance
# -------------
def test_predict_classbalance():
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
predict = clf.predict(X_test)
predict_target = [0, 0, 1, 1, 1, 1, 1, 1]
for a, b in zip(predict, predict_target):
assert a > b - precision and a < b + precision
# DecisionTreeClassifier.feature_importances_
# ===========================================
def test_feature_importances():
clf = DecisionTreeClassifier(class_balance=None, random_state=0)
clf.fit(X, y)
feature_importances = clf.feature_importances_
feature_importances_target = [0.25, 0.75, 0.]
for a, b in zip(feature_importances, feature_importances_target):
assert a > b - precision
# not fitted
clf = DecisionTreeClassifier(class_balance=None)
with pytest.raises(NotFittedError):
feature_importances = clf.feature_importances_
# class_balance
# -------------
def test_feature_importances_classbalance():
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
feature_importances = clf.feature_importances_
feature_importances_target = [0.45454545, 0.54545455, 0.]
for a, b in zip(feature_importances, feature_importances_target):
assert a > b - precision
# DecisionTreeClassifier.export_graphviz()
# ========================================
def test_export_graphviz():
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
dot_data = clf.export_graphviz()
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="X[0] <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="X[1] <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# feature_names
# -------------
def test_export_graphviz_inverse_class():
y_inv_c = np.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0])
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y_inv_c)
dot_data = clf.export_graphviz()
print(dot_data)
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="X[0] > 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 4 [penwidth=3.125000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 1 [penwidth=6.875000] ;' '\n' \
r'4 [label="[1, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'1 [label="X[1] > 0.5\n[0.27, 0.73]", fillcolor="#00FF0034"] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'3 [label="[1, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'2 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# feature_names
# -------------
def test_export_graphviz_featurenames():
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
with pytest.raises(TypeError):
dot_data = clf.export_graphviz(feature_names=0)
with pytest.raises(IndexError):
dot_data = clf.export_graphviz(feature_names=[ ])
with pytest.raises(IndexError):
dot_data = clf.export_graphviz(feature_names=["f1"])
dot_data = clf.export_graphviz(feature_names=["f1", "f2", "f3"])
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="f1 <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="f2 <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
dot_data = clf.export_graphviz(feature_names=["f1", "f2", "f3", "f4"])
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="f1 <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="f2 <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# class_names
# -----------
def test_export_graphviz_classnames():
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
with pytest.raises(TypeError):
dot_data = clf.export_graphviz(class_names=0)
with pytest.raises(IndexError):
dot_data = clf.export_graphviz(class_names=[ ])
with pytest.raises(IndexError):
dot_data = clf.export_graphviz(class_names=['A'])
dot_data = clf.export_graphviz(class_names=['A', 'B'])
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="X[0] <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="X[1] <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\nA", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
dot_data = clf.export_graphviz(class_names=['A', 'B', 'C'])
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="X[0] <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="X[1] <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\nA", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# rotate
# ------
def test_export_graphviz_rotate():
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
dot_data = clf.export_graphviz(rotate=True)
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'rankdir=LR ;' '\n' \
r'0 [label="X[0] <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=-45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="X[1] <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
dot_data = clf.export_graphviz(rotate=False)
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="X[0] <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="X[1] <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\n0", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\n1", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# feature_names + class_names
# ---------------------------
def test_export_graphviz_featurenames_classnames():
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
dot_data = clf.export_graphviz(feature_names=["f1", "f2", "f3"],
class_names=['A', 'B'])
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'0 [label="f1 <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="f2 <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\nA", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# feature_names + class_names + rotate
# ------------------------------------
def test_export_graphviz_featurenames_classnames_rotate():
clf = DecisionTreeClassifier(class_balance='balanced', random_state=0)
clf.fit(X, y)
dot_data = clf.export_graphviz(feature_names=["f1", "f2", "f3"],
class_names=['A', 'B'],
rotate=True)
dot_data_target = \
r'digraph Tree {' '\n' \
r'node [shape=box, style="rounded, filled", color="black", fontname=helvetica, fontsize=14] ;' '\n' \
r'edge [fontname=helvetica, fontsize=12] ;' '\n' \
r'rankdir=LR ;' '\n' \
r'0 [label="f1 <= 0.5\np(class) = [0.5, 0.5]\nclass, n = 10", fillcolor="#FF000000"] ;' '\n' \
r'0 -> 1 [penwidth=6.875000, headlabel="True", labeldistance=2.5, labelangle=-45] ;' '\n' \
r'0 -> 4 [penwidth=3.125000] ;' '\n' \
r'1 [label="f2 <= 0.5\n[0.73, 0.27]", fillcolor="#FF000034"] ;' '\n' \
r'1 -> 2 [penwidth=5.000000] ;' '\n' \
r'1 -> 3 [penwidth=1.875000] ;' '\n' \
r'2 [label="[1, 0]\nA", fillcolor="#FF0000FF"] ;' '\n' \
r'3 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'4 [label="[0, 1]\nB", fillcolor="#00FF00FF"] ;' '\n' \
r'}'
assert dot_data == dot_data_target
# Extreme Data
# ============
# Empty X, y training data
# ------------------------
def test_empty_Xy_train():
X_train = np.array([]).astype(np.double).reshape(1, -1)
y_train = np.array([])
clf = DecisionTreeClassifier()
with pytest.raises(ValueError):
clf.fit(X_train, y_train)
# 1 X, y training data
# --------------------
def test_1_Xy_train():
X_train = np.array([[0, 0, 0]]).astype(np.double).reshape(1, -1)
y_train = np.array([0])
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
data = clf.export_text()
data_target = r'0 [1]; '
assert data == data_target
X_test = np.array([[1, 1, 1]]).astype(np.double).reshape(1, -1)
predict = clf.predict(X_test)
predict_target = [0]
for a, b in zip(predict, predict_target):
assert a > b - precision and a < b + precision
# All X = 0 training data
# -----------------------
def test_X_0_train():
X_train = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]).astype(np.double)
y_train = np.array([0, 1, 1])
clf = DecisionTreeClassifier(class_balance=None)
clf.fit(X_train, y_train)
data = clf.export_text()
data_target = r'0 [1, 2]; '
assert data == data_target
predict = clf.predict(X_train)
predict_target = [1, 1, 1]
for a, b in zip(predict, predict_target):
assert a > b - precision and a < b + precision
# All y = 0 training data
# -----------------------
def test_y_0_train():
X_train = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]]).astype(np.double)
y_train = np.array([0, 0, 0])
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
data = clf.export_text()
print(data)
data_target = r'0 [3]; '
assert data == data_target
predict = clf.predict(X_train)
predict_target = [0, 0, 0]
for a, b in zip(predict, predict_target):
assert a > b - precision and a < b + precision
# Number of classes very large
# ----------------------------
# code coverage for duplication of offset_list in create_rgb_LUT in export_graphviz( )
def test_numberclasses_large():
n_classes = 97 # max number of colors = 96
X_train = np.array(range(n_classes)).astype(np.double).reshape(-1,1)
y_train = np.array(range(n_classes))
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
dot_data = clf.export_graphviz()
# no error raised
# Mismatch number of features
# ---------------------------
def test_mismatch_nfeatures():
X_train = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]]).astype(np.double)
y_train = np.array([0, 1, 2])
X_test = np.array([[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0]]).astype(np.double)
y_test = np.array([0, 1, 2])
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
with pytest.raises(ValueError) as excinfo:
predict = clf.predict(X_test)
assert 'number of features' in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
predict_proba = clf.predict_proba(X_test)
assert 'number of features' in str(excinfo.value)
|
Hide Transcript Show Transcript
WEBVTT MEGAN: THEY ARE BLOODSUCKINGPARASITES.ANYONE WHO HAS BEEN IN THE BUGBUSINESS KNOWS, >> THE INSECT FROM HELL. MEGAN: BED BUGS WILL MAKE YOURSKIN CRAWL.>> IT'S THE WORST INSECT IN THEWORLD.THEY CAN LIVE A YEAR WITHOUTFEEDING.SO THEY'RE VERY DIFFICULT TO GETRID OF. MEGAN: MARK DUTTON, THE MANAGEROF CANTON ACE HARDWARE, SAYSBALTIMORE HAS A BED BUG PROBLEM,AND IT'S HARD TO SLEEP TIGHTONCE YOU FIGURE OUT .>> PEOPLE TEND TO THINK BED BU, HAVING BEDBUGS IS RELATED TOPOOR HOUSEKEEPING, BUT IT'S NOT.ANYONE CAN GET BED BUGS.MEGAN: ESPECIALLY BECAUSETHEY'RE HITCHHIKERS, AND THEYOFTEN ACT AS THE SOUVENIR YOUNEVER WANTED>> IT IS IMPORTANT TO MAKE SURETHAT IF YOU GO TO HOTELS ORCRUISES OR PLACES OUTSIDE THATTHEY USUALLY SIT DAY COMICS --INSPECT IT WELL.MEGAN: ACCORDING TO THE EXPERTSTHEY'RE NOT IMPOSSIBLE TO FIND., YOU JUST HAVE TO KNOW WHAT YOUARE LOOKING FOR.TAKE THIS APPLE.AN ADULT BED BUG IS ABOUT THESIZE OF THE SEED.AND ONCE YOU FIND THEM, IT'STIME TO GET DOWN TO BUSINESS.MARK DUTTON SAYS IT TAKES TIME,BUT THERE ARE PLENTY OF WAYS TOEVICT BED BUGS. HE SAYS TREATMENTS OF SPRAYS,ALONG WITH SEALANT COVERS FORTHE MATTRESS AND THE BOX SPRING,WILL DO THE TRICK.BUT REMEMBER, JUST BECAUSETHEY'RE CALLED BED BUGS DOESN'TMEAN THAT'S THE ONLY PLACE TOFIND THEM.>> THEY CAN BE BEHIND ELECTRICALOUTLETS, THEY CAN BE BEHINDBASEBOARDS, THEY CAN BE IN YOURNIGHTSTANDS. THEY LOVE WOOD.THEY LOVE BOOKS.MEGAN: BOTTOM LINE WITH THESEGUYS, KEEP AN EYE OUT FOR THEMBEFORE THEY FIND THEIR WAY TOYOU.IN BALTIMORE, MEGAN PRINGLE,
Advertisement Baltimore ranked top bed bug city in US City moves up nine spots in survey, Orkin finds Share Shares Copy Link Copy
The phrase, "Sleep tight, don't let the bed bugs bite," isn't all that easy with this story. Baltimore ranks No. 1 on the list of the top 50 bed bug cities, according to a survey by the pest company Orkin. Orkin based the results on bed bug data from the metro areas where the company performed the most treatments. "It's the worst insect in the world,” Mark Dutton, manager at Canton Ace Hardware, said. “They can live a year without feeding. So they're very difficult to get rid of." Dutton said Baltimore has a bed bug problem, and it's hard to sleep tight once you have figured that out. “People tend to think bed bugs is related to poor housekeeping, but it's not,” Dutton said. “Anyone can get bed bugs.” Pest experts said part of the problem is that bed bugs are considered “hitchhikers” that people don’t realize they have brought home until it is too late. "It's really important if you go to a hotel or cruise, places outside where you usually stay, inspect that as well,” Orkin entomologist Ron Harrison said. According to the experts, bed bugs are not impossible to find. People just have to know what they are looking for as an adult bed bug is about the size of an apple seed. Dutton said it takes time, but there are plenty of ways to evict bed bugs, including treatment sprays, along with sealant covers for mattresses and box springs. Experts warn that bed bugs can also be found behind electrical outlets and baseboards, in night stands, wood and books. |
<filename>AnnotationToolUnitTest/ch/ethz/scu/obit/test/reader/microscopy/package-info.java
package ch.ethz.scu.obit.test.reader.microscopy; |
<reponame>albertov/hs-mapnik<filename>pure/src/Mapnik/Map.hs<gh_stars>1-10
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DuplicateRecordFields #-}
module Mapnik.Map where
import Mapnik.Imports
import Mapnik.Common
import Mapnik.Color
import Mapnik.Enums
import Mapnik.Parameter
import Data.Monoid (mempty)
import Data.Default
import Mapnik.Style
import Mapnik.Layer
import Prelude hiding (map)
data Map s = Map
{ backgroundColor :: !(Maybe Color)
, backgroundImage :: !(Maybe FilePath)
, backgroundImageCompOp :: !(Maybe CompositeMode)
, backgroundImageOpacity :: !(Maybe Double)
, srs :: !(Maybe Proj4)
, bufferSize :: !(Maybe Int)
, maximumExtent :: !(Maybe Box)
, fontDirectory :: !(Maybe FilePath)
, basePath :: !(Maybe FilePath)
, fontSets :: !FontSetMap
, styles :: !Styles
, layers :: ![Layer s]
, parameters :: !Parameters
} deriving (Eq, Show, Generic)
deriveMapnikJSON ''Map
instance Default (Map s) where
def = Map
{ backgroundColor = Nothing
, backgroundImage = Nothing
, backgroundImageCompOp = Nothing
, backgroundImageOpacity = Nothing
, srs = Nothing
, bufferSize = Nothing
, maximumExtent = Nothing
, fontDirectory = Nothing
, basePath = Nothing
, fontSets = mempty
, styles = mempty
, layers = mempty
, parameters = mempty
}
|
package main
import "fmt"
type PathIndexer struct{}
func (pi *PathIndexer) receive(path, event string) {
fmt.Printf("Indexing: %v, %v\n", path, event)
}
type PathFileMD5 struct{}
func (pfm *PathFileMD5) receive(path, event string) {
fmt.Printf("Checksuming: %v, %v\n", path, event)
}
|
/**
* Holds state associated with a Surface used for MediaCodec decoder output.
* <p>
* The (width,height) constructor for this class will prepare GL, create a SurfaceTexture,
* and then create a Surface for that SurfaceTexture. The Surface can be passed to
* MediaCodec.configure() to receive decoder output. When a frame arrives, we latch the
* texture with updateTexImage, then render the texture with GL to a pbuffer.
* <p>
* The no-arg constructor skips the GL preparation step and doesn't allocate a pbuffer.
* Instead, it just creates the Surface and SurfaceTexture, and when a frame arrives
* we just draw it on whatever surface is current.
* <p>
* By default, the Surface will be using a BufferQueue in asynchronous mode, so we
* can potentially drop frames.
*/
public class OutputSurface implements SurfaceTexture.OnFrameAvailableListener {
private static final String TAG = "OutputSurface";
private static final boolean VERBOSE = false;
private EGLDisplay mEGLDisplay = EGL14.EGL_NO_DISPLAY;
private EGLContext mEGLContext = EGL14.EGL_NO_CONTEXT;
private EGLSurface mEGLSurface = EGL14.EGL_NO_SURFACE;
private SurfaceTexture mSurfaceTexture;
private Surface mSurface;
private Object mFrameSyncObject = new Object(); // guards mFrameAvailable
private boolean mFrameAvailable;
private TextureRender mTextureRender;
/**
* Creates an OutputSurface backed by a pbuffer with the specifed dimensions. The new
* EGL context and surface will be made current. Creates a Surface that can be passed
* to MediaCodec.configure().
*/
public OutputSurface(int width, int height) {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException();
}
eglSetup(width, height);
makeCurrent();
setup(this);
}
private void makeCurrent() {
}
private void eglSetup(int width, int height) {
}
/**
* Creates instances of TextureRender and SurfaceTexture, and a Surface associated
* with the SurfaceTexture.
*/
private void setup(SurfaceTexture.OnFrameAvailableListener listener) {
mTextureRender = new TextureRender();
mTextureRender.surfaceCreated();
// Even if we don't access the SurfaceTexture after the constructor returns, we
// still need to keep a reference to it. The Surface doesn't retain a reference
// at the Java level, so if we don't either then the object can get GCed, which
// causes the native finalizer to run.
if (VERBOSE) Log.d(TAG, "textureID=" + mTextureRender.getTextureId());
mSurfaceTexture = new SurfaceTexture(mTextureRender.getTextureId());
// This doesn't work if OutputSurface is created on the thread that CTS started for
// these test cases.
//
// The CTS-created thread has a Looper, and the SurfaceTexture constructor will
// create a Handler that uses it. The "frame available" message is delivered
// there, but since we're not a Looper-based thread we'll never see it. For
// this to do anything useful, OutputSurface must be created on a thread without
// a Looper, so that SurfaceTexture uses the main application Looper instead.
//
// Java language note: passing "this" out of a constructor is generally unwise,
// but we should be able to get away with it here.
mSurfaceTexture.setOnFrameAvailableListener(listener);
mSurface = new Surface(mSurfaceTexture);
}
@Override
public void onFrameAvailable(SurfaceTexture surfaceTexture) {
}
public Surface getSurface() {
return null;
}
} |
package org.aksw.jena_sparql_api.core;
import org.aksw.jena_sparql_api.syntax.UpdateRequestUtils;
import org.apache.jena.sparql.core.DatasetDescription;
import org.apache.jena.update.UpdateProcessor;
import org.apache.jena.update.UpdateRequest;
public class UpdateExecutionFactoryDatasetDescription
extends UpdateExecutionFactoryDelegate
{
protected String withIri;
protected DatasetDescription datasetDescription;
public UpdateExecutionFactoryDatasetDescription(UpdateExecutionFactory uef, String withIri, DatasetDescription datasetDescription) {
super(uef);
this.withIri = withIri;
this.datasetDescription = datasetDescription;
}
@Override
public UpdateProcessor createUpdateProcessor(UpdateRequest updateRequest) {
UpdateRequest clone = UpdateRequestUtils.clone(updateRequest);
UpdateRequestUtils.applyWithIri(updateRequest, withIri);
UpdateRequestUtils.applyDatasetDescription(clone, datasetDescription);
UpdateProcessor result = super.createUpdateProcessor(updateRequest);
return result;
}
}
|
package plan
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/src-d/go-mysql-server/sql"
)
func TestShowCreateDatabase(t *testing.T) {
require := require.New(t)
node := NewShowCreateDatabase(sql.UnresolvedDatabase("foo"), true)
iter, err := node.RowIter(sql.NewEmptyContext())
require.NoError(err)
rows, err := sql.RowIterToRows(iter)
require.NoError(err)
require.Equal([]sql.Row{
{"foo", "CREATE DATABASE /*!32312 IF NOT EXISTS*/ `foo` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8_bin */"},
}, rows)
node = NewShowCreateDatabase(sql.UnresolvedDatabase("foo"), false)
iter, err = node.RowIter(sql.NewEmptyContext())
require.NoError(err)
rows, err = sql.RowIterToRows(iter)
require.NoError(err)
require.Equal([]sql.Row{
{"foo", "CREATE DATABASE `foo` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8_bin */"},
}, rows)
}
|
Modeling of Brain Physics
The physics of the human brain has two components – basic physics common to all mammals and the physics of thinking inherent only in man. The development of the mental component of the structural and functional organization of the brain in phylogeny was associated with the chiral factor of the external environment, and in ontogenesis - with the social factor. The sensitivity of the brain to these factors was based on the single-connected nature of its aqueous basis, the mechanism of electromagnetic induction, and the features of the thermodynamics of the brain in a state of night sleep. In order to unify the description of the mechanism of electromagnetic processes in the brain, the concept of a quasiphoton has been introduced, combining all forms of excitation of electronic and molecular-cellular structures of the brain. Equivalent schemes of vibrational contours of neural network elements and macrostructures of the brain are proposed. Estimates of the kinetic parameters (activation energy, velocity) of the physical processes underlying the energy-information exchange of the brain with the external environment are made. Mechanisms of operative (physical) and permanent (chemical) memory of the brain, including a model of nonlocal quantum correlations, are discussed. |
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Formatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static class Ans implements Comparable<Ans>
{
String name;
int ps;
public Ans(String n, int p)
{
name=n;
ps=p;
}
@Override
public int compareTo(Ans o) {
// TODO Auto-generated method stub
if(o.ps<this.ps)
return -1;
if(o.ps>this.ps)
return 1;
return this.name.compareTo(o.name);
}
}
static TreeMap<String, Integer> pots;
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String name=bf.readLine();
pots=new TreeMap<String, Integer>();
int n=Integer.parseInt(bf.readLine());
for(int i=0; i<n; i++)
{
StringTokenizer stk=new StringTokenizer(bf.readLine());
String name1=stk.nextToken();
int pts=0;
String c=stk.nextToken();
if(c.equals("posted"))
{
stk.nextToken();
String name2=stk.nextToken();
name2=name2.substring(0,name2.length()-2);
stk.nextToken();
if((name1.equals(name)||name2.equals(name)) && !(name1.equals(name) && name2.equals(name)))
{
if(name1.equals(name))
{
if(!pots.containsKey(name2))
pots.put(name2, 0);
int p=pots.get(name2);
pots.remove(name2);
pots.put(name2, p+15);
}
else
{
if(!pots.containsKey(name1))
pots.put(name1, 0);
int p=pots.get(name1);
pots.remove(name1);
pots.put(name1, p+15);
}
}
else
{
if(!name1.equals(name) && !name2.equals(name))
{
if(!pots.containsKey(name1))
pots.put(name1, 0);
if(!pots.containsKey(name2))
pots.put(name2, 0);
}
}
}
if(c.equals("commented"))
{
stk.nextToken();
String name2=stk.nextToken();
name2=name2.substring(0,name2.length()-2);
stk.nextToken();
if((name1.equals(name)||name2.equals(name)) && !(name1.equals(name) && name2.equals(name)))
{
if(name1.equals(name))
{
if(!pots.containsKey(name2))
pots.put(name2, 0);
int p=pots.get(name2);
pots.remove(name2);
pots.put(name2, p+10);
}
else
{
if(!pots.containsKey(name1))
pots.put(name1, 0);
int p=pots.get(name1);
pots.remove(name1);
pots.put(name1, p+10);
}
}
else
{
if(!name1.equals(name) && !name2.equals(name))
{
if(!pots.containsKey(name1))
pots.put(name1, 0);
if(!pots.containsKey(name2))
pots.put(name2, 0);
}
}
}
if(c.equals("likes"))
{
//stk.nextToken();
String name2=stk.nextToken();
name2=name2.substring(0,name2.length()-2);
stk.nextToken();
if((name1.equals(name)||name2.equals(name)) && !(name1.equals(name) && name2.equals(name)))
{
if(name1.equals(name))
{
if(!pots.containsKey(name2))
pots.put(name2, 0);
int p=pots.get(name2);
pots.remove(name2);
pots.put(name2, p+5);
}
else
{
if(!pots.containsKey(name1))
pots.put(name1, 0);
int p=pots.get(name1);
pots.remove(name1);
pots.put(name1, p+5);
}
}
else
{
if(!name1.equals(name) && !name2.equals(name))
{
if(!pots.containsKey(name1))
pots.put(name1, 0);
if(!pots.containsKey(name2))
pots.put(name2, 0);
}
}
}
}
ArrayList<Ans> ans=new ArrayList<Ans>();
for(String v:pots.keySet())
{
ans.add(new Ans(v,pots.get(v)));
}
Collections.sort(ans);
for(Ans x:ans)
{
pw.println(x.name);
}
pw.flush();
}
}
/*
4 4
1 2 2 3
*
*/ |
package main
import "fmt"
func main() {
var str string
fmt.Scan(&str)
str = string(str[0] + 1)
fmt.Println(str)
} |
#include<stdio.h>
int main()
{
long long int a,b,c,i,j;
double k=0;
long long int s[110];
scanf("%lld",&a);
for(i=1;i<=a;i++){
scanf("%lld",&s[i]);
}
for(i=1;i<=a;i++){
for(j=i+1;j<=a;j++){
if(s[i]>s[j]){
int t=s[j];
s[j]=s[i];
s[i]=t;
}
}
}
for(i=a;i>0;i=i-2){
if(i==1){k=k+(s[i]*s[i]);}
else {c=(s[i]*s[i])-(s[i-1]*s[i-1]);
k=c+k;}
}
printf("%.10lf",k*3.1415926536);
return 0;
}
|
package com.test.project.mapper;
import com.test.project.entity.IntegralConsumption;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 积分消费的数据映射
*/
@Component
@Mapper
public interface IntegralConsumptionMapper {
/**
* 删除一条积分消费记录
*
* @param id 记录id
* @return 删除记录
*/
@Delete("delete from integralConsumption where id = #{id}")
int deleteByPrimaryKey(Integer id);
/**
* 添加一条积分消费记录
*
* @param record 消费记录
* @return 添加结果
*/
@Insert("insert into integralConsumption (consumer, beneficiary, value) values (#{consumer}, #{beneficiary}, #{value});")
int insert(IntegralConsumption record);
/**
* 根据id查询一条消费记录
*
* @param id id
* @return 记录
*/
@Select("select id, consumer, beneficiary, value, time from integralConsumption where id = #{id};")
IntegralConsumption selectById(Integer id);
/**
* 根据生产者查询消费记录
*
* @param consumer 花钱的人的id
* @return 记录列表
*/
@Select("select id, consumer, beneficiary, value, time from integralConsumption where consumer = #{consumer};")
List<IntegralConsumption> findByConsumer(int consumer);
/**
* 根据受益者查询消费记录
*
* @param beneficiary 收钱的人的id
* @return 记录列表
*/
@Select("select id, consumer, beneficiary, value, time from integralConsumption where beneficiary = #{beneficiary};")
List<IntegralConsumption> findByBeneficiary(int beneficiary);
/**
* 修改一条积分消费记录
*
* @param record 新的记录
* @return 修改结果
*/
@Update("update integralConsumption set value = #{value} where id = #{id}")
int updateByPrimaryKey(IntegralConsumption record);
} |
Using activity-based costing to track resource use in group practices.
Research shows that understanding how resources are consumed can help group practices control costs. An American Academy of Orthopaedic Surgeons study used an activity-based costing (ABC) system to measure how resources are consumed in providing medical services. Teams of accounting professors observed 18 diverse orthopedic surgery practices. The researchers identified 17 resource-consuming business processes performed by nonphysician office staff. They measured resource consumption by assigning costs to each process according to how much time is spent on related work activities. When group practices understand how their resources are being consumed, they can reduce costs and optimize revenues by making adjustments in how administrative and clinical staff work. |
def streamlines(self):
if self.hdf_handle is not None:
return LazyStreamlinesGetter(self.hdf_handle, self.subject_id)
else:
raise ValueError("No streamlines available without an HDF handle!") |
// license:BSD-3-Clause
// copyright-holders:<NAME>
/**********************************************************************
Sega SK-1100 keyboard printer port emulation
**********************************************************************
**********************************************************************/
#ifndef MAME_BUS_SG1000_EXP_SK1100_PRN_H
#define MAME_BUS_SG1000_EXP_SK1100_PRN_H
#pragma once
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// ======================> sk1100_printer_port_device
class device_sk1100_printer_port_interface;
class sk1100_printer_port_device : public device_t, public device_single_card_slot_interface<device_sk1100_printer_port_interface>
{
public:
// construction/destruction
template <typename T>
sk1100_printer_port_device(machine_config const &mconfig, char const *tag, device_t *owner, T &&opts, char const *dflt)
: sk1100_printer_port_device(mconfig, tag, owner, 0)
{
option_reset();
opts(*this);
set_default_option(dflt);
set_fixed(false);
}
sk1100_printer_port_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock = 0);
virtual ~sk1100_printer_port_device();
DECLARE_READ_LINE_MEMBER(fault_r);
DECLARE_READ_LINE_MEMBER(busy_r);
DECLARE_WRITE_LINE_MEMBER(data_w);
DECLARE_WRITE_LINE_MEMBER(reset_w);
DECLARE_WRITE_LINE_MEMBER(feed_w);
protected:
// device-level overrides
virtual void device_start() override;
private:
device_sk1100_printer_port_interface *m_device;
};
// ======================> device_sk1100_printer_port_interface
// class representing interface-specific live sk1100_printer_port peripheral
class device_sk1100_printer_port_interface : public device_interface
{
friend class sk1100_printer_port_device;
public:
// construction/destruction
virtual ~device_sk1100_printer_port_interface();
protected:
device_sk1100_printer_port_interface(const machine_config &mconfig, device_t &device);
virtual DECLARE_WRITE_LINE_MEMBER( input_data ) { }
virtual DECLARE_WRITE_LINE_MEMBER( input_reset ) { }
virtual DECLARE_WRITE_LINE_MEMBER( input_feed ) { }
virtual DECLARE_READ_LINE_MEMBER( output_fault ) { return 1; }
virtual DECLARE_READ_LINE_MEMBER( output_busy ) { return 1; }
};
// device type definition
DECLARE_DEVICE_TYPE(SK1100_PRINTER_PORT, sk1100_printer_port_device)
void sk1100_printer_port_devices(device_slot_interface &device);
#endif // MAME_BUS_SG1000_EXP_SK1100_PRN_H
|
def jacobian(self, tcp_jntid):
j = np.zeros((6, len(self.jlc_object.tgtjnts)))
counter = 0
for jid in self.jlc_object.tgtjnts:
grax = self.jlc_object.jnts[jid]["gl_motionax"]
if self.jlc_object.jnts[jid]["type"] == 'revolute':
diffq = self.jlc_object.jnts[tcp_jntid]["gl_posq"] - self.jlc_object.jnts[jid]["gl_posq"]
j[:3, counter] = np.cross(grax, diffq)
j[3:6, counter] = grax
if self.jlc_object.jnts[jid]["type"] == 'prismatic':
j[:3, counter] = grax
counter += 1
if jid == tcp_jntid:
break
return j |
The Panthers continued to remain undefeated after shutting down the Washington Redskins the previous week. Against another NFC East opponent, the Panthers faced the Cowboys this week in Dallas. This game featured a key match-up between the Panthers’ cornerback Josh Norman and Cowboys’ wide receiver Dez Bryant. Josh Norman is having a career year. Josh Norman is rated as ProFootballFocus’ #2 cornerback overall this season so far, and #1 overall in coverage. In this breakdown, we will take a look at Josh Norman’s play versus Dez Bryant.
Josh Norman (#24) vs Cowboys: 6 targets, 2 catches allowed for 16 yards
Target Quarter Receiver Route Result 1 1 Bryant Go Incomplete 2 1 Beasley Hitch Complete – 10 yards 3 2 Bryant In-and-Up Incomplete 4 3 Bryant Slant Complete – 6 yards 5 4 Bryant Sluggo Incomplete 6 4 Bryant Fade Incomplete
First, let’s look at the plays where Norman was targeted by Romo and Cassel.
Play 1
Situation: 2nd and 6 at DAL 24
Description: (14:22 – 1st) T.Romo pass incomplete deep left to D.Bryant (J.Norman). Pass incomplete off play action on a “fly” pattern
Bryant at the top of your screen runs a go-route releasing towards the sideline.
The Panthers are in Cover 1 Man and Norman is lined up on the line of scrimmage across from him.
After the snap, Norman extends his outside arm to press Bryant while taking his kick-step towards the inside guarding against a quick in-breaking route.
Bryant swipes away his arm and then dashes up the sideline. Many cornerbacks would have a hard time recovering from this as Norman completely turns his hips inside and has to spin inside, but he recovers well.
As the pass comes towards Bryant, Norman does an excellent job of spotting the ball and swiping away Bryant’s arms to causes the pass deflection.
Note: Instead of going out of order and doing all of Bryant’s targets first, I’ll cover Norman’s single target while he’s covering Cole Beasley in order to follow the chart at the beginning of the article.
Play 2
Description: Situation: 2nd and 9 at CAR 18
(3:16 – 1st) (Shotgun) T.Romo pass short left to C.Beasley to CAR 8 for 10 yards (J.Norman)
Anytime in this game, when a wide receiver lined up to the outside of Bryant, Norman shifted to cover the outside wide receiver, while the slot cornerback covered Bryant.
Panthers are in Cover 2 with Norman covering the sideline underneath zone at the top of your screen.
Beasley runs an in-breaking hitch route in front of Norman’s zone.
Romo releases the ball towards the sideline, which makes Beasley turn towards the sideline and comeback to it.
Beasley snags the ball and attempts to cut upfield, but Norman grabs him by the ankle to trip him still giving him the first down.
Norman takes too long to recognize that the throw is coming. He is obviously guarding against a potential double move like a hitch-and-go, but Norman does not see the ball coming to Beasley in time to make a play on it while giving him a full yard cushion at the top of Beasley’s stem. Perfectly run route by Beasley.
Panthers run a Cover 4 shell versus the Cowboys’ 11-personnel grouping out of shotgun.
Bryant lines up on the far right side (top of your screen) and runs an in-and-up route attacking the gap between the two right zones.
The deep right safety bites on Bryant’s first cut leaving a hole open over the middle of the field.
Norman thinks he has the deep part of the route covered so he slows down.
This play could have easily gone for a long touchdown if Romo throws this ball 1-2 yards shorter. Missed opportunity for the Cowboys. This was Romo’s second game back from injury, so it’s understandable he’s out of sync with his wide receiver on a deep pass.
Panthers are in Cover 1 Man and Norman is playing man-to-man coverage on Bryant at the bottom of your screen.
Bryant runs a slant underneath Norman’s soft coverage giving him space to work underneath.
Romo, about to be hit, throws a soft ball not fully able to step into the pass. This causes the pass to be short and inaccurate due to the pressure, but Bryant hauls it in while rolling forward on the ground.
Not much for Norman to do here, besides potentially playing more press-man at the line of scrimmage, even if this potentially exposes a deeper pass.
This was Bryant’s only catch while being covered by Norman and itw as for just 6 yards.
Description: Situation: 3rd and 14 at DAL 23(9:33 – 2nd) (Shotgun) T.Romo pass incomplete deep right to D.Bryant. Pass incomplete on a “GO” patternSituation: 1st and 10 at CAR 35Description: (10:01 – 3rd) (Shotgun) T.Romo pass short middle to D.Bryant to CAR 29 for 6 yards (J.Norman) [T.Davis]. pass complete on a “slant” patternSituation: 1st and 10 at CAR 27Description: (6:46 – 4th) (Shotgun) M.Cassel pass incomplete deep left to D.Bryant. Pass incomplete left corner of the end zone 2 yards deep
Bryant at the bottom of your screen runs a sluggo-route attempting to trick Norman. Sluggo-routes work on cornerbackcs that expect the ball to come quickly out of the hands of the quarterback. A cornerback might look toward the backfield and get caught flat-footed therefore exposing the deep portion of the route. Norman does not fall for it.
Cassel places the pass too far inside, so Bryant has to jump over Norman in an attempt to catch the ball.
Norman turns just in time to hit Bryant’s hands causing the incompletion in the endzone.
Situation: 1st and Goal at CAR 5Description: (4:32 – 4th) (No Huddle, Shotgun) M.Cassel pass incomplete short right to D.Bryant. PENALTY on CAR-J.Norman, Unsportsmanlike Conduct, 3 yards, enforced at CAR 5
A fade route in the endzone by Cassel is Bryant’s final pass while being covered by Norman.
Norman is playing off-man coverage on Bryant, which should have been a sign to Cassel not to throw Bryant the ball, but this (among many others) is the reason why Cassel is not a starter in the NFL.
Cassel places the ball too high for Bryant who jumps for it and can’t bring it in.
Norman celebrated in the back of the endzone after the pass which caused the unsportsmanlike conduct penalty.
On the next page, we will take a look at a few passes where Norman was not targeted, his lone blemish, and Bryant’s 20 yard reception. |
ES News Email Enter your email address Please enter an email address Email address is invalid Fill out this field Email address is invalid You already have an account. Please log in or register with your social account
Police allegations against two students at a tuition fees demo were thrown out after YouTube film and photographs showed “shocking” inconsistencies in Met officers’ accounts of the incidents.
In both cases the students were wrestled to the ground, arrested, strip-searched, fingerprinted and faced charges that could have damaged their careers.
Debaleena Dasgupta, a solicitor from Birnberg Peirce who represented the men, called on Scotland Yard to investigate, adding: “The police are given immense power and malicious prosecution is one of the grossest abuses of this.”
Both arrests came as education minister David Willetts gave a lecture at London’s School of Oriental and African Studies.
Ashok Kumar, 29, had been invited by a government official to interview Mr Willetts at the event. Police claimed Mr Kumar twice pushed an officer and blocked an attempt to stop a protester allegedly pushing a camera in another constable’s face. He was charged with obstruction.
The case against him was dropped in court after YouTube footage showed the police account was wrong and that no assault or obstruction had taken place.
Scotland Yard has agreed to pay Mr Kumar £20,000 in damages after he launched legal action for wrongful arrest, false imprisonment, assault and malicious prosecution. Mr Kumar, who was at the LSE at the time of the incident in June 2011, but is now studying for a PhD at Oxford, today spoke of his relief at being cleared.
But he said he had been appalled by his treatment and the inaccurate accounts given by police. “What was astonishing was I was sitting in court and there were officers there ready to testify that I had done something when it was as clear as day from the video that I hadn’t,” he said.
Mr Kumar said he was stopped from entering the lecture by officers. As he waited outside, he saw a teenager who was filming police being told by Pc Paul McAuslan not to push a camera in his face.
Mr Kumar intervened, to which the officer responded angrily. Moments later, Mr Kumar was wrestled to the ground by several officers. Charges were brought with Pc McAuslan claiming that Mr Kumar had pushed him twice before running off. A letter from Scotland Yard’s legal department to Mr Kumar’s solicitor states that the Met “accepts that there do appear to be inconsistencies between this footage and the notes of Pc McAuslan”.
The other case involved Simon Behrman, 36, a law PhD student at Birkbeck College who had gone to SOAS to demonstrate against Mr Willetts’s policies.
The Met paid £20,000 damages and conceded that testimony given in court by Pc Chris Johnson clashed with the evidence of photos of the incident. Mr Behrman claimed that he fell after Pc Johnson grabbed his rucksack and the protest group he had joined surged forward.
Legal papers claim Mr Behrman was then punched in the chest by another officer, Pc Thomas Ashley, before being taken in a headlock by another officer.
At his trial at Highbury magistrates’ court, Pc Johnson said Mr Behrman had been violent and had struggled with a security guard.
The case was abandoned when pictures taken by a photographer were shown to the court which the judge said “blow this case out of the water”.
The Met said that it had begun an investigation. A spokeswoman added: “Three officers are the subject of the IPCC supervised investigation. At no time had we previously received a public complaint in relation to this matter. As soon as we were aware of the video evidence an investigation was launched.” |
import { combineReducers, compose } from '@ngrx/store';
import { assemblyListReducers } from './assembly.reducers';
export const assemblysReducers = combineReducers({
assemblyList: assemblyListReducers
});
|
<filename>bdf2-jbpm4/src/main/java/com/bstek/bdf2/jbpm4/listener/impl/ControlTabFilter.java<gh_stars>1-10
package com.bstek.bdf2.jbpm4.listener.impl;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import com.bstek.bdf2.jbpm4.model.ComponentControl;
import com.bstek.bdf2.jbpm4.model.ControlType;
import com.bstek.dorado.view.widget.base.tab.ControlTab;
/**
* @author Jacky.gao
* @since 2013-7-1
*/
@Component("com.bstek.bdf2.jbpm4.listener.impl.ControlTabFilter")
public class ControlTabFilter extends AbstractFilter {
public void filter(Object component, Collection<ComponentControl> controls) {
ControlTab tab=(ControlTab)component;
String id=tab.getName();
if(StringUtils.isEmpty(id)){
id=tab.getCaption();
}
if(StringUtils.isEmpty(id)){
return;
}
ComponentControl cc=this.match(controls, component, id);
if(cc==null){
return;
}
if(cc.getControlType()==null || cc.getControlType().equals(ControlType.ignore)){
tab.setIgnored(true);
}else{
tab.setDisabled(true);
}
}
public boolean support(Object component) {
return component instanceof ControlTab;
}
}
|
/**
* Provides the SCM build information to the property sets if the URL to the
* SCM is provided.
*
* @param buildMetaDataProperties the build meta data properties.
*/
public final void provideBuildMetaData(
final Properties buildMetaDataProperties) {
final ScmControl scmControl = scmInfo.getScmControl();
if (scmControl.isAddScmInfo() && !scmControl.isOffline()
&& project.getScm() != null) {
try {
final ScmConnectionInfo scmConnectionInfo = loadConnectionInfo();
final ScmAccessInfo scmAccessInfo = createScmAccessInfo();
final RevisionHelper helper =
new RevisionHelper(scmInfo.getScmManager(), scmConnectionInfo,
scmAccessInfo, scmInfo.getBuildDatePattern());
helper.provideScmBuildInfo(buildMetaDataProperties, scmControl);
} catch (final ScmRepositoryException e) {
throw new IllegalStateException(
"Cannot fetch SCM revision information.", e);
} catch (final NoSuchScmProviderException e) {
throw new IllegalStateException(
"Cannot fetch SCM revision information.", e);
}
} else {
LOG.debug("Skipping SCM data since addScmInfo="
+ scmControl.isAddScmInfo() + ", offline=" + scmControl.isOffline()
+ ", scmInfoProvided=" + (project.getScm() != null) + ".");
}
} |
In a video interview with RT America, Rolling Stone's Matt Taibbi, the author of Griftopia, says that as of now, and until the government more aggressively prosecutes financial fraud, Wall Street has a continued incentive to bend the rules in their favor. (Hat tip to Naked Capitalism.)
Since the financial crisis, Taibbi has been one of Wall Street's most outspoken critics. Earlier this month, Taibbi wrote "The People. vs. Goldman Sachs," a sweeping investigation into the Senate report on Goldman Sachs that accused the investment bank of profiting by misleading investors.
"There's really no incentive going forward for people on Wall Street not to commit crimes," Taibbi says in the interview. "The number one thing that came out of this whole period is that there were absolutely no consequences for any of the people that committed this widespread fraud."
Right now, Taibbi continues, Wall Street rightfully sees themselves as above the law, pointing to the billions of dollars in bank bailouts and a lack of prosecution.
Still, with Goldman Sachs last week announcing it is expecting federal subpoenas for its mortgage business, Taibbi sees the current climate as the "last opportunity" for the federal government to take direct action against Wall Street for their role in the financial crisis.
"Personally, I'm hopeful that they actually will do something. It's just too late, but at least it will come eventually," Taibbi said. |
/**
* Convenience method to encode a {@code long} value. Converts the value into a byte array and calls {@link #encode(byte[])}.
*
* @param value
* the number to be encoded
* @return the encoded representation
*/
public static String doEncode(final long value) {
ByteBuffer bb = ByteBuffer.allocate(8);
bb.putLong(value);
bb.flip();
return doEncode(bb.array());
} |
/**
* Return first element in this buffer and remove
*/
public Object next() {
Object x = elems.head;
remove();
return x;
} |
def on_end(self, task) -> None:
if not is_primary() or getattr(task, "test_only", False):
return
self.save_torchscript(task) |
package testChainCode
import (
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/peer"
)
func (c *TestChainCode) getValue(stub shim.ChaincodeStubInterface, args []string) peer.Response {
result := args[0]
return shim.Success([]byte(result))
} |
/**
* This class provides a helper type that contains all the operations for artifacts in a given repository.
*
* <p><strong>Instantiating Registry Artifact </strong></p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.instantiation -->
* <pre>
* RegistryArtifact registryArtifact = new ContainerRegistryClientBuilder()
* .endpoint(endpoint)
* .credential(credential)
* .audience(ContainerRegistryAudience.AZURE_RESOURCE_MANAGER_PUBLIC_CLOUD)
* .buildClient().getArtifact(repository, digest);
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.instantiation -->
*/
@ServiceClient(builder = ContainerRegistryClientBuilder.class)
public final class RegistryArtifact {
private final RegistryArtifactAsync asyncClient;
/**
* Creates a RegistryArtifact type that sends requests to the given repository in the container registry service at {@code endpoint}.
* Each service call goes through the {@code pipeline}.
* @param asyncClient The async client for the given repository.
*/
RegistryArtifact(RegistryArtifactAsync asyncClient) {
this.asyncClient = asyncClient;
}
/**
* Gets the Azure Container Registry service endpoint for the current instance.
* @return The service endpoint for the current instance.
*/
public String getRegistryEndpoint() {
return this.asyncClient.getRegistryEndpoint();
}
/**
* Gets the repository name for the current instance.
* Gets the repository name for the current instance.
* @return Name of the repository for the current instance.
* */
public String getRepositoryName() {
return this.asyncClient.getRepositoryName();
}
/**
* Gets the fully qualified reference for the current instance.
* @return Fully qualified reference of the current instance.
* */
public String getFullyQualifiedReference() {
return this.asyncClient.getFullyQualifiedReference();
}
/**
* Deletes the registry artifact with the digest and repository associated with the instance.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the registry artifact.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.deleteWithResponse#Context -->
* <pre>
* client.deleteWithResponse(Context.NONE);
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.deleteWithResponse#Context -->
*
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A REST response containing the result of the service call.
* @throws ClientAuthenticationException thrown if the client does not have access to the repository.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> deleteWithResponse(Context context) {
return this.asyncClient.deleteWithResponse(context).block();
}
/**
* Deletes the registry artifact with the digest and repository associated with the instance.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the registry artifact.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.delete -->
* <pre>
* client.delete();
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.delete -->
*
* @throws ClientAuthenticationException thrown if the client does not have access to modify the namespace.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void delete() {
this.deleteWithResponse(Context.NONE).getValue();
}
/**
* Deletes the tag with the matching tag name for the given {@link #getRepositoryName() repository}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the tag for the given repository.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.deleteTagWithResponse -->
* <pre>
* String tag = getTag();
* client.deleteTagWithResponse(tag, Context.NONE);
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.deleteTagWithResponse -->
*
* @param tag The name of the tag that needs to be deleted.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A REST response containing the result of the service call.
* @throws ClientAuthenticationException thrown if the client does not have access to modify the namespace.
* @throws NullPointerException thrown if {@code tag} is null.
* @throws IllegalArgumentException thrown if {@code tag} is empty.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<Void> deleteTagWithResponse(String tag, Context context) {
return this.asyncClient.deleteTagWithResponse(tag, context).block();
}
/**
* Deletes the tag with the matching tag name for the given {@link #getRepositoryName() repository}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Delete the tag for the given repository.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.deleteTag -->
* <pre>
* String tag = getTag();
* client.deleteTag(tag);
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.deleteTag -->
*
* @param tag The name of the tag that needs to be deleted.
* @throws ClientAuthenticationException thrown if the client does not have access to modify the namespace.
* @throws NullPointerException thrown if {@code tag} is null.
* @throws IllegalArgumentException throws if {@code tag} is empty.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public void deleteTag(String tag) {
this.deleteTagWithResponse(tag, Context.NONE).getValue();
}
/**
* Gets the {@link ArtifactManifestProperties properties} associated with an artifact in given {@link #getRepositoryName() repository}.
*
* <p>This method can take in both a digest as well as a tag.<br>
* In case a tag is provided it calls the service to get the digest associated with the given tag.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the properties for the given repository.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.getManifestPropertiesWithResponse -->
* <pre>
* Response<ArtifactManifestProperties> response = client.getManifestPropertiesWithResponse(
* Context.NONE);
* final ArtifactManifestProperties properties = response.getValue();
* System.out.printf("Digest:%s,", properties.getDigest());
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.getManifestPropertiesWithResponse -->
*
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A REST response containing {@link ArtifactManifestProperties properties} associated with the given {@code Digest}.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<ArtifactManifestProperties> getManifestPropertiesWithResponse(Context context) {
return this.asyncClient.getManifestPropertiesWithResponse(context).block();
}
/**
* Gets the {@link ArtifactManifestProperties properties} associated with an artifact in given {@link #getRepositoryName() repository}.
*
* <p>This method can take in both a digest as well as a tag.<br>
* In case a tag is provided it calls the service to get the digest associated with the given tag.</p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Get the registry artifact properties for a given tag or digest.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.getManifestProperties -->
* <pre>
* ArtifactManifestProperties properties = client.getManifestProperties();
* System.out.printf("Digest:%s,", properties.getDigest());
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.getManifestProperties -->
*
* @return The {@link ArtifactManifestProperties properties} associated with the given {@code Digest}.
* @throws ClientAuthenticationException thrown if the client's credentials do not have access to modify the namespace.
* @throws ResourceNotFoundException thrown if the given digest was not found.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public ArtifactManifestProperties getManifestProperties() {
return this.getManifestPropertiesWithResponse(Context.NONE).getValue();
}
/**
* Gets the tag properties associated with a given tag in the {@link #getRepositoryName() repository}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the properties associated with the given tag.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.getTagPropertiesWithResponse -->
* <pre>
* String tag = getTag();
* Response<ArtifactTagProperties> response = client.getTagPropertiesWithResponse(tag, Context.NONE);
* final ArtifactTagProperties properties = response.getValue();
* System.out.printf("Digest:%s,", properties.getDigest());
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.getTagPropertiesWithResponse -->
*
* @param tag name of the tag.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A REST response with the {@link ArtifactTagProperties properties} associated with the given tag.
* @throws ClientAuthenticationException thrown if the client does not have access to the repository.
* @throws ResourceNotFoundException thrown if the given tag was not found.
* @throws NullPointerException thrown if {@code tag} is null.
* @throws IllegalArgumentException throws if {@code tag} is empty.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<ArtifactTagProperties> getTagPropertiesWithResponse(String tag, Context context) {
return this.asyncClient.getTagPropertiesWithResponse(tag, context).block();
}
/**
* Gets the tag properties associated with a given tag in the {@link #getRepositoryName() repository}.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve the properties associated with the given tag.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.getTagProperties -->
* <pre>
* String tag = getTag();
* ArtifactTagProperties properties = client.getTagProperties(tag);
* System.out.printf("Digest:%s,", properties.getDigest());
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.getTagProperties -->
*
* @param tag name of the tag.
* @return The {@link ArtifactTagProperties properties} associated with the given tag.
* @throws ClientAuthenticationException thrown if the client does not have access to the repository.
* @throws ResourceNotFoundException thrown if the given tag was not found.
* @throws NullPointerException thrown if {@code tag} is null.
* @throws IllegalArgumentException throws if {@code tag} is empty.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public ArtifactTagProperties getTagProperties(String tag) {
return getTagPropertiesWithResponse(tag, Context.NONE).getValue();
}
/**
* Fetches all the tags associated with the given {@link #getRepositoryName() repository}.
*
* <p> If you would like to specify the order in which the tags are returned please
* use the overload that takes in the options parameter {@link #listTagProperties(ArtifactTagOrder, Context)} listTagProperties}
* No assumptions on the order can be made if no options are provided to the service.
* </p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all the tags associated with the given repository.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.listTagProperties -->
* <pre>
* client.listTagProperties().iterableByPage(10).forEach(pagedResponse -> {
* pagedResponse.getValue().stream().forEach(
* tagProperties -> System.out.println(tagProperties.getDigest()));
* });
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.listTagProperties -->
*
* @return {@link PagedIterable} of the artifacts for the given repository in the order specified by the options.
* @throws ClientAuthenticationException thrown if the client does not have access to the repository.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<ArtifactTagProperties> listTagProperties() {
return listTagProperties(ArtifactTagOrder.NONE, Context.NONE);
}
/**
* Fetches all the tags associated with the given {@link #getRepositoryName() repository}.
*
* <p> The method supports options to select the order in which the tags are returned by the service.
* Currently the service supports an ascending or descending order based on the last updated time of the tag.
* No assumptions on the order can be made if no options are provided to the service.
* </p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all the tags associated with the given repository from the most recently updated to the last.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.listTagPropertiesWithOptionsNoContext -->
* <pre>
* client.listTagProperties(ArtifactTagOrder.LAST_UPDATED_ON_DESCENDING)
* .iterableByPage(10)
* .forEach(pagedResponse -> {
* pagedResponse.getValue()
* .stream()
* .forEach(tagProperties -> System.out.println(tagProperties.getDigest()));
* });
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.listTagPropertiesWithOptionsNoContext -->
*
* @param order The order in which the tags should be returned by the service.
* @return {@link PagedIterable} of the artifacts for the given repository in the order specified by the options.
* @throws ClientAuthenticationException thrown if the client does not have access to the repository.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<ArtifactTagProperties> listTagProperties(ArtifactTagOrder order) {
return this.listTagProperties(order, Context.NONE);
}
/**
* Fetches all the tags associated with the given {@link #getRepositoryName() repository}.
*
* <p> The method supports options to select the order in which the tags are returned by the service.
* Currently the service supports an ascending or descending order based on the last updated time of the tag.
* No assumptions on the order can be made if no options are provided to the service.
* </p>
*
* <p><strong>Code Samples</strong></p>
*
* <p>Retrieve all the tags associated with the given repository from the most recently updated to the last.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.listTagPropertiesWithOptions -->
* <pre>
* client.listTagProperties(ArtifactTagOrder.LAST_UPDATED_ON_DESCENDING, Context.NONE)
* .iterableByPage(10)
* .forEach(pagedResponse -> {
* pagedResponse.getValue()
* .stream()
* .forEach(tagProperties -> System.out.println(tagProperties.getDigest()));
* });
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.listTagPropertiesWithOptions -->
*
* @param order The order in which the tags should be returned by the service.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return {@link PagedIterable} of the artifacts for the given repository in the order specified by the options.
* @throws ClientAuthenticationException thrown if the client does not have access to the repository.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<ArtifactTagProperties> listTagProperties(ArtifactTagOrder order, Context context) {
return new PagedIterable<ArtifactTagProperties>(asyncClient.listTagProperties(order, context));
}
/**
* Update the properties {@link ArtifactTagProperties} of the given tag in {@link #getRepositoryName() repository}.
* These properties set whether the given tag can be updated, deleted and retrieved.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Update the writeable properties of a given tag.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.updateTagPropertiesWithResponse -->
* <pre>
* ArtifactTagProperties properties = getArtifactTagProperties();
* String tag = getTag();
* client.updateTagPropertiesWithResponse(tag, properties, Context.NONE);
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.updateTagPropertiesWithResponse -->
*
* @param tag Name of the tag.
* @param tagProperties {@link ArtifactTagProperties tagProperties} to be set.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A REST response for the completion.
* @throws ClientAuthenticationException thrown if the client does not have access to repository.
* @throws ResourceNotFoundException thrown if the given {@code tag} was not found.
* @throws NullPointerException thrown if {@code tag} or {@code tagProperties} is null.
* @throws IllegalArgumentException thrown if {@code tag} or {@code tagProperties} is empty.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<ArtifactTagProperties> updateTagPropertiesWithResponse(String tag, ArtifactTagProperties tagProperties, Context context) {
return this.asyncClient.updateTagPropertiesWithResponse(tag, tagProperties, context).block();
}
/**
* Update the properties {@link ArtifactTagProperties} of the given {@code tag}.
* These properties set whether the given tag can be updated, deleted and retrieved.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Update the writeable properties of a given tag.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.updateTagProperties -->
* <pre>
* ArtifactTagProperties properties = getArtifactTagProperties();
* String tag = getTag();
* client.updateTagProperties(tag, properties);
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.updateTagProperties -->
*
* @param tag Name of the tag.
* @param tagProperties {@link ArtifactTagProperties tagProperties} to be set.
* @return The updated {@link ArtifactTagProperties properties }
* @throws ClientAuthenticationException thrown if the client does not have access to repository.
* @throws ResourceNotFoundException thrown if the given {@code tag} was not found.
* @throws NullPointerException thrown if {@code tag} or {@code tagProperties} is null.
* @throws IllegalArgumentException thrown if {@code tag} or {@code tagProperties} is empty.
* @throws HttpResponseException thrown if any other unexpected exception is returned by the service.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public ArtifactTagProperties updateTagProperties(String tag, ArtifactTagProperties tagProperties) {
return this.updateTagPropertiesWithResponse(tag, tagProperties, Context.NONE).getValue();
}
/**
* Update the properties {@link ArtifactTagProperties} of the artifact with the given {@code digest}.
* These properties set whether the given manifest can be updated, deleted and retrieved.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Update the writeable properties of a given artifact.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.updateManifestPropertiesWithResponse -->
* <pre>
* ArtifactManifestProperties properties = getArtifactManifestProperties();
* client.updateManifestPropertiesWithResponse(properties, Context.NONE);
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.updateManifestPropertiesWithResponse -->
*
* @param manifestProperties {@link ArtifactManifestProperties tagProperties} to be set.
* @param context Additional context that is passed through the Http pipeline during the service call.
* @return A REST response for the completion.
* @throws ClientAuthenticationException thrown if the client does not have access to repository.
* @throws NullPointerException thrown if the {@code manifestProperties} is null.
* @throws ResourceNotFoundException thrown if the given {@code digest} was not found.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public Response<ArtifactManifestProperties> updateManifestPropertiesWithResponse(ArtifactManifestProperties manifestProperties, Context context) {
return this.asyncClient.updateManifestPropertiesWithResponse(manifestProperties, context).block();
}
/**
* Update the writeable properties {@link ArtifactTagProperties} of the artifact with the given {@code digest}.
* These properties set whether the given manifest can be updated, deleted and retrieved.
*
* <p><strong>Code Samples</strong></p>
*
* <p>Update the writeable properties of a given manifest.</p>
*
* <!-- src_embed com.azure.containers.containerregistry.RegistryArtifact.updateManifestProperties -->
* <pre>
* ArtifactManifestProperties properties = getArtifactManifestProperties();
* client.updateManifestProperties(properties);
* </pre>
* <!-- end com.azure.containers.containerregistry.RegistryArtifact.updateManifestProperties -->
*
* @param manifestProperties {@link ArtifactManifestProperties manifestProperties} to be set.
* @return The updated {@link ArtifactManifestProperties properties }
* @throws ClientAuthenticationException thrown if the client does not have access to repository.
* @throws ResourceNotFoundException thrown if the given {@code digest} was not found.
* @throws NullPointerException thrown if the {@code manifestProperties} is null.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
public ArtifactManifestProperties updateManifestProperties(ArtifactManifestProperties manifestProperties) {
return this.updateManifestPropertiesWithResponse(manifestProperties, Context.NONE).getValue();
}
} |
// statsFilter Init. and sets the text field of Filter.
func statsFilter(filter string) *tview.TextView {
f := tview.NewTextView()
f.SetText(filter).SetTextAlign(tview.AlignCenter)
f.SetTitle(" Filter ").SetTitleAlign(tview.AlignLeft)
f.SetDynamicColors(true)
f.SetBackgroundColor(themeColor)
f.SetBorder(true)
return f
} |
package com.devonfw.module.cxf.common.impl.client.rest;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.apache.cxf.jaxrs.client.ResponseExceptionMapper;
import org.apache.cxf.jaxrs.impl.ResponseImpl;
import org.apache.cxf.jaxrs.model.OperationResourceInfo;
import org.apache.cxf.message.Message;
import org.apache.cxf.transport.Conduit;
import org.apache.cxf.ws.addressing.AttributedURIType;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import com.devonfw.module.service.common.api.client.ServiceClientErrorFactory;
import com.devonfw.module.service.common.api.client.context.ServiceContext;
/**
* An Implementation of {@link ResponseExceptionMapper} that converts a failure response back to a {@link Throwable}
* using {@link ServiceClientErrorFactory}.
*
* @since 3.0.0
*/
@Provider
public class RestServiceExceptionMapper implements ResponseExceptionMapper<Throwable> {
private final ServiceClientErrorFactory errorUnmarshaller;
private final ServiceContext<?> context;
/**
* The constructor.
*
* @param errorUnmarshaller the {@link ServiceClientErrorFactory}.
* @param context the {@link ServiceContext}.
*/
public RestServiceExceptionMapper(ServiceClientErrorFactory errorUnmarshaller, ServiceContext<?> context) {
super();
this.errorUnmarshaller = errorUnmarshaller;
this.context = context;
}
@Override
public Throwable fromResponse(Response response) {
response.bufferEntity();
if (response.hasEntity()) {
String data = response.readEntity(String.class);
if ((data != null) && !data.isEmpty()) {
MediaType mediaType = response.getMediaType();
String url = getUrl(response);
String operation = getOperation(response);
String serviceDetails = this.context.getServiceDescription(operation, url);
return this.errorUnmarshaller.unmarshall(data, mediaType.toString(), response.getStatus(), serviceDetails);
}
}
return null;
}
private String getOperation(Response response) {
if (response instanceof ResponseImpl) {
Message message = ((ResponseImpl) response).getOutMessage();
if (message != null) {
Object invocationContext = message.get(Message.INVOCATION_CONTEXT);
Object requestContext = getFromMap(invocationContext, "RequestContext");
OperationResourceInfo operation = getFromMap(requestContext, OperationResourceInfo.class);
if (operation != null) {
Method method = operation.getAnnotatedMethod();
if (method != null) {
return method.getName();
}
}
}
}
return "";
}
@SuppressWarnings("rawtypes")
private static Object getFromMap(Object map, Object key) {
if (map instanceof Map) {
return ((Map) map).get(key);
}
return null;
}
@SuppressWarnings("rawtypes")
private static <T> T getFromMap(Object map, Class<T> key) {
if (map instanceof Map) {
Object value = ((Map) map).get(key.getName());
if (value != null) {
try {
return key.cast(value);
} catch (Exception e) {
}
}
}
return null;
}
private String getUrl(Response response) {
URI url = response.getLocation();
if (url != null) {
return url.toString();
} else if (response instanceof ResponseImpl) {
Message message = ((ResponseImpl) response).getOutMessage();
if (message != null) {
Object uri = message.get(Message.REQUEST_URI);
if (uri instanceof String) {
return (String) uri;
}
Conduit conduit = message.get(Conduit.class);
if (conduit != null) {
EndpointReferenceType target = conduit.getTarget();
if (target != null) {
AttributedURIType address = target.getAddress();
if (address != null) {
return address.getValue();
}
}
}
}
}
return "";
}
}
|
/**
* Have all instantiated ofSwitches had OpenFlow Messages? Needed e.g. for
* NOX: after successfull TCP Session, NOX does NOTHING, so each 'switch'
* has to send a OFHello for Handshake with Floodlight sending a OFHello at
* any time follows an immediate Disconnect from the Controller.
*/
public void alrdyOpenFlowed() {
for (Connection ofSwitch : this.switches) {
alrdyOpenFlowed(ofSwitch);
}
} |
<gh_stars>0
package B7;
import java.util.ArrayList;
import java.util.List;
public class UniqueWordFinder {
static List<Word> findUniqWordsFromFirstSentence(Paragraph p) {
List<Word> result = new ArrayList<>();
if (!p.getSentences().isEmpty()) {
List<Word> allWords = p.getSentences().get(0).getWords();
allWords.forEach(word -> {
for (int i = 1; i < p.getSentences().size(); i++) {
if (p.getSentences().get(i).contains(word)) {
result.add(word);
}
}
});
}
return result;
}
}
|
def read_records_from_input(self, input_stream: BinaryIO) -> Iterator[dict]:
raise NotImplementedError("This method has to be implemented to read formatted records!") |
// Sends a single character of text as text input into RmlUi.
bool Context::ProcessTextInput(Character character)
{
String text = StringUtilities::ToUTF8(character);
return ProcessTextInput(text);
} |
def build_model(cls, args, task):
levenshtein_rebert_base_architecture(args)
if getattr(args, "max_source_positions", None) is None:
args.max_source_positions = DEFAULT_MAX_SOURCE_POSITIONS
if getattr(args, "max_target_positions", None) is None:
args.max_target_positions = DEFAULT_MAX_TARGET_POSITIONS
src_dict, tgt_dict = task.source_dictionary, task.target_dictionary
src_pinyin_dict = task.src_pinyin_dict
if args.pinyin_on is True:
encoder_pinyin_embed_tokens = cls.build_embedding(
args, src_pinyin_dict, args.encoder_pinyin_embed_dim, args.encoder_pinyin_embed_path
)
if args.encoder_pinyin_embed_path is None:
encoder_pinyin_embed_tokens.apply(init_bert_params)
else:
encoder_pinyin_embed_tokens = None
encoder = cls.build_encoder(args, src_dict, src_pinyin_dict, encoder_pinyin_embed_tokens)
decoder = cls.build_decoder(args, tgt_dict, encoder)
return cls(args, encoder, decoder) |
The Right to Know Colorado GMO proposition 105 mandates the labeling of GMO food products. Since consumers like to know what they eat, the idea of GMO labeling is appealing. However, the proposal is ill-conceived and poorly written. It creates more confusion than enlightenment, it will dramatically increase the costs of foods, and taxpayers will face huge legal bills defending the law. A recent analysis of GMO labeling costs by two Cornell University scientists pegged the costs at $500 per family of 4 per year. Three similar studies carried out in California and Washington State have calculated price tags of $400-800. Why do we need to have mandatory GMO food labeling when voluntarily labeled non-GMO products are readily available?
The GMO food labeling law only requires information on whether a given product was produced by a GMO. It will not inform the consumer what type of genetic change has been made to the organism (has a new gene been added? has an existing gene been silenced or its activity been increased as in classic breeding? has the plant been "vaccinated" to fight viral diseases, or does it produce a toxin to kill corn borers, or a pheromone gas that drives away aphids?). It will not provide information about the composition or the nutritional properties of the product, nor information about the amount of GMO product contained in the food. Finally, it will not inform the consumer whether the food contains genetically engineered molecules, or if - as in the case of refined sugar produced from GM sugar beets - it is free of GMO molecules.
Advertisement
According to studies by the National Academy of Sciences and the American Medical Association there is no science-based or medical reason to single out GM foods for mandatory labeling since they have been extensively evaluated and determined to be safe. To counter this finding, anti-GMO groups have started to finance certain "Academies" that support their claims, like the American Academy of Environmental Medicine, which is referred to by Quackwatch as a "questionable organization."
What makes GMO labeling so expensive? Some of these costs are already evident in certified organic products. Between 2008 and 2011 the average cost for organic ice cream, margarine spreads and eggs were 100 percent higher than of conventional products, and in 2012/13 organic fruit and vegetable prices averaged 50-100 percent higher. The proposed GMO labeling is more stringent: It will require keeping track of and segregating all crops and products from seed purchase to food sale, regular testing for purity, mandatory reporting of the status of millions of products to a regulatory agency, and law enforcement. GMO labeling would place a huge financial burden on small farmers and business owners. Larger food companies that handle millions of packaged food products per day will have to set up sophisticated testing laboratories and hire hundreds of bookkeepers and lawyers to comply with a multitude of state labeling requirements and to police foreign-made products.
If the labeling initiative is accepted, organizations like Green Peace will make life miserable for firms selling GMO-containing foods as it has done in other countries. Some firms will try to reformulate their products, but finding substitutes at reasonable prices may be difficult. Chicken bouillon might contain sugar from GM sugar beets, maltodextrin from GM corn, and hydrolysed protein and tocopherol (vitamin E) from GM soybeans. In 2013 93 percent of the soybeans produced in the U.S. were of the GMO type, but only 0.17 percent were organic. Even doubling the demand for organic soybeans would lead to huge price changes in this commodity alone.
In conclusion, the main purposes of the GMO labeling initiative are to satisfy "consumer curiosity" and to increase the sales and profits of the organic food industry, which funded the initiative. The costs will be huge, the benefits to consumers small, and the bureaucracy needed immense. Is the proposed GMO food labeling worth $500 for a family of four?
Andrew Staehelin is a professor emeritus of the Department of Molecular, Cellular and Developmental Biology at the University of Colorado Boulder. |
I have embarked on a project even thought it's adifficultone for me personally when it comes to stress and the magnitude of work involved.However, I trulybelievein this project andthis is whyIn this new Islamic High School, from Gr 9 - 12 our young men and women will learn the Qur'an cover to cover. They will learn to understand it directly in the Arabic language.The meaning of each word, The Tafseer, its correct Recitation and application. How many of us regret this aspect in our lives? How sad do we feel when we hear the Qur'an in Salah without understanding it?It is the most important book in our life, yet we don't understand it. This is why I love this project and why I am working so hard to make it a reality.In addition, we will be teaching the required Ontario Ministry Curriculum and endeavour to provide them with the best learning experience - supporting student success so that they may enter the best universities.Let's offer our Youth the best of both worlds...that they may attain success in this world and the next Insha-Allah.- Starting September 2014 with Grade 9- Qualified teachers- Limited spots available - 1 class of 20 girls and 1 class of 20 boys- Located within the Kennedy/Britannia area of Mississauga- Leadership program- Youth Centre & Counselling open to the Community- Weekend Qur'an classes tailored to meet the needs of Youth- Community programsIf you have any questions please contact me.Email: [email protected]
Toll-Free Phone: 1 (855) 623-4624 ext 0 or ext 1For more information please visit www.GuardianInternationalSchool.ca Guardian International School Canada is supported and sponsored by Mercy Mission Canada.
JazakAllahu KhairanIndeed, the men who practice charity and the women who practice charity and [they who] have loaned Allah a goodly loan - it will be multiplied for them, and they will have a noble reward. [Surat Al-Ĥadīd, 57:18] |
<reponame>mangab0159/baekjoon
# https://www.acmicpc.net/problem/1167
import sys
ifunc, g = lambda: [*map(int, sys.stdin.readline().rstrip().split())], range
n = ifunc()[0]
edges = [None for _ in g(n+1)]
for _ in g(n):
il = ifunc()
v = il[0]
edges[v] = [(il[idx], il[idx+1]) for idx in g(1, len(il)-2, 2)]
dist = [[0, 0] for _ in g(n+1)]
def dfs(cv, pv):
global dist
for nv, w in edges[cv]:
if nv == pv: continue
dfs(nv, cv)
dist1 = dist[nv][0]+w
if dist1 > dist[cv][0]:
dist[cv][1] = dist[cv][0]
dist[cv][0] = dist1
elif dist1 > dist[cv][1]:
dist[cv][1] = dist1
dfs(1, 1)
print(sum(max(dist, key=lambda x: (x[0]+x[1])))) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.