content
stringlengths 7
2.61M
|
---|
def _get_item_embeddings(self) -> torch.tensor:
if not hasattr(self, 'item_embeddings_'):
items = torch.arange(self.hparams.num_items, device=self.device)
item_embeddings = self.item_embeddings(items)
for item_dense_layer in self.item_dense_layers:
item_embeddings = F.leaky_relu(
item_dense_layer(item_embeddings)
)
self.item_embeddings_ = item_embeddings.detach()
return self.item_embeddings_ |
Efficacy, doseresponse relationship and safety of oncedaily extendedrelease metformin (Glucophage® XR) in type 2 diabetic patients with inadequate glycaemic control despite prior treatment with diet and exercise: results from two doubleblind, placebocontrolled studies Aim: The efficacy, doseresponse relationships and safety of an extendedrelease formulation of metformin (Glucophage® XR) were evaluated in two doubleblind, randomized, placebocontrolled studies of 24 and 16weeks' duration, in patients with inadequate glycaemic control despite diet and exercise. Protocol 1 provided an evaluation of metformin XR at a commonly used dosage. Protocol 2 evaluated different dosages of metformin XR. |
package elegit.treefx;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.binding.When;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.Group;
/**
* Connects two cells in the TreeGraph using a DirectedPath
*/
public class Edge extends Group {
// Determines whether all edges are set to be visible or not
public static BooleanProperty allVisible = new SimpleBooleanProperty(true);
// Whether or not this edge is visible
private BooleanProperty visible;
// The endpoints of this edge
private Cell source;
private Cell target;
// The path that will be drawn to represent this edge
private DirectedPath path;
// Whether extra points between the start and endpoints have been added
private boolean addedMidPoints;
// The y value to draw the mid points at
private DoubleProperty midLineX;
/**
* Constructs a directed line between the source and target cells and binds
* properties to handle relocation smoothly
* @param source the source (parent) cell
* @param target the target (child) cell
*/
public Edge(Cell source, Cell target) {
this.source = source;
this.target = target;
this.addedMidPoints = false;
midLineX = new SimpleDoubleProperty(0);
DoubleBinding endX = source.translateXProperty().add(source.widthProperty().divide(2.0));
DoubleBinding endY = source.translateYProperty().add(source.heightProperty());
DoubleBinding startX = target.translateXProperty().add(target.widthProperty().divide(2.0));
DoubleBinding startY = target.translateYProperty().add(0);
path = new DirectedPath(startX, startY, endX, endY);
checkAndAddMidPoints(startY, endY);
path.addPoint(endX, endY.add(TreeLayout.V_SPACING / 4.));
source.translateXProperty().addListener((observable, oldValue, newValue) -> {
checkAndAddMidPoints(startY, endY);
});
target.translateYProperty().addListener((observable, oldValue, newValue) -> {
checkAndAddMidPoints(startY, endY);
});
source.translateXProperty().addListener((observable, oldValue, newValue) -> {
checkAndAddMidPoints(startY, endY);
});
target.translateYProperty().addListener((observable, oldValue, newValue) -> {
checkAndAddMidPoints(startY, endY);
});
// Change the X of the midpoints depending on whether the target is above, below, or at the same
// level as the source
midLineX.bind(new When(target.rowLocationProperty.subtract(source.rowLocationProperty).lessThan(0))
.then(new When(target.columnLocationProperty.subtract(source.columnLocationProperty).greaterThan(0))
.then(endX.add(TreeLayout.H_SPACING / 2.))
.otherwise(new When(target.columnLocationProperty.subtract(source.columnLocationProperty).lessThan(0))
.then(startX.add(TreeLayout.H_SPACING / 2.))
.otherwise(startX)))
.otherwise(new When(target.columnLocationProperty.subtract(source.columnLocationProperty).greaterThan(0))
.then(endX.add(TreeLayout.H_SPACING / 2.))
.otherwise(new When(target.columnLocationProperty.subtract(source.columnLocationProperty).lessThan(0))
.then(startX.add(TreeLayout.H_SPACING / 2.))
.otherwise(startX))));
if(source.getCellType() != Cell.CellType.BOTH || target.getCellType() != Cell.CellType.BOTH){
path.setDashed(true);
}
getChildren().add(path);
visible = new SimpleBooleanProperty(false);
visibleProperty().bind(source.visibleProperty().and(target.visibleProperty())
.and(allVisible.or(visible)));
source.edges.add(this);
target.edges.add(this);
}
/**
* Checks the start and endpoints to see if any midpoints are necessary for drawing the line
* between them correctly. If the endpoints are more than 1 column apart and, the midpoints
* are added at the calculated x value
* @param startY the starting y coordinate of this edge
* @param endY the ending y coordinate of this edge
*/
private void checkAndAddMidPoints(DoubleBinding startY, DoubleBinding endY){
if(target.rowLocationProperty.get() - source.rowLocationProperty.get() > 1
|| target.rowLocationProperty.get() - source.rowLocationProperty.get() < 0){
if(!addedMidPoints){
path.addPoint(midLineX.add(0), startY.subtract(TreeLayout.V_SPACING/3.), 1);
path.addPoint(midLineX.add(0), endY.add(TreeLayout.V_SPACING/2.), 2);
this.addedMidPoints = true;
}
}else{
if(addedMidPoints){
path.removePoint(2);
path.removePoint(1);
this.addedMidPoints = false;
}
}
}
/**
* @param enable whether to set this edge as visible or not
*/
public void setHighlighted(boolean enable){
this.visible.set(enable);
}
public Cell getSource() { return this.source; }
public Cell getTarget() { return this.target; }
public void resetDashed() {
if(source.getCellType() != Cell.CellType.BOTH || target.getCellType() != Cell.CellType.BOTH)
path.setDashed(true);
else
path.setDashed(false);
}
}
|
Not everyone is happy to see Obama go. Many foreigners would love to have him back. Then the federal government would be sure to keep using our money to take away our jobs and give them to people from other countries:
A pro-immigrant program was expanded under President Obama that paid U.S. firms $2.7 billion to hire 180,000 foreign “students,” jobs that likely otherwise would have gone to Americans, according to a new report. The so-called “Optional Practical Training” was supposedly set up for foreign students but actually included no training and put college graduates in the high-paying jobs for three years. The Center for Immigration Studies, which on Friday urged President Trump to stop the program, estimated that the jobs paid $60,000, suggesting a total of $11 billion in annual wages lost to American workers, over $32 billion over three years.
The program paid companies a $10,000–$15,000 bonus to hire foreigners, on top of the bonus of evading payroll taxes for Social Security and Medicare. No wonder the workforce participation rate has been cratering.
On a tip from Stormfax. |
The Ethics of Investing in Cryptocurrencies Much has been written about the sudden rise of cryptocurrencies, but there remains a glaring gap in the literature as to whether investing in cryptocurrencies is ethical. This first-of-its-kind Article aims to fill that gap by providing an in-depth ethical analysis based on a classical utilitarian framework comparing arguments for and against cryptocurrency investing. Topics covered include traditional views of ethical investing, environmental considerations, the support of illegal transactions, diverting funds from traditional investments which provide more societal benefit, unique U.S. considerations, efficacy as currency, and corporate social responsibility. Such analysis invites future research into this emerging, multi-trillion-dollar industry. |
Radiochemical processing of activated specimens of vanadiumchromiumtitanium alloy The extraction part of the technological scheme for radiochemical separation of components of irradiated vanadiumchromiumtitanium (VCrTi) alloy and for their purification from metallic activation products was tested on the whole using activated alloy specimens. It was shown that the replacement of the acid re-extraction of vanadium with a peroxide re-extraction and of the acid re-extraction of chromium with an alkaline re-extraction substantially improves the characteristics of the extraction reprocessing of the activated VCrTi alloy. In particular, the durations of the vanadium and chromium re-extractions were shortened by about an order of magnitude, the outputs of these alloy components increased, vanadium purification from rare-earth metals became twice as great, and chromium decontamination from cobalt increased by two orders of magnitude. |
We’ve been keeping a close eye on SiliconDust for many years, but even more so since they announced the HDHomeRun DVR. It’s been a few months since we’ve heard much, but they were able to answer many of our questions when we met with them at CES this week.
Everyone wants to know when HDHomeRun DVR is going to be released. Their plan is to launch a release candidate (RC) in Q1 this year. That RC will include over the air (OTA) and unencrypted cable support in the United States, Canada, U.K., New Zealand, most of Western Europe, and Finland. For those of you with copy-protected channels using the HDHomeRun Prime, unfortunately you’re going to need to a wait a little longer. They’ve not forgotten about you, and there’s been a tremendous amount of work in making sure they will be able to support the capability on multiple platforms. They also need to make sure they do it right otherwise they could face massive fines. So expect support for copy-protected cable to come after the official release. The release candidate period is expected to last for two to four weeks.
There’s one last thing to remind those of you who were Kickstarter backers about. As part of your pledge you’re receiving a one-year subscription to the HDHomeRun DVR service. Don’t worry, because your year of service hasn’t even started yet. It won’t start until they’ve officially released the product.
One thing that you may or may not have noticed over the New Year holiday is that SiliconDust changed the guide data provider in many regions. Previously they were using multiple sources for different regions. Over the New Year holiday they completed the transition to put everyone on Gracenote. If you’re seeing any guide data issues, make sure that your tuners are using the latest firmware.
There’s another initiative that SiliconDust would like to make their customers aware of. They recently released a redesigned version of the HDHomeRun Extend. They were able to remove the fan from the device and simply use a better heatsink to keep the temperatures down. If you’ve got a model with a fan in it, you can send it to SiliconDust to have them swap the fan out for the new heatsink.
Lastly, SiliconDust continues to work with other partners. For example we discussed recently that some Samsung TVs were able to natively connect to HDHomeRun tuners. Unfortunately that functionality was disabled shortly after it was released. It turns out the firmware that enabled it was never mean to be released. SiliconDust continues to work with Samsung to get that feature optimized and turned back on. Maybe you’ve purchased an LG TV because you love their WebOS user interface. If so, you’ll be pleased to know that SiliconDust is also in talks with the Korean manufacturer to enable playback on their TVs also. |
<reponame>vtta2008/pipelineTool
# -*- coding: utf-8 -*-
"""
Script Name: TaskInfo.py
Author: <NAME>/Jimmy - 3D artist.
Description:
"""
# -------------------------------------------------------------------------------------------------------------
""" Import """
import json
from pyPLM.Core import Date, Time
from pyPLM.Widgets import GroupBox, VBoxLayout, Label
from PLM.cores import sqlUtils
from PLM.cores.models import Task
from PLM.utils import create_datetime
class TaskInfo(GroupBox):
key = 'TaskInfo'
def __init__(self, task):
super(TaskInfo, self).__init__()
self.database = sqlUtils()
with open(task, 'r') as f:
self._data = json.load(f)
self.setMaximumWidth(100)
self.setTitle(self._data['id'])
self.layout = VBoxLayout()
self._id = self._data['id']
self._name = self._data['name']
self._mode = self._data['mode']
self._type = self._data['type']
self._teamID = self._data['teamID']
self._projectID = self._data['projectID']
self._organisationID = self._data['organisationID']
self._details = self._data['details']
self._hour = int(self._data['endtime'].split(':')[0])
self._minute = int(self._data['endtime'].split(':')[1])
self._second = int(self._data['endtime'].split(':')[2])
self._day = int(self._data['enddate'].split('/')[0])
self._month = int(self._data['enddate'].split('/')[1])
self._year = int(self._data['enddate'].split('/')[2])
self.start = create_datetime(Time.currentTime().hour(), Time.currentTime().minute(),
Time.currentTime().second(), Date.currentDate().day(),
Date.currentDate().month(), Date.currentDate().year())
self.end = create_datetime(self._hour, self._minute, self._second, self._day, self._month, self._year)
try:
self.username = [self.database.query_table('curUser')[0]]
except (ValueError, IndexError):
self.username = []
self.task = Task(self._id, self._name, self._mode, self._type,
self._teamID, self._projectID, self._organisationID,
self.start, self.end, self._details)
self._countdown = '{0}:{1}:{2}'.format(self.task.hours, self.task.minutes, self.task.seconds)
self.task.countdown.connect(self.update_countdown)
self.task_status = Label({'txt': '{0}'.format(self.task.status)})
self.task_duedate = Label({'txt': '{0}'.format(self.task._enddate)})
self.task_duetime = Label({'txt': '{0}'.format(self.task._endtime)})
self.task_countdown = Label({'txt': '{0}'.format(self._countdown)})
self.layout.addWidget(self.task_status)
self.layout.addWidget(self.task_duedate)
self.layout.addWidget(self.task_duetime)
self.layout.addWidget(self.task_countdown)
self.setLayout(self.layout)
self.setMaximumSize(100, 120)
def update_countdown(self, val):
if self.task.status == 'Overdued':
self.task_status.setStyleSheet('color: red')
elif self.task.status == 'Urgent':
self.task_status.setStyleSheet('color: orange')
else:
self.task_status.setStyleSheet('color: green')
return self.task_countdown.setText(val)
@property
def id(self):
return self._id
@property
def mode(self):
return self._mode
@property
def type(self):
return self._type
@property
def project(self):
return self._projectID
@property
def organisation(self):
return self._organisationID
@property
def hour(self):
return self._hour
@property
def minute(self):
return self._minute
@property
def second(self):
return self._second
@property
def day(self):
return self._day
@property
def month(self):
return self._month
@property
def year(self):
return self._year
@id.setter
def id(self, val):
self._id = val
@mode.setter
def mode(self, val):
self._mode = val
@type.setter
def type(self, val):
self._type = val
@project.setter
def project(self, val):
self._projectID = val
@organisation.setter
def organisation(self, val):
self._organisationID = val
@hour.setter
def hour(self, val):
self._hour = val
@minute.setter
def minute(self, val):
self._minute = val
@second.setter
def second(self, val):
self._second = val
@day.setter
def day(self, val):
self._day = val
@month.setter
def month(self, val):
self._month = val
@year.setter
def year(self, val):
self._year = val
# -------------------------------------------------------------------------------------------------------------
# Created by panda on 2/12/2019 - 10:49 PM
# © 2017 - 2018 DAMGteam. All rights reserved |
EVANSTON - Professors Loren Ghiglione, a champion of Native American scholarship and inclusion on campus, and E. Patrick Johnson, a prolific arts scholar and performer who founded the community-focused Black Arts Initiative, are the inaugural recipients of the Provost Award for Faculty Excellence in Diversity and Equity.
Each will receive $5,000 to further their diversity initiatives, and12 inaugural recipients of the Provost Grant for Faculty Innovation in Diversity and Equity include both individual faculty members and groups of researchers. The grants to the recipients range from $5,000 to $20,000.
Through these two programs, Northwestern University’s Office of the Provost has awarded nearly $165,000 to faculty to build a more diverse, inclusive and equitable climate on campus. The programs are aimed at enhancing diversity across the spectrum, including race, gender, religion, socioeconomic status, age and political affiliation.
The grant recipients have proposed projects that will, for example, enhance female representation in STEM fields, expand media options for LGBT audiences and better serve individuals with visual, hearing or physical impairments.
“Understanding the diverse groups that make up our nation and the world is central to the critical thinking that is a hallmark of a university education,” Northwestern Provost Dan Linzer said. “And it is a privilege to honor faculty who, through their teaching and scholarship, are exploring diversity across disciplines to understand both the historic, economic and psychological consequences of biases as well as the incredibly rich ways that our differences contribute to our history, culture and art.”
The Provost Awards and Provost Grants will be given each year. The award nomination and grant application processes for 2017-18 will be announced on the Office of the Provost website during spring quarter 2017.
Recipients of Provost Awards for Faculty Excellence in Diversity and Equity Ghiglione and Johnson are recognized as exemplars working collaboratively to build a more diverse, inclusive and equitable climate at Northwestern. Loren Ghiglione , professor in the Medill School of Journalism, Media, Integrated Marketing Communications, is recognized for his outstanding and ongoing work to illuminate and support the Native American population on campus. That includes his leadership of the 2015-16 One Book One Northwestern steering group and the 2016-17 Native American and Indigenous Peoples Steering Group, his successful efforts to recruit Native American faculty and his engagement of these issues with undergraduate students.
E. Patrick Johnson , chair of African-American Studies in the Weinberg College of Arts and Sciences and Carlos Montezuma Professor of Performance Studies in the School of Communication, is recognized for his tireless work in building an interdisciplinary research, practice and community-focused Black Arts Initiative at Northwestern. |
<filename>src/webparts/videoRecord/VideoRecordWebPart.ts
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import * as strings from 'VideoRecordWebPartStrings';
import { VideoRecord } from './components/VideoRecord';
import { IVideoRecordProps } from './components/IVideoRecordProps';
import { sp } from "@pnp/sp";
import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy } from '@pnp/spfx-property-controls/lib/PropertyFieldListPicker';
export interface IVideoRecordWebPartProps {
list: string;
}
export default class VideoRecordWebPart extends BaseClientSideWebPart<IVideoRecordWebPartProps> {
public onInit(): Promise<void> {
return super.onInit().then(_ => {
// other init code may be present
sp.setup({
spfxContext: this.context
});
});
}
public render(): void {
const element: React.ReactElement<IVideoRecordProps> = React.createElement(
VideoRecord,
{
list: this.properties.list,
onConfigure: () => {
this.context.propertyPane.open();
}
}
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyFieldListPicker('list', {
label: strings.ListFieldLabel,
selectedList: this.properties.list,
includeHidden: false,
orderBy: PropertyFieldListPickerOrderBy.Title,
disabled: false,
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
context: this.context,
onGetErrorMessage: null,
deferredValidationTime: 0,
key: 'listPickerFieldId'
})
]
}
]
}
]
};
}
}
|
Since the advent of IE 6, Microsoft has lost focus on Internet Explorer. Having captured a dominant market share in the browser wars, the company slowed updates and has been sagging in terms of providing the features that make competing browsers rather attractive (i.e., Mozilla and integrated pop-up blocking, tabbed browsing, etc.). Indeed, a year ago the company was hinting strongly that Internet Explorer would no longer be developed as a standalone application, but with increasing competition and the lengthened Longhorn release schedule, the company appears to have changed its mind. Already with Service Pack 2 we're going to see the introduction of improvements to the browser, but could a major update of the browser be in the works before the introduction of Longhorn?
In my new job role I'm very interested in hearing about what you the customers would like to see. I know that there are many requests already out there around CSS support, transparent PNG support etc. and we do read every single one of them. I can say though that somewhat vague requests for "better standards support" are not as useful as a specific example of what you'd like to see changed and specifically why it would improve things. Obviously I cannot guarrantee [sic] that every request will be implemented but please let me know what you'd like to see. Probably the best place to do that is on the Internet Explorer Wiki on Channel 9 or post here.
I had to chuckle when I first read that. "Why [better standards support] would improve things"? Maybe because they're, uh, standards? Indeed, they can be found published at the W3C, among other places. Nevertheless, all browsers have their standards issues, and chances are that Microsoft is more interested in speeding up the browsing experience and implementing new features than necessarily overhauling their renderer. What would you like to see added to Internet Explorer? |
<filename>src/components/selection/selection.tsx
import { Component, Host, h, Element, Prop, Watch } from '@stencil/core';
@Component({
tag: 'hc-selection',
styleUrl: 'selection.scss',
shadow: true
})
export class Selection {
@Element() el:HTMLElement
@Prop() titles: string = '请选择'
@Prop() visible: boolean = false
@Prop() round: boolean = true
@Prop() data: string;
dataArr;
componentDidLoad () {
}
@Watch('data')
dataHandle (value: string) {
this.dataArr = eval(`(${value})`)
console.log(this.dataArr)
}
render() {
return (
<Host>
</Host>
);
}
}
|
What is the Ad hoc Ethical Committee?
The Ad hoc Ethical Committee is an informal body of three appointed members who provide advice to the Commission, particularly on former commissioners’ revolving doors moves, but potentially on all matters relating to the Code of Conduct for Commissioners.
The committee’s remit is extremely limited. It can only advise, but not decide, on revolving door moves, via opinions submitted to the Commission. These opinions are not pro-actively published by the Commission but can be released through access to documents, as was done in this case. Ultimately, it is the commissioners themselves who, during college meetings, are to judge their ex-colleagues and determine whether or not their new roles are compatible with the Code of Conduct and the wider EU treaty.
Aside from this, the committee is also limited in its activities as it cannot act proactively; it can only look at those matters referred to it by the Commission.
Who sits on the Ad hoc Ethical Committee?
As of July 2016, the members are Mr Christiaan Timmermans, Ms Dagmar Roth-Behrendt and Mr Heinz Zourek.
Of the three, Dagmar Roth-Behrendt is the most well-known. This German social democrat stood down as an MEP in 2014 after five terms in the EU legislature. During her time in office, she sat on the Legal Affairs committee and was rapporteur on, among other dossiers, the 2012 reform of the Staff Regulations (which contain the revolving door rules and other terms of employment for EU institution staff). She is now a special adviser to Commissioner Andriukaitis (Health & Food Safety), focussing on “assessing the situation of executive agencies of DG SANTE”. Roth-Behrendt’s husband is Horst Reichenbach, who has led several Commission departments before heading the Commission’s task force for Greece 2011-15. He is now a director of the European Bank for Reconstruction – and a special adviser to Commissioner Moscovici (Economic and Financial Affairs, Taxation and Customs). Unsurprisingly, Roth-Behrendt and Reichenbach recently made it onto Politico’s list of “Brussels’ most notable political power couples”.
Heinz Zourek is another established EU player. He was in the Commission, specifically as director-general at DG for Taxation and the Customs Union until December 2015, after first joining the Commission in 1995. He was also a special adviser on the financial transaction tax to Commissioner Moscovici (until 31 July 2016), and was inadvertently caught up in a 2015 cash-for-access scandal when he refused to meet the influential British politician Jack Straw who sought to lobby EU officials on behalf of paying clients.
Christiaan Timmermans is a former judge at the Court of Justice (2000-2010) and was previously at the Commission’s legal service.
Since members of the Ad hoc Ethical Committee for commissioners’ ethics are appointed by commissioners themselves, the committee's independence might be considered limited. But this concern is compounded by the fact that the Juncker Commission appointed Roth-Behrendt and Zourek, both of whom had already been appointed by commissioners as their special advisers. Surely such proximity puts them in an awkward and potentially conflicting situation?
Given the heavy criticism levelled at the Commission when it appointed Michel Petite as chairman of its ethics committee back in 2009, it is particularly surprising that the Juncker Commission chose to recruit for its Ad hoc Ethical Committee in a similarly questionable manner. In 2012, then Commission President Barroso decided to re-appoint Michel Petite as Ad hoc Ethical Committee chairman, despite questions of judgement raised about Petite's own career choices. Petite had had a controversial spin through the revolving door, from heading up the Commission's legal service, to moving to global law firm Clifford Chance in 2008. Petite lobbied the Commission on behalf of Clifford Chance’s clients, including ones from the tobacco industry. Following an NGO complaint criticising the re-appointment of a lobbyist as chairman of the ethics committee, the European Ombudsman protested in writing to Barroso and recommended that Petite be replaced. Petite’s ‘resignation’ from the Ad hoc Ethical Committee was announced a few days later.
What is the Ad hoc Ethical Committee likely to say on the Barroso case?
As the committee in its current set-up only ‘took office’ in July 2016, there is no precedent we could use to assess the advice it will provide on revolving door moves. Barroso's move to Goldman Sachs will be the first time the committee is tasked with assessing a revolving door move. Previous ethics committee have approved almost all new jobs proposed by ex-commissioners, but there have been some notable exceptions.
During the 18-month period between November 2014 and April 2016 which required new roles of Barrosso II commissioners to be authorised by the Juncker Commission, opinions given by the Ad hoc Ethical Committee in its previous constellation led two former commissioners to withdraw a total of three requests for the approval of such new jobs. While the Commission refused to provide any further information on the positions concerned in these withdrawals, former education commissioner Androulla Vassiliou confirmed to CEO that the committee's opinion had signaled potential conflicts of interest connected to her two proposed roles. She therefore decided to reject the offers and did not proceed to seek Commission authorisation for the roles.
An earlier Ad hoc Ethical Committee also issued a negative opinion in the case of former internal market commissioner Charlie McCreevy who in 2010 and in the wake of the financial crash was keen to take a new role at the NBNK Investments bank. Significant controversy arose over this looming revolving door case, including critical media coverage and NGO complaints. After the Ad hoc Ethical Committee provided its negative opinion and the Commission subsequently threatened to reject the role, McCreevy ultimately withdrew his request for authorisation. Nevertheless, the Commission was happy to authorise McCreevy to take up another controversial role - with prominent European low-cost airline Ryanair.
Notwithstanding these examples, CEO's 2015 report points to several problematic new roles taken up by former commissioners about which both the Ad hoc Ethical Committee and the College of Commissioners failed to be as critical as we would have expected.
The need for professional, independent and truly transparent decision-making
It is clear that the whole decision-making process around departing commissioners’ revolving door moves must be reformed - a reform that must focus on creating a truly independent and transparent ethics committee. Members of the College, who will themselves one day be ex-commissioners, should not be involved in the appointment of committee members whatsoever, nor should they have any part in the decision-making on revolving doors cases.
Instead, we need professional, independent and truly transparent decision-making. As part of wider reform of the Code of Conduct for Commissioners, the Alliance for Lobbying Transparency and Ethics Regulation (ALTER-EU) has advised for the Ad hoc Ethical Committee in its current form to be replaced by a fully independent ethics committee of experts, who have no links to the EU institutions and are recruited from member states' ethics and administration systems. This fully independent ethics committee should be responsible for the whole authorisation process, supported by a well-resourced secretariat with investigative powers.
The case of former industry commissioner Günter Verheugen drives home the dangers of leaving the College of Commissioners to authorise revolving door. When Verheugen left the Commission in 2010, he failed to inform the institution that he set up a consultancy firm, nor did he seek authorisation for it. Once he restrospectively did, the Ad hoc Ethical Committee did not approve Verheugen's involvement with the consultancy. The Commission went on to authorise the role regardless, flat out ignoring the committee's advice.
This illustrates why revolving doors decision-making on commissioners’ new roles should be taken entirely out of the hands of the College - and that will entail a serious revamp of the ethical committee.
Update: Info on Mr Zourek was updated on 20 September 2016. |
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.oauth.uma.permission.service.impl;
import org.wso2.carbon.identity.oauth.uma.permission.service.PermissionService;
import org.wso2.carbon.identity.oauth.uma.permission.service.ReadPropertiesFile;
import org.wso2.carbon.identity.oauth.uma.permission.service.dao.PermissionTicketDAO;
import org.wso2.carbon.identity.oauth.uma.permission.service.exception.PermissionDAOException;
import org.wso2.carbon.identity.oauth.uma.permission.service.exception.UMAResourceException;
import org.wso2.carbon.identity.oauth.uma.permission.service.model.PermissionTicketModel;
import org.wso2.carbon.identity.oauth.uma.permission.service.model.Resource;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;
/**
* PermissionServiceImpl service is used for permission registration.
*/
public class PermissionServiceImpl implements PermissionService {
private static final String UTC = "UTC";
@Override
public PermissionTicketModel issuePermissionTicket(List<Resource> resourceList, int tenantId) throws
UMAResourceException, PermissionDAOException {
PermissionTicketModel permissionTicketModel = new PermissionTicketModel();
ReadPropertiesFile.readFileConfigValues(permissionTicketModel);
//TODO: Make this an extension point.
String ticketString = UUID.randomUUID().toString();
permissionTicketModel.setTicket(ticketString);
permissionTicketModel.setCreatedTime(Calendar.getInstance(TimeZone.getTimeZone(UTC)));
permissionTicketModel.setStatus("ACTIVE");
permissionTicketModel.setTenantId(tenantId);
PermissionTicketDAO.persistPTandRequestedPermissions(resourceList, permissionTicketModel);
return permissionTicketModel;
}
}
|
#include "Quaternion.hpp"
#include "vec3.hpp"
#include "Math.hpp"
#include <cassert>
using namespace math;
Quaternion::Quaternion(const float p_x, const float p_y, const float p_z, const float p_w) {
set(p_x, p_y, p_z, p_w);
normalize();
}
Quaternion::Quaternion(const Quaternion& p_other) {
set(p_other);
}
Quaternion::Quaternion() {
setIdentity();
}
Quaternion::~Quaternion() {
}
#if 0
void Quaternion::toMatrix(Matrix& p_out) {
const float matrix[3][3] =
{
{1 - 2*m_y*2 - 2*m_z*2, 2*m_x*m_y - 2*m_w*m_z, 2*m_x*m_z + 2*m_w*m_y},
{2*m_x*m_y + 2*m_w*m_z, 1 - 2*m_x*2 - 2*m_z*2, 2*m_y*m_z - 2*m_w*m_x},
{2*m_x*m_z - 2*m_w*m_y, 2*m_y*m_z + 2*m_w*m_x, 1 - 2*m_x*2 - 2*m_y*2}
};
p_out.set(matrix);
}
#endif
float Quaternion::length() const {
return squareRoot( lengthSquared() );
}
float Quaternion::lengthSquared() const {
return square(m_x) + square(m_y) + square(m_z) + square(m_w);
}
bool Quaternion::isUnit() const {
const float ls = lengthSquared();
return equal(ls, 1.0f);
}
void Quaternion::setIdentity() {
m_x = m_y = m_z =0.0f;
m_w = 1.0f;
}
void Quaternion::setEuler(const float p_x, const float p_y, const float p_z) {
const vec3 aAxis((float)sin(p_x/2), 0, 0),
bAxis(0, (float)sin(p_y/2), 0),
cAxis(0, 0, (float)sin(p_z/2));
const float aAngle = (float) cos(p_x/2),
bAngle = (float) cos(p_y/2),
cAngle = (float) cos(p_z/2);
const Quaternion b(bAxis, bAngle), c(cAxis, cAngle);
setRotation(aAxis,aAngle);
(*this) *= b;
(*this) *= c;
normalize();
}
void Quaternion::conjugate(){
set( -m_x, -m_y, -m_z, m_w );
}
Quaternion Quaternion::getConjugate() const {
Quaternion temp(*this);
temp.conjugate();
return temp;
}
const Quaternion& Quaternion::operator*=(const Quaternion& p_quat) {
vec3 v1(m_x, m_y, m_z);
vec3 v2(p_quat.m_x, p_quat.m_y, p_quat.m_z);
float sc1 = m_w;
float sc2 = p_quat.m_w;
float scalar = sc1*sc2 - (v1 dot v2);
vec3 result = v2*sc1 + v1*sc2 + (v1 cross v2);
m_x = result.getX();
m_y = result.getY();
m_z = result.getZ();
m_w = scalar;
normalize();
return *this;
}
Quaternion Quaternion::operator*(const Quaternion& b) const {
Quaternion temp(*this);
temp *= b;
return temp;
}
void Quaternion::set(const float p_x, const float p_y, const float p_z, const float p_w) {
m_x = p_x;
m_y = p_y;
m_z = p_z;
m_w = p_w;
normalize();
}
void Quaternion::set(const Quaternion& p_quat) {
set(p_quat.m_x, p_quat.m_y, p_quat.m_z, p_quat.m_w);
}
Quaternion::Quaternion(const vec3& angle, const float theta) {
setRotation(angle, theta);
}
void Quaternion::setRotation(const vec3& pAxis, const float theta) {
const float halfTheta = theta/2;
const float sinHalfTheta = (float) sin(halfTheta);
const float cosHalfTheta = (float) cos(halfTheta);
const vec3 axis = pAxis.getNormalized();
m_x = axis.getX() * sinHalfTheta;
m_y = axis.getY() * sinHalfTheta;
m_z = axis.getZ() * sinHalfTheta;
m_w = cosHalfTheta;
normalize();
}
/*void Quaternion::toAxisAngle(vec3* axis, float* theta) const {
assert(axis);
assert(theta);
assert( equal(1.0f, length()));
//normalize();
const float scale = squareRoot(square(m_x) + square(m_y) + square(m_z));
// const float scale = (float) sin(angle);
if( equal(scale, 0.0f) ){
*theta = 0.0f;
*axis = vec3(0.0f, 0.0f, 1.0f);
}
else {
const float halfAngle = (float) acos(m_w);
assert(0<=halfAngle);
assert(PI >= halfAngle);
const float angle = 2.0f * halfAngle;
*axis = vec3( m_x / scale,
m_y / scale,
m_z / scale );
axis->normalize();
*theta = angle;
}
}*/
void Quaternion::toAxisAngle(vec3* axis, float* theta) const {
assert(axis);
assert(theta);
const float len = length();
assert( equal(1.0f, length()) ); // normalised
const float cosAngle = m_w;
const float angle = acos(cosAngle) * 2 ;
float sinAngle = squareRoot(1 - square(cosAngle));
if( abs(sinAngle) < 0.0005f ) {
sinAngle = 1;
}
*axis = vec3( m_x / sinAngle,
m_y / sinAngle,
m_z / sinAngle);//.getNormalized();
*theta = angle;
const float l = axis->getLength();
}
float Quaternion::normalize() {
float l = length();
m_x /= l;
m_y /= l;
m_z /= l;
m_w /= l;
return l;
}
Quaternion::Quaternion(const vec3& vec) {
set(vec.getX(), vec.getY(), vec.getZ(), 0.0f);
}
/*
// optimized a little 2006-02-14
vec3 Quaternion::rotateVectorAroundOrigin(const vec3& v) const {
Quaternion q1 = getConjugate();
Quaternion q2(v);
//Quaternion q3(*this);
q2 *= (*this); // previously q3
q1 *= q2;
vec3 rv(q1.m_x, q1.m_y, q1.m_z);
rv.normalize();
return rv;
}
*/
// optimized a little 2006-02-14
vec3 Quaternion::rotateVectorAroundOrigin(const vec3& vec) const {
const Quaternion point(vec);
const Quaternion result = (*this) * point * getConjugate();
return vec3(result.m_x, result.m_y, result.m_z);
}
vec3 Quaternion::getIn() const {
return rotateVectorAroundOrigin(op::vec3::zAxisNegative);
}
vec3 Quaternion::getUp() const {
return rotateVectorAroundOrigin(op::vec3::yAxisPositive);
}
vec3 Quaternion::getRight() const {
return rotateVectorAroundOrigin(op::vec3::xAxisPositive);
}
const float Quaternion::getX() const {
return m_x;
}
const float Quaternion::getY() const {
return m_y;
}
const float Quaternion::getZ() const {
return m_z;
}
const float Quaternion::getW() const {
return m_w;
}
bool Quaternion::operator==(const Quaternion& pOther) const {
return math::equal(getX(), pOther.getX()) &&
math::equal(getY(), pOther.getY()) &&
math::equal(getZ(), pOther.getZ()) &&
math::equal(getW(), pOther.getW());
}
bool Quaternion::operator!=(const Quaternion& pOther) const {
return !(*this == pOther);
}
void Quaternion::lookAt(const vec3& pFrom, const vec3& pTo, const vec3& pUp) {
assert(pUp.isUnit());
lookInDirection((pTo-pFrom).getNormalized(), pUp);
}
void Quaternion::lookInDirection(const vec3& pDirection, const vec3& pUp) {
assert(pDirection.isUnit());
assert(pUp.isUnit());
const vec3 v = (pDirection cross pUp).getNormalized();
const vec3 u = v cross pDirection;
const vec3 n = -pDirection;
#define vecAsArray(v) {v.getX(), v.getY(), v.getZ()}
const float mat[3][3] = { vecAsArray(v), vecAsArray(u), vecAsArray(n) };
fromMatrix3(mat);
}
// this code is grabbed from somwhere
// rework with my own code from mathfaq
void Quaternion::fromMatrix3(const float mat[3][3])
{
int NXT[] = {1, 2, 0};
float q[4];
// check the diagonal
float tr = mat[0][0] + mat[1][1] + mat[2][2];
if( tr > 0.0f)
{
float s = (float)squareRoot(tr + 1.0f);
m_w = s * 0.5f;
s = 0.5f / s;
m_x = (mat[1][2] - mat[2][1]) * s;
m_y = (mat[2][0] - mat[0][2]) * s;
m_z = (mat[0][1] - mat[1][0]) * s;
}
else
{
// diagonal is negative
// get biggest diagonal element
int i = 0;
if (mat[1][1] > mat[0][0]) i = 1;
if (mat[2][2] > mat[i][i]) i = 2;
//setup index sequence
int j = NXT[i];
int k = NXT[j];
float s = (float)squareRoot((mat[i][i] - (mat[j][j] + mat[k][k])) + 1.0f);
q[i] = s * 0.5f;
if (s != 0.0f) s = 0.5f / s;
q[j] = (mat[i][j] + mat[j][i]) * s;
q[k] = (mat[i][k] + mat[k][i]) * s;
q[3] = (mat[j][k] - mat[k][j]) * s;
m_x = q[0];
m_y = q[1];
m_z = q[2];
m_w = q[3];
}
}
// from math-faq
/*void Quaternion::fromMatrix3(const float pMatrix[3][3]) {
const real trace = pMatrix[0][0] + pMatrix[1][1] + pMatrix[2][2] + 1;
#define mat(c, r) pMatrix[r][c]
if( trace>0.0f ) {
// instant calculation
const float s = 0.5f / squareRoot(trace);
m_w = 0.25f / s;
m_x = (mat(2, 1) - mat(1, 2)) * s;
m_y = (mat(0, 2) - mat(2, 0)) * s;
m_z = (mat(1, 0) - mat(0, 1)) * s;
}
else {
// diagonal is negative, identify the largest colum digital value
int col = 0;
#define TEST_MATRIX(INDEX) if( pMatrix[col][col] < pMatrix[INDEX][INDEX]) col = INDEX
TEST_MATRIX(1);
TEST_MATRIX(2);
#undef TEST_MATRIX
switch(col) {
case 0:
{
const real s = squareRoot( 1.0f + pMatrix[0][0] - pMatrix[1][1] - pMatrix[2][2] ) * 2;
const real oneOverS = 1.0f / s;
m_x = 0.5f * oneOverS;
m_y = (mat(0, 1) + mat(1, 0) ) * oneOverS;
m_z = (mat(0, 2) + mat(2, 0) ) * oneOverS;
m_w = (mat(1, 2) + mat(2, 1) ) * oneOverS;
}
break;
case 1:
{
// something is wrong here
const real s = squareRoot( 1.0f + pMatrix[1][1] - pMatrix[0][0] - pMatrix[2][2] ) * 2;
const real oneOverS = 1.0f / s;
m_x = (mat(0, 1) + mat(1, 0) ) * oneOverS;
m_y = 0.5f * oneOverS;
m_z = (mat(1, 2) + mat(2, 1) ) * oneOverS;
m_w = (mat(2, 0) + mat(0, 2) ) * oneOverS;
}
break;
case 2:
{
const real s = squareRoot( 1.0f + pMatrix[2][2] - pMatrix[0][0] - pMatrix[1][1] ) * 2;
const real oneOverS = 1.0f / s;
m_x = (mat(0, 2) + mat(2, 0) ) * oneOverS;
m_y = (mat(1, 2) + mat(2, 1) ) * oneOverS;
m_z = 0.5f * oneOverS;
m_w = (mat(0, 1) + mat(1, 0) ) * oneOverS;
}
break;
default:
assert(0 && "This shouldn't happen, bad programming code before case");
}
}
#undef mat
}*/
/*Points in space, the physical things, are normally represented as 3 or 4
floats. The effect of a rotation on a collection of points can be
computed from the representation of the rotation, and here matrices seem
fastest, using three dot products. Using their own product twice,
quaternions are a bit less efficient. (They are usually converted to
matrices at the last minute.)
p2 = q p1 q^(-1)*/
/*math::vec3 Quaternion::rotateVector(const std::vec3& p_vector) {
math::vec3 vector;
q^(-1) = [-V,w]/(V.V+ww)
q p1 q^(-1);
}*/
/* Sequences of rotations can be interpolated, so that the object being
turned is rotated to specific poses at specific times. This motivated
<NAME>'s early use of quaternions in computer graphics, as
published in 1985. He used an analog of linear interpolation (sometimes
called "lerp") that he called "Slerp", and also introduced an analog of
a piecewise Bezier curve. A few years later in some course notes he
described another curve variation he called "Squad", which still seems
to be popular. Later authors have proposed many alternatives.
sin (1-t)A sin tA
Slerp(q1,q2;t) = q1 ---------- + q2 ------, cos A = q1.q2
sin A sin A
Squad(q1,a1,b2,q2;t) = Slerp(Slerp(q1,q2;t),
Slerp(a1,b2;t);
2t(1-t))
*/
// http://www.faqs.org/faqs/graphics/algorithms-faq/
#if 0
// from minorlogic in gamedev.net
inline void From2Vec( Quaternion& q, const vector3& from, const vector3& to ) {
vector3 c = cross(from, to);
float d = dot(from, to);
q.set( c.x, c.y, c.z, d + (float)sqrt( from.len_squared()*to.len_squared() ) );
// here we can take a 180 Deg case , "from" or "to" is 0 length
// by check that q.w close to 0
q.normalize();
}
//or simpler to understand :
inline void From2Vec( Quaternion& q, const vector3& from, const vector3& to ) {
vector3 c = cross(from, to);
float d = dot(from, to);
q.set( c.x, c.y, c.z, d );
q.normalize(); // prevent of "from" or "to" is not unit
q.w += 1.0f; // reducing angle by 2
q.normalize();
}
#endif
Quaternion Quaternion::slerp(const Quaternion& p_to, const float p_time) const {
float cosOmega = m_x * p_to.m_x +
m_y * p_to.m_y +
m_z * p_to.m_z +
m_w * p_to.m_w ;
const float sign = (cosOmega<0.0f) ? (-1.0f) : (1.0f);
cosOmega *= sign;
float scaleFrom;
float scaleTo;
const float DELTA = 0.0001f;
if( (1.0f-cosOmega) > DELTA ) {
// regular slerp
const float omega = acos(cosOmega);
const float sinOmega = sin(omega);
scaleFrom = sin((1.0f - p_time) * omega) / sinOmega;
scaleTo = sin(p_time * omega) / sinOmega;
}
else {
// from and to are close, do a linear interpolation to speed things up a little
scaleFrom = 1.0f - p_time;
scaleTo = p_time;
}
scaleTo *= sign; // save two multiplications
return Quaternion( (scaleFrom * m_x) + (scaleTo * p_to.m_x),
(scaleFrom * m_y) + (scaleTo * p_to.m_y),
(scaleFrom * m_z) + (scaleTo * p_to.m_z),
(scaleFrom * m_w) + (scaleTo * p_to.m_w)
);
}
#if 0
// gamasutra quat article ref:
// http://www.gamasutra.com/features/19980703/quaternions_01.htm
QuatSlerp(QUAT * from, QUAT * to, float t, QUAT * res)
{
float to1[4];
double omega, cosom, sinom, scale0, scale1;
// calc cosine
cosom = from->x * to->x + from->y * to->y + from->z * to->z
+ from->w * to->w;
// adjust signs (if necessary)
if ( cosom <0.0 ){
cosom = -cosom;
to1[0] = - to->x;
to1[1] = - to->y;
to1[2] = - to->z;
to1[3] = - to->w;
}
else {
to1[0] = to->x;
to1[1] = to->y;
to1[2] = to->z;
to1[3] = to->w;
}
// calculate coefficients
if ( (1.0 - cosom) > DELTA ) {
// standard case (slerp)
omega = acos(cosom);
sinom = sin(omega);
scale0 = sin((1.0 - t) * omega) / sinom;
scale1 = sin(t * omega) / sinom;
} else {
// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
scale0 = 1.0 - t;
scale1 = t;
}
// calculate final values
res->x = scale0 * from->x + scale1 * to1[0];
res->y = scale0 * from->y + scale1 * to1[1];
res->z = scale0 * from->z + scale1 * to1[2];
res->w = scale0 * from->w + scale1 * to1[3];
}
#endif |
<gh_stars>0
#ifndef VIRTUAL_FORCE_PRF_
#define VIRTUAL_FORCE_PRF_
#include "haptic_teleoperation/ForceField.h"
class VirtualForcePrf : public ForceField
{
public:
VirtualForcePrf(ros::NodeHandle & n_);
VirtualForcePrf() {std::cout << "default child constructor" << std::endl ; }
~VirtualForcePrf(){}
Eigen::Vector3d getForcePoint(geometry_msgs::Point32 & c_current , Eigen::Vector3d robot_vel) ;
void setMinDistance(double dmin);
void setMaxAcceleration( double amax);
void setCriticalAreaRadius(double rpz);
void setTimeAhead(double tahead);
double getMinDistance();
double getMaxAcceleration();
double getCriticalAreaRadius();
double getTimeAhead();
void setParameters(double dmin, double amax , double rpz ,double tahead ) ;
private:
double minDistance;
double maxAcceleration ;
double criticalAreaRadius ;
double timeAhead ;
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100005;
static vector<vector<int>> adj;
static int dp[MAX];
static int type[1000];
int bin(int lo, int x){
int l = 0;
int r = adj[x].size() - 1;
int index = 1000000;
while(l<= r){
int m = (l + r)/2;
if(adj[x][m] < lo){
l = m+1;
}
else{
index = min(adj[x][m], index);
r = m-1;
}
}
if(index == 1000000){
return -1;
}
return index;
}
int main(){
vector<int> t;
int n;
cin >> n;
string s;
cin >> s;
for(int i =0 ; i<1000; i++){
vector<int> temp;
adj.emplace_back(temp);
}
for(int i = 0; i<n; i++){
int x = s[i] - 'A';
adj[x].emplace_back(i);
//cout << x << " x" << endl;
type[x] = 1;
t.emplace_back(x);
}
int types = 0;
for(int i = 0; i<1000; i++){
types += type[i];
}
map<int, int> m;
int c = 0;
int ans = -1;
for(int i = 0; i<n; i++){
map<int, int>:: iterator it = m.find(t[i]);
if(it== m.end()){
m[t[i]] = 1;
c += 1;
}
if(c == types){
dp[0] = i;
break;
}
}
ans = dp[0] + 1;
//cout << ans << " ans" << endl;
for(int i = 1; i<=n- types; i++){
int r = t[i-1];
int stop = dp[i-1];
int index = bin(i, r);
//cout << i << " " << r << " " << index << " " << stop << endl;
if(index == -1){
break;
}
if(index <=stop){
dp[i] = dp[i-1];
}
else{
dp[i] = index;
}
ans = min(ans, dp[i] - i + 1);
}
cout <<ans;
return 0;
}
|
package no.nav.organisasjonforvalter.dto.responses;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
import static java.util.Objects.isNull;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BestillingStatus {
private String orgnummer;
private String miljoe;
private String uuid;
private List<ItemDto> itemDtos;
private StatusDTO status;
private String feilmelding;
public List<ItemDto> getItemDtos() {
if (isNull(itemDtos)) {
itemDtos = new ArrayList<>();
}
return itemDtos;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class ItemDto {
private Integer id;
private ItemStatus status;
public enum ItemStatus {INITIALIZING, NOT_STARTED, RUNNING, COMPLETED, ERROR, FAILED}
}
}
|
L = input()
T = len(L)
L = L.lower()
S = '.'
for i in range (T):
if not(L[i] in ('a','e','i','o','u','y')):
S = S + L[i] +'.'
P = len(S)
K = '.'
for i in range (1,P-1):
K = K + S[i]
print (K) |
/** Save industry-type build data. */
static void Save_ITBL()
{
for (int i = 0; i < NUM_INDUSTRYTYPES; i++) {
SlSetArrayIndex(i);
SlObject(_industry_builder.builddata + i, _industrytype_builder_desc);
}
} |
The present invention relates generally to air brake systems and more specifically for an air brake system and a relay valve to be used in a vehicle convertible between highway and railroad modes of use.
There has always been a great interest in the combined transportation of highway and rail vehicles. This has generally included the loading of road trailers onto flat bed rail cars which are then transported across the rails and then driven to location away from the rails. Efforts have also been made to equip trailers with road wheels and rail wheels such that the trailer itself forms both a road trailer and a rail car. One such vehicle is described in U.S. Pat. Nos. 4,202,276 and 4,202,277 to Browne et al. The major problem with the prior art system including that of the above-mentioned patents is that the designers have generally designed a brake system using highway technology and criteria which is unacceptable for use in a rail system.
As an example, the system in the aforementioned U.S. Patents use a straight air brake system to operate the brake. In this system the pressure and the brake pipe line are used to control a relay valve which in turn controls the brakes. This style of system had been used extensively in rail vehicles but has been replaced by ABD (air brake diaphragm) valves wherein the valve is responsive to modulation of the brake pipe pressure to produce its own brake control signal. A major advantage of the ABD valves is that they provide better control and quicker response as well as the capability of providing braking control for a further distant or longer length train.
Thus there exists a need for a braking system for a vehicle which is capable of highway and railway operation with a rail fluid braking system meeting the standards of the rail industry. |
DERBY COUNTY are Aston Villa’s “main challengers” for automatic promotion, David Prutton has claimed.
Derby currently sit second in the Championship table but Steve Bruce’s fifth-placed side are just three points behind after winning their last four games.
Cardiff City, Bristol City and Fulham occupy the remaining play-off spots and also have their eyes on a place in the Premier League.
Wolves look set to clinch the Championship title after building up a 12-point lead at the top of the table and Sky Sports pundit Prutton reckons the other promotion hopefuls are battling it out for second.
“You'd have Derby as the favourites right now as they occupy that spot and are on a good run themselves, and they're similar to Villa in how they've built their success this season on having a solid base, much like Cardiff as well,” he said. “The other teams around them such as Bristol City, Sheffield United and Fulham are often a little bit more cavalier in their approach.
“It's such a tight battle right now but if I had to narrow it down I'd say that Derby and Aston Villa are the main challengers for the top two, I can't split them though!
Prutton believes the pressure is on Bruce to restore Villa to the top-flight but he is confident the Championship promotion expert will fulfil his brief if he is given time.
He added: “[Bruce] has been as exasperated as anyone at their inconsistency at times this season, but he's always been very up front and honest when he's realised his team weren't good enough. Their last defeat in the league at Brentford on Boxing Day was a perfect example of that.
“I think he's proved he's got what it takes to get them to the Premier League, whether it happens this season or not.
“Villa were on the slide when he came in and it's not always easy to turn that around, regardless of the size of the club.
Should Villa win promotion this season, Prutton believes owner Tony Xia would have to get his chequebook out once again.
He added: “They would obviously have to strengthen their squad, as any side does after getting promotion.
“They've got an experienced Premier League manager but there's no doubt they'd need another striker and maybe a couple of others as well.
“Would John Terry fancy another season in the Premier League? You get the feeling he'd want to prove himself at that level again, despite having done it for so many years already. |
Establishment of Authenticated Secret Session Keys Using Digital Signature Standard ABSTRACT A scheme for establishing authenticated Diffie-Hellman based shared keys using Digital Signature Standard (DSS). A similar technique with one random variable was proposed earlier, and it was found that such system with one random variable is not well secured. Subsequently, it was pointed out that at least two random variables are required for satisfying three cryptographic properties of authenticity, security, and uniqueness of the session keys established. In this work, a new approach for establishing authenticated secret session keys using two random numbers is presented. An in-depth analysis of the proposed scheme for the three cryptographic properties of authenticity, security, and uniqueness has been done, and no such weakness has been found. |
It was a choice he lived to regret. Having misjudged the diameter of the 18in (30 centimetre) hole, which workmen had dug to fix in a lamppost, he became wedged in it up to his armpits.
A crowd of more than 100 people gathered around to watch as he struggled to wriggle free. Some tried to pull him out, but he was stuck fast.
The unidentified man was eventually rescued by firefighters, after being laughed at and photographed by morning shoppers in Swansea, south Wales, for more than two hours.
One onlooker, 29-year-old builder Gareth Hughes, said: "He was wedged in so tight we'd have pulled his arms out of their sockets if we'd pulled any harder. He was stuck fast, right up to his chest.
"We were all stood around this unfortunate man in the hole having a right old laugh.
"The man said he'd gone in feet first to retrieve a lighter he'd dropped in the hole and got stuck.
"God knows how he even managed to squeeze in the hole because it was only 30cm in diameter.
"Once the firemen arrived, they strapped a rope round him, beneath his armpits, and winched him out."
An ambulance was put on standby to treat the man, but he was pulled out uninjured.
A spokesman for Mid and West Wales Fire and Rescue Service said: "We received a call saying a male was stuck in a service duct outside a curry house in Swansea.
"We used a quad pod, which has a winch, to pull him out."
An ambulance was on standby, but the man was uninjured. |
New powers allowing police to clear the streets and create "no-go" areas for the public are being considered, the home secretary, Theresa May, has said.
May said it was time to consider whether the police needed a power "to impose a general curfew in a particular area" in the aftermath of last week's riots.
The home secretary said the government was also contemplating tougher powers to impose curfews on individual teenagers under the age of 16.
In a speech in London, she said the power to declare a general curfew was needed because existing dispersal powers only allowed the police to declare a "no go" area with advance notification.
"In the fast-moving situation we have seen in the last week, we need to make sure the police have all the powers that are necessary," she added.
Asked about the curfew powers, May said: "It's something that we're going to look at to address whether, and to what extent, we may need to change the law.
"There are two issues – one is the availability of curfew powers in relation to individuals who are under the age of 16, and the other is whether … at the moment the curfew powers are specific in terms of individuals and attached to individuals, and it's whether more general powers are needed.
"I think we need to look at dispersal powers as well, because those do require an upfront designation of an area.
"It's clear to me that, as long as we tolerate the kind of antisocial behaviour that takes place every day up and down the country, we will continue to see high levels of crime, a lack of respect for private property and a contempt for community life."
She said the police "need to have the legal powers to take robust action against criminals", adding: "They also need strong leaders – single-minded crimefighters who get to the top and measure their own performance on nothing but taking the fight to lawbreakers.
"I want police officers to hear this message loud and clear: as long as you act within reason and the law, I will never damn you if you do."
May praised officers who put themselves in harm's way during the riots, saying everyone owed them "a debt of gratitude".
She added that controversial proposals to replace police authorities with elected police and crime commissioners from next year, and the introduction of a new National Crime Agency, were now more important than ever.
The home secretary also defended her decision not to delay the appointment of the new Metropolitan police commissioner to enable a foreign national, such as Bill Bratton, to apply for the job.
She is also writing to Sir Denis O'Connor, the chief inspector of constabulary, saying forces should be given clearer guidance on tactics, pre-emptive action, the number of officers trained in public order policing, the need for forces to assist others, and the appropriate arrest policy.
O'Connor warned earlier this year that more than two in five forces were unprepared to help police major protests.
May rejected calls from senior officers to reconsider the government's 20% cuts to police budgets in the wake of the riots.
"I am clear that, even at the end of this spending period, forces will still have the resources to deploy officers in the same numbers we have seen in the last week," she said.
"It's clear to me that we can improve the visibility and availability of the police to the public.
"It's more important than ever that we do so, because we are asking the police to fight crime on a tighter budget."
England riots: will harsher sentences act as a deterrent? |
import pandas as pd
import dask
import dask.array as da
def _find_unique_subset(a,b):
a_pd = pd.DataFrame(a)
b_pd = pd.DataFrame(b)
a_pd = a_pd.append(b_pd)
a_pd = a_pd.drop_duplicates(a_pd.columns[-1])
#print(a_pd.columns[-1])
return a_pd.to_numpy()
#return da.from_array(a_pd.to_numpy(),chunks=chunks)
def _tree_combine_list(list_to_sum,func):
import dask.array as da
while len(list_to_sum) > 1:
new_list_to_sum = []
for i in range(0, len(list_to_sum), 2):
if i < len(list_to_sum) - 1:
lazy = dask.delayed(_find_unique_subset)(list_to_sum[i],list_to_sum[i+1])
else:
lazy = list_to_sum[i]
new_list_to_sum.append(lazy)
list_to_sum = new_list_to_sum
return list_to_sum[0]
|
/// Does the same as `lz77_optimal`, but optimized for the fixed tree of the
/// deflate standard.
/// The fixed tree never gives the best compression. But this gives the best
/// possible LZ77 encoding possible with the fixed tree.
/// This does not create or output any fixed tree, only LZ77 data optimized for
/// using with a fixed tree.
/// If `instart` is larger than `0`, it uses values before `instart` as starting
/// dictionary.
pub fn lz77_optimal_fixed<C>(
s: &mut ZopfliBlockState<C>,
in_data: &[u8],
instart: usize,
inend: usize,
store: &mut Lz77Store,
) where
C: Cache,
{
s.blockstart = instart;
s.blockend = inend;
let mut h = ZopfliHash::new();
let mut costs = Vec::with_capacity(inend - instart - 1);
lz77_optimal_run(
s,
in_data,
instart,
inend,
get_cost_fixed,
store,
&mut h,
&mut costs,
);
} |
I think I owe a friend $1.87, and anxiety over the debt may cause the early demise of one or the other of us. No offense meant to him, but I’d like to try and make sure it’s not me.
I think I owe a friend $1.87, and anxiety over the debt may cause the early demise of one or the other of us.
No offense meant to him, but I’d like to try and make sure it’s not me. Either of us, actually, but I’m sort of dwelling on myself to the extent that the stress from it has become hazardous to my health.
OK, it may be too late in our lives for our demise to be termed “early.” Still, it’s possible that one of us could kick off in what most would consider an untimely manner, or at least in a cheap manner — for less than two bucks. How sad.
I don’t want to place blame, but it’s pretty much his fault. He did me a favor. He took a risk.
After topping off the fuel tank in his boat with diesel fuel at the end of the season so it could be stored, he dumped what was left in the tank of my boat. It took what we figured was $1.87 worth. Actually, he might have said it was “only a couple of dollars.” I was the one who might have used a calculator.
I should have just given him two bucks right then and there, but he was up on his boat, and I was down on the ground beside mine. Throwing two dollar bills up a few feet is more difficult than you might think, unless you tie them to a rock. I suppose I could have heaved eight quarters up to him, but, according to what my mom told me when she caught me and my brother in a penny fight in the garage, coin-throwing could have poked his eye out.
“I’m not worried about it,” he answered, and he wouldn’t be, of course, because we just had lunch at the marina. I would have bought him that lunch if I’d known I’d be facing this clam chowder for diesel fuel exchange so soon down the road.
He kept on talking while I reached for my wallet. It wasn’t there. It was in my car, about 100 feet away — beyond the limits of most friendships. I’d pay him later with lunch. In the meantime, I said the only thing I could think of to offer him reassurance.
I never did cough up the $1.87. Which is why, that night or early morning, I found myself in bed, awake, not really worried, but with a feeling of indebtedness.
I think he was kidding. He had to be kidding. Nobody’s health suffers over $1.87. Actually, mine would, if I didn’t stop thinking about it. But, I couldn’t. I’ve known this friend and his wife for 40 years. I didn’t want him to have a heart attack, even if it was a fake one.
Finally, I drifted off to sleep. Nobody died from lack of sleep or got killed by someone when he called too early in the morning. But, it’s still bothering me.
So, please, people, take my advice, and pay your debts immediately. Always wear comfortable shoes in case you have to walk to your wallet. And carry a brick so your money goes higher. |
I had some concerns about this documentary. It sees Nick Hewer and Margaret Mountford from the Apprentice try to compare the lives of unemployed people on benefits with those of working “taxpayers”.
Was this going to be more media stigmatising of those who need help?
Would it just be another intrusive fly on the wall series to provide employment to Alan Sugar’s firing squad?
But this was the one of the most balanced programmes I’ve seen about life on benefits.
In the first episode the “taxpayers” try to challenge the thinking that supposedly has people trapped on benefits.
What they find is not a “scrounging” mindset but a myriad of complex social problems.
At least two of the claimants seem to have real problems with personal confidence.
Luther—a single parent with a walking impediment and experience of homelessness—comes across as a man lost in time.
The government approach of all stick and no carrot is not going to help him, or Debbie who clings to the comfort of her pets.
Most of the people shown needed support with issues outside of the normal scope of looking for jobs.
Punitive measures against individuals and families like these are likely to add to their problems making them less “employable” than they already are.
What becomes clear to several of the “taxpayers” is that they are not so different or so far removed from the unemployed people they are paired with as they might have been led to believe.
Some of them only just managed to escape similar circumstances, and it was interesting seeing them notice this.
Simon remarks on a flatscreen TV and a smartphone.
But he recognises that “When I became unemployed I still had my things, and people would have made the same assumption—that I had it good”.
Meanwhile Liam the “workshy” graduate surprises Stevie with his work volunteering for a youth group.
The idea that he is too ashamed to work in a shop, or that only laziness keeps Debbie out of a job, doesn’t address the real problems.
There are not enough affordable places in nurseries, and not enough jobs in the first place.
And while no one in this programme is affected by the bedroom tax, their problems will get worse for the foreseeable future as more austerity policies are rolled out.
Nick and Margaret: We All Pay Your Benefits is available on BBC iPlayer. |
Stochastic stability of some state-dependent growth-collapse processes In this paper we consider a discrete-time process which grows according to a random walk with nonnegative increments between crash times at which it collapses to 0. We assume that the probability of crashing depends on the level of the process. We study the stochastic stability of this growth-collapse process. Special emphasis is given to the case in which the probability of crashing tends to 0 as the level of the process increases. In particular, we show that the process may exhibit long-range dependence and that the crash sizes may have a power law distribution. |
84th Pennsylvania Infantry Regiment
Service
The 84th Pennsylvania Infantry was organized at Huntingdon, Pennsylvania and Camp Curtin (in Harrisburg) beginning October 1861 and mustered in December 23, 1861, for a three-year enlistment under the command of Colonel William Gray Murray.
The regiment was attached to 1st Brigade, Lander's Division, Army of the Potomac, to March 1862. 1st Brigade, Shield's 2nd Division, V Corps, to April 1862. 1st Brigade, Shield's Division, Department of the Shenandoah, to May 1862. 4th Brigade, Shield's Division, Department of the Rappahannock, to June 1862. 4th Brigade, 2nd Division, III Corps, Army of Virginia, to September 1863. 2nd Brigade, 3rd Division, III Corps, Army of the Potomac, to June 1863. 1st Brigade, 2nd Division, III Corps, to March 1864. 2nd Brigade, 4th Division, II Corps, to May 1864. 4th Brigade, 3rd Division, II Corps, to July 1864. 2nd Brigade, 3rd Division, II Corps, to January 1865.
The 84th Pennsylvania Infantry ceased to exist on January 13, 1865, when it was consolidated with the 57th Pennsylvania Infantry.
Detailed service
At Camp Curtin until December 31, 1861. Moved to Hancock, Md., December 31 – January 2, 1862, then to Bath. Action at Bath January 4, and at Hancock January 5. Retreat to Cumberland, Md., January 10–12, 1862. Duty guarding North and South Branch Bridges and at Paw Paw Tunnel until March 1862. Advance on Winchester, Va., March 5–15. First Battle of Kernstown March 23. Occupation of Mt. Jackson April 17. Provost at Berryville until May 2. March to Fredericksburg May 12–22, and return to Front Royal May 25–29. Action near Front Royal May 31. Port Republic June 8–9. Moved to Alexandria June 29. Duty there until July. Battle of Cedar Mountain August 9. Pope's Campaign in northern Virginia August 16 – September 2. Fords of the Rappahannock August 20–24. Thoroughfare Gap August 28. Battles of Groveton August 29, Bull Run August 30, Chantilly September 1. Duty at Arlington Heights, defenses of Washington, Whipple's Command, until October. Moved to Pleasant Valley, Md., October 18, then to Warrenton and Falmouth October 24 – November 19. Battle of Fredericksburg, December 12–15. Burnside's 2nd Campaign, "Mud March," January 20–24, 1863. At Falmouth, Va., until April. Chancellorsville Campaign April 27 – May 6. Battle of Chancellorsville May 1–5. Gettysburg Campaign June 11 – July 24. Guarding Corps' trains during battle of Gettysburg July 1–3. Pursuit of Lee July 5–24. Wapping Heights, Va., July 23. Duty on line of the Rappahannock until October. Bristoe Campaign October 9–22. Advance to line of the Rappahannock November 7–8. Kelly's Ford November 7. Mine Run Campaign November 26 – December 2. Payne's Farm November 27. Regiment reenlisted January 1864. Demonstration on the Rapidan February 6–7. Duty near Brandy Station until May. Rapidan Campaign May 4–June 12. Battles of the Wilderness May 5–7, Spotsylvania May 8–12, Spotsylvania Court House May 12–21. Assault on the Salient May 12. Harris Farm May 19. North Anna River May 23–26. Line of the Pamunkey May 26–28. Totopotomoy May 28–31. Haw's Shop May 31. Cold Harbor June 1–12. Before Petersburg June 16–18. Siege of Petersburg June 16, 1864, to January 6, 1865. Weldon Railroad June 22–23, 1864. Demonstration north of James River at Deep Bottom July 27–29. Deep Bottom July 27–28. Mine Explosion, Petersburg, July 30 (reserve). Demonstration north of the James at Deep Bottom August 13–20. Strawberry Plains, Deep Bottom, August 14–18. Peeble's Farm, Poplar Grove Church, September 29 – October 2. Boydton Plank Road, October 27–28.
Casualties
The regiment lost a total of 224 men during service; 6 officers and 119 enlisted men killed or mortally wounded, 1 officer and 98 enlisted men died from disease-related causes. |
<filename>extensions/interactions/DragAndDropSortInput/directives/drag-and-drop-sort-input-rules.service.spec.ts
// Copyright 2018 The Oppia 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.
/**
* @fileoverview Unit tests for Drag and Drop Sorting rules.
*/
import { DragAndDropSortInputRulesService } from 'interactions/DragAndDropSortInput/directives/drag-and-drop-sort-input-rules.service';
describe('Drag and Drop Sort Input rules service', () => {
let ddsrs: DragAndDropSortInputRulesService;
beforeEach(() => {
ddsrs = new DragAndDropSortInputRulesService();
});
it('should have a correct \'is equal to ordering\' rule', () => {
var RULE_INPUT: {x: string[][]} = {
x: [
['rule_input_1', 'rule_input_2'],
['rule_input_3'],
['rule_input_4', 'rule_input_6']
]
};
expect(ddsrs.IsEqualToOrdering(
[
['rule_input_1', 'rule_input_2'],
['rule_input_3'],
['rule_input_4', 'rule_input_6']
], RULE_INPUT)).toBe(true);
expect(ddsrs.IsEqualToOrdering(
[
['rule_input_2', 'rule_input_1'],
['rule_input_3'],
['rule_input_4', 'rule_input_6']], RULE_INPUT)).toBe(true);
expect(ddsrs.IsEqualToOrdering(
[
['abbb', 'rule_input_2'],
['rule_input_3'],
['rule_input_5', 'rule_input_6']], RULE_INPUT)).toBe(false);
expect(ddsrs.IsEqualToOrdering(
[
['rule_input_1', 'rule_input_2'],
['rule_input_3', 'rule_input_6'],
['rule_input_4']], RULE_INPUT)).toBe(false);
expect(ddsrs.IsEqualToOrdering(
[
['rule_input_1', 'rule_input_2', 'g'],
['rule_input_3'],
['rule_input_4', 'rule_input_6']], RULE_INPUT)).toBe(false);
expect(ddsrs.IsEqualToOrdering(
[
['rule_input_3'],
['rule_input_1', 'rule_input_2'],
['rule_input_4', 'rule_input_6']], RULE_INPUT)).toBe(false);
expect(ddsrs.IsEqualToOrdering(
[
['rule_input_1', 'rule_input_2'],
['rule_input_3']], RULE_INPUT)).toBe(false);
});
it('should have a correct \'is equal to ordering with one item at incorrect' +
' position\' rule', () => {
var RULE_INPUT: {x: string[][]} = {
x: [
['rule_input_1', 'rule_input_2'],
['rule_input_3'],
['rule_input_4', 'rule_input_6']]
};
expect(ddsrs.IsEqualToOrderingWithOneItemAtIncorrectPosition(
[
['rule_input_1', 'rule_input_2'],
['rule_input_3'],
['rule_input_4', 'rule_input_6']], RULE_INPUT)).toBe(false);
expect(ddsrs.IsEqualToOrderingWithOneItemAtIncorrectPosition(
[
['rule_input_2', 'rule_input_1'],
['rule_input_3'],
['rule_input_4', 'rule_input_6']], RULE_INPUT)).toBe(false);
expect(ddsrs.IsEqualToOrderingWithOneItemAtIncorrectPosition(
[
['rule_input_1', 'rule_input_2'],
['rule_input_3', 'rule_input_6']], RULE_INPUT)).toBe(true);
expect(ddsrs.IsEqualToOrderingWithOneItemAtIncorrectPosition(
[
['rule_input_1', 'rule_input_2', 'rule_input_3'],
['rule_input_4', 'rule_input_6']], RULE_INPUT)).toBe(false);
expect(ddsrs.IsEqualToOrderingWithOneItemAtIncorrectPosition(
[
['rule_input_1'],
['rule_input_3'],
['rule_input_4', 'rule_input_6']], RULE_INPUT)).toBe(true);
expect(ddsrs.IsEqualToOrderingWithOneItemAtIncorrectPosition(
[
['rule_input_1', 'rule_input_2', 'rule_input_4'],
['rule_input_3'],
['rule_input_5', 'rule_input_6']], RULE_INPUT)).toBe(false);
expect(ddsrs.IsEqualToOrderingWithOneItemAtIncorrectPosition(
[
['rule_input_1', 'rule_input_2'],
['rule_input_3', 'rule_input_4', 'rule_input_6']
], RULE_INPUT)).toBe(false);
});
it('should have a correct \'has element X at position Y\' rule', () => {
var RULE_INPUT: {x: string, y: number} = {
x: 'rule_input_2',
y: 2
};
expect(ddsrs.HasElementXAtPositionY(
[
['rule_input_1'],
['rule_input_2', 'rule_input_3']], RULE_INPUT)).toBe(true);
expect(ddsrs.HasElementXAtPositionY(
[
['rule_input_1', 'rule_input_2'],
['rule_input_3']], RULE_INPUT)).toBe(false);
expect(ddsrs.HasElementXAtPositionY(
[
['rule_input_1'],
['rule_input_2']], RULE_INPUT)).toBe(true);
expect(ddsrs.HasElementXAtPositionY(
[
['rule_input_1'],
['rule_input_5'],
['rule_input_2', 'rule_input_3']], RULE_INPUT)).toBe(false);
expect(
ddsrs.HasElementXAtPositionY([], RULE_INPUT)
).toBe(false);
});
it('should have a correct \'has element X before element Y\' rule',
() => {
var RULE_INPUT: {x: string, y: string} = {
x: 'rule_input_2',
y: 'rule_input_5'
};
expect(ddsrs.HasElementXBeforeElementY(
[
['rule_input_1', 'rule_input_2'],
['rule_input_3', 'rule_input_5']], RULE_INPUT)).toBe(true);
expect(ddsrs.HasElementXBeforeElementY(
[
['rule_input_1', 'rule_input_5'],
['rule_input_3', 'rule_input_2']], RULE_INPUT)).toBe(false);
expect(ddsrs.HasElementXBeforeElementY(
[
['rule_input_1'], ['rule_input_2'],
['rule_input_3', 'rule_input_5']], RULE_INPUT)).toBe(true);
expect(ddsrs.HasElementXBeforeElementY(
[
['rule_input_5', 'rule_input_2'],
['rule_input_3', 'rule_input_1']], RULE_INPUT)).toBe(false);
});
});
|
An Analysis of Scientific Production in Big Data Knowledge Domain on Google Books, YouTube and IEEE Explore® Digital Library The paper aims to reveal the current state of book, video and article production in Big Data Knowledge Domain on particular platforms by examining the capabilities of Application Programming Interface (API) technology in conducting scientific data-driven research. Queries append public records from Google Books, YouTube and IEEE Explore® Digital Library to two research paradigms (sets of data sets): Big Data (incl. Analysis, Engineering, Architecture, Governance, Management, Frameworks) and Big Data interdisciplinary fields (Data Science, Data Mining, Deep Learning, Machine Learning, Artificial Intelligence). Metadata from more than 25 000 conference papers, 2000 books over the past 50 years, and 4 000 videos for the last 12 years, matching the searching criteria, has been stored and analyzed. The outputs are summarized in statistics, forecasting, rating key findings by various attributes: title, author, publisher, research field, category, subject, publication year, description, view count, and a combination of mentioned metadata in cross-tables. Nearly a half of billion video views; a half of million article reference count; a twofold increase in the number of papers in Machine learning over past three years compared to the total number in the same field for entire 1988-2016 period; 1:2:12 overall books-to-videos-to conference papers ratio; 61.3% of last year's video production just in a month (Jan-2020); the earliest found usage of "Artificial Intelligence" expression in a printed law document dated 1848 are few curious examples of analysis findings. The paper presents non-commercial research and retrieved data is collected entirely from public records. |
// Copyright (c) 2019 PaddlePaddle 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.
/*
* This file implements the pattern matcher for op fusion, which is from
* PaddleLite
*/
#pragma once
#include <functional>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "core/types.h"
#include "utility/logging.h"
namespace nnadapter {
class PatternMatcher {
public:
// This is a simple representation of a model. It holds the pointer of the
// operand and operation to avoid changing the model during the op fusion.
struct Node {
explicit Node(core::Operand* o) : operand(o) {}
explicit Node(core::Operation* o) : operation(o) {}
bool IsOperand() const;
bool IsOperation() const;
core::Operand* operand{nullptr};
core::Operation* operation{nullptr};
std::vector<Node*> inlinks{};
std::vector<Node*> outlinks{};
};
using Condition = std::function<bool(const Node*)>;
/*
* A pattern in a graph, which defined with pattern nodes and edges. Most
* graph patterns can be divided into the nodes and the links between them.
*
* For example, the FullyConnected fusion need to filter the NNADAPTER_MATMUL
* and NNADAPTER_ADD operations from the model, the NNADAPTER_MATMUL's output
* should have only one consumer which is the NNADAPTER_ADD. This pattern can
* be
* defined as with the following pseudo codes:
* // Create two operation patterns
* matmul = CreatePattern("matmul", NNADAPTER_MATMUL);
* add = CreatePattern("add", NNADAPTER_ADD);
* // Create the operand patterns
* output = CreatePattern("output") \
* ->IsOperationOutputOperand(NNADAPTER_MATMUL, 0) \
* ->IsOperationInputOperand(NNADAPTER_ADD, 0) \
* ->IsIntermediate();
* // Create the topological connections for the patterns
* matmul >> output;
* output >> add;
*
* One can add more specific asserts for the pattern nodes or edges, both the
* operation and operand pattern nodes can be ruled in MatchCondition(...).
*
*/
struct Pattern;
using Edge = std::pair<Pattern*, Pattern*>;
using Subgraph = std::map<Pattern*, Node*>;
struct Pattern {
explicit Pattern(std::vector<Edge>* e, NNAdapterOperationType t);
// Link self to the other pattern
Pattern& operator>>(Pattern& other);
// Link self to other patterns
Pattern& operator>>(std::vector<Pattern*>& others);
// Link other patterns to self
friend Pattern& operator>>(std::vector<Pattern*>& others, Pattern& self);
bool MatchAllConditions(const Node* node) const;
// Utility conditions
Pattern* IsOperand();
Pattern* IsOperation(NNAdapterOperationType type = NNADAPTER_UNKNOWN);
Pattern* IsConstantOperand();
Pattern* IsVariableOperand();
Pattern* IsConstantCopyOperand();
Pattern* IsConstantReferenceOperand();
Pattern* IsTemporaryVariableOperand();
Pattern* IsTemporaryShapeOperand();
Pattern* IsOperationInputOperand(NNAdapterOperationType type,
int index = -1);
Pattern* IsOperationOutputOperand(NNAdapterOperationType type,
int index = -1);
Pattern* IsModelInputOperand();
Pattern* IsModelOutputOperand();
Pattern* IsNotModelInputOperand();
Pattern* IsNotModelOutputOperand();
Pattern* CheckInputCount(int num);
Pattern* CheckOutputCount(int num);
// Mark the pattern matched node to be deleted, so its inlinks and outlinks
// should be inside a matched subgraph.
Pattern* IsIntermediate();
// Add a custom condition
Pattern* MatchCondition(const Condition& condition);
Pattern& operator=(const Pattern&) = delete;
Pattern(const Pattern&) = delete;
Pattern(Pattern&& other) = default;
std::vector<Edge>* edges;
NNAdapterOperationType type{NNADAPTER_UNKNOWN};
bool intermediate{false};
std::vector<Condition> conditions;
};
virtual ~PatternMatcher() = default;
// Return the number of matched subgraphs
size_t Apply(core::Model* model);
virtual void BuildPattern() = 0;
// Create or a operand or operation pattern with a unique key
Pattern* CreatePattern(const std::string& key,
NNAdapterOperationType type = NNADAPTER_UNKNOWN);
protected:
// Handling the matched subgraphs, such as inserting a new operation and some
// operands, then delete the intermediate operand and operations if returns
// true, otherwise ignore it.
virtual bool HandleMatchedResults(
core::Model* model, const std::map<std::string, Node*>& nodes) = 0;
// Convert the operands and operations of the core::Model to the nodes with
// inlinks and outlinks
void BuildNodes(core::Model* model, std::list<Node>* nodes);
bool MarkPatterns(std::list<Node>* nodes);
// Detect all the pattern and output the hit records.
std::vector<Subgraph> DetectPatterns();
void UniquePatterns(std::vector<PatternMatcher::Subgraph>* subgraphs);
void ValidatePatterns(std::vector<PatternMatcher::Subgraph>* subgraphs);
void RemoveOverlappedPatterns(std::vector<Subgraph>* subgraphs);
protected:
std::map<std::string, std::unique_ptr<Pattern>> patterns_;
std::vector<Edge> edges_;
std::map<const Pattern*, std::set<Node*>> pattern2nodes_;
};
} // namespace nnadapter
|
In this new arrangement, the nerd is the one who's in a position to look down on the masses.
Continue Reading Below Advertisement
Some of that is understandable. People who have been on the outside for a long time, and finally find a small group of like-minded folks to band with out on the fringes, would naturally be quite upset when tons of the very insiders who had excluded them for so many years came pouring out from Cool Land and plopped right down in the middle of Comic Book Refugee Camp, claiming loudly that they had been there the whole time.
If the guy that used to taunt you for playing video games is now wearing an ironic Valve trucker hat and chest-thumping to all his buddies about his kill counts and epic teabaggings and the booth babes he scored with at E3, you would understandably not want to chat with him about which Portal shirt would look cooler on him.
Also he just discovered "The cake is a lie," and quotes it constantly.
Continue Reading Below Advertisement
Those people are really annoying, but in fighting them, what are you really holding on to? If you cared about a specific game or Star Trek series before everybody jumped on board, sure, maybe you want to cling onto your loyal fan badge for that particular thing, but protecting the "nerd" label itself? If you want to defend liking Game of Thrones back when it was just books, does it really make sense to stand shoulder-to-shoulder with 16-year-old Xbox Live addicts, moth collectors and a Cisco software engineer? Maybe they think Game of Thrones is overhyped and tries too hard to be gritty and all the characters' names are stupid.
This is their totally hypothetical opinion. I would never say anything like that about such a beloved and critically acclaimed series.
Continue Reading Below Advertisement
With the diffusion of hobbies and entertainment, and the fact that it's cool to be smart now, maybe the word "nerd" doesn't really mean anything useful anymore. It was hard enough to get people to agree on what it meant before -- was it mainly about the rejection? Did you have to be smart? Which hobbies counted? -- but now it's even less clear.
Nerds don't even dress like nerds these days. Someone dressed like this would be a hipster.
Continue Reading Below Advertisement
Maybe it's time to drop the word and focus separately on each of the "nerd" traits we happen to have. Traits that include so many people that if we called them all nerds, there would be more "nerds" than non-nerds. So instead of calling our own set of traits "nerd things" and arguing with other nerds about why traits outside of our set aren't "real" nerd things, why not just say there's no definitive standard for nerdiness and let us all be the individual things that make us up?
Be smart. Be socially awkward. Be a Joss Whedon or Dr. Who or Bleach fan. Be an Angry Birds player or a JRPG gamer or a hardcore FPS killer. Hate everyone who isn't. Or do all of the above.
And I'm not going to call you a nerd for it. I'm just going to call you someone with really bad taste.
For more from Christina, check out 6 Groups Who Don't Work as Movie Bad Guys Anymore and 5 Reasons The War Between Dog and Cat People Needs to Stop. |
<filename>src/pg_parse.rs
use byteorder::{ByteOrder, BigEndian};
use errors::*;
use postgres_protocol::message::{frontend, backend};
use postgres_protocol::message::backend::{ParseResult};
/// An enum representing Postgres frontend message types
#[derive(Debug, PartialEq)]
pub enum MessageType {
ParseComplete,
Startup,
SSLRequest,
Authentication,
BackendKeyData,
BindComplete,
CloseComplete,
CommandComplete,
CopyData,
CopyDone,
CopyInResponse,
CopyOutResponse,
DataRow,
EmptyQueryResponse,
ErrorResponse,
NoData,
NoticeResponse,
NotificationResponse,
ParameterDescription,
ParameterStatus,
PasswordMessage,
PortalSuspended,
ReadyForQuery,
RowDescription,
Terminate,
Query,
NoTag,
#[doc(hidden)]
__ForExtensibility,
}
impl From<u8> for MessageType {
fn from(val: u8) -> Self {
match val {
b'1' => MessageType::ParseComplete,
b'2' => MessageType::BindComplete,
b'3' => MessageType::CloseComplete,
b'A' => MessageType::NotificationResponse,
b'c' => MessageType::CopyDone,
b'C' => MessageType::CommandComplete,
b'd' => MessageType::CopyData,
b'D' => MessageType::DataRow,
b'E' => MessageType::ErrorResponse,
b'G' => MessageType::CopyInResponse,
b'H' => MessageType::CopyOutResponse,
b'I' => MessageType::EmptyQueryResponse,
b'K' => MessageType::BackendKeyData,
b'n' => MessageType::NoData,
b'N' => MessageType::NoticeResponse,
b'R' => MessageType::Authentication,
b's' => MessageType::PortalSuspended,
b'S' => MessageType::ParameterStatus,
b't' => MessageType::ParameterDescription,
b'p' => MessageType::PasswordMessage,
b'T' => MessageType::RowDescription,
b'Z' => MessageType::ReadyForQuery,
b'Q' => MessageType::Query,
b'X' => MessageType::Terminate,
_ => MessageType::NoTag
}
}
}
#[derive(Debug)]
pub struct MessagePacket {
pub msg_type: MessageType,
// TODO: not pub
pub body: Vec<u8>
}
impl MessagePacket {
fn new(msg_type: MessageType, body: Vec<u8>) -> Self {
MessagePacket {
msg_type: msg_type,
body: body
}
}
pub fn try_from(buf: &mut Vec<u8>) -> Result<Self> {
if buf.len() < 5 {
bail!("not enough data");
}
let tag = buf[0];
let msg_type = tag.into();
debug!("tag: {}", tag as char);
let (msg_type, len) = match msg_type {
MessageType::NoTag => {
let len = BigEndian::read_u32(&buf[0..4]) as usize;
if len == 8 {
unimplemented!();
(MessageType::SSLRequest, len)
} else {
(MessageType::Startup, len)
}
},
msg_type => {
let len = BigEndian::read_u32(&buf[1..5]) as usize + 1;
debug!("Type: {:?}, {:?}, {:?}", msg_type, len, buf.len());
if len == buf.len() {
(msg_type, len)
} else {
bail!("not fully loaded");
}
},
};
Ok(MessagePacket::new(msg_type, buf.drain(..len).collect()))
}
// pub fn to_message(&self) -> ::std::io::Result<ParseResult<frontend::borrowed::Message>> {
// frontend::borrowed::Message::parse(&self.body[..])
// }
pub fn write<W>(&self, writer: &mut W) -> ::std::io::Result<usize>
where W: ::std::io::Write {
writer.write(&self.body[..])
}
} |
<reponame>robert-scheck/FORT-validator
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "SignedObjectSyntax"
* found in "rfc6488.asn1"
* `asn1c -Werror -fcompound-names -fwide-types -D asn1/asn1c -no-gen-PER -no-gen-example`
*/
#include "BinaryTime.h"
int
BinaryTime_constraint(const asn_TYPE_descriptor_t *td, const void *sptr,
asn_app_constraint_failed_f *ctfailcb, void *app_key) {
const INTEGER_t *st = (const INTEGER_t *)sptr;
long value;
if(!sptr) {
ASN__CTFAIL(app_key, td, sptr,
"%s: value not given (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
/* Check if the sign bit is present */
value = st->buf ? ((st->buf[0] & 0x80) ? -1 : 1) : 0;
if((value >= 0)) {
/* Constraint check succeeded */
return 0;
} else {
ASN__CTFAIL(app_key, td, sptr,
"%s: constraint failed (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
}
/*
* This type is implemented using INTEGER,
* so here we adjust the DEF accordingly.
*/
static asn_oer_constraints_t asn_OER_type_BinaryTime_constr_1 CC_NOTUSED = {
{ 0, 1 } /* (0..MAX) */,
-1};
static const ber_tlv_tag_t asn_DEF_BinaryTime_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (2 << 2))
};
asn_TYPE_descriptor_t asn_DEF_BinaryTime = {
"BinaryTime",
"BinaryTime",
&asn_OP_INTEGER,
asn_DEF_BinaryTime_tags_1,
sizeof(asn_DEF_BinaryTime_tags_1)
/sizeof(asn_DEF_BinaryTime_tags_1[0]), /* 1 */
asn_DEF_BinaryTime_tags_1, /* Same as above */
sizeof(asn_DEF_BinaryTime_tags_1)
/sizeof(asn_DEF_BinaryTime_tags_1[0]), /* 1 */
{ &asn_OER_type_BinaryTime_constr_1, 0, BinaryTime_constraint },
0, 0, /* No members */
0 /* No specifics */
};
|
Effect of nonvital tooth bleaching on microleakage of resin composite restorations. Thirty-six extracted, noncarious, nonfractured human incisors were divided into four groups of nine teeth. Endodontic access cavities were prepared, the pulp chamber was debrided, the root canals were cleansed, and root canal treatment was completed. Pulp cavities of teeth in group 1 received a cotton pellet and were sealed with Cavit. Groups 2, 3, and 4 received a mixture of 30% hydrogen peroxide and sodium perborate for 3, 4, and 7 days, respectively, were sealed with Cavit, and were stored in a humidor until used. Cavit and the other materials were removed, and the cavities were rinsed and restored with Scotchbond Multipurpose and Silux. The teeth were thermocycled, stained with 50% silver nitrate, and sectioned longitudinally. Dye penetration was measured. Results indicated that bleaching adversely affected the marginal seal at the tooth-restoration interface, as evidenced by increased microleakage; the highest rate of microleakage was found after the 7-day application of bleaching materials. |
A Bibenzyl Component Moscatilin Mitigates Glycation-Mediated Damages in an SH-SY5Y Cell Model of Neurodegenerative Diseases through AMPK Activation and RAGE/NF-B Pathway Suppression Moscatilin can protect rat pheochromocytoma cells against methylglyoxal-induced damage. Elimination of the effect of advanced glycation end-products (AGEs) but activation of AMP-activated protein kinase (AMPK) are the potential therapeutic targets for the neurodegenerative diseases. Our study aimed to clarify AMPK signalings role in the beneficial effects of moscatilin on the diabetic/hyperglycemia-associated neurodegenerative disorders. AGEs-induced injury in SH-SY5Y cells was used as an in vitro neurodegenerative model. AGEs stimulation resulted in cellular viability loss and reactive oxygen species production, and mitochondrial membrane potential collapse. It was observed that the cleaved forms of caspase-9, caspase-3, and poly (ADP-ribose) polymerase increased in SH-SY5Y cells following AGEs exposure. AGEs decreased Bcl-2 but increased Bax and p53 expression and nuclear factor kappa-B activation in SH-SY5Y cells. AGEs also attenuated the phosphorylation level of AMPK. These AGEs-induced detrimental effects were ameliorated by moscatilin, which was similar to the actions of metformin. Compound C, an inhibitor of AMPK, abolished the beneficial effects of moscatilin on the regulation of SH-SY5Y cells function, indicating the involvement of AMPK. In conclusion, moscatilin offers a promising therapeutic strategy to reduce the neurotoxicity or AMPK dysfunction of AGEs. It provides a potential beneficial effect with AGEs-related neurodegenerative diseases. Introduction Many neurodegenerative diseases occur when nerve cells from the brain or peripheral nervous system are lost, ultimately leading to either functional loss (ataxia) or sensory deficits (dementia). The pathogenesis mechanism of neurodegenerative diseases is exceptionally complex. Oxidative stress due to the excessive production and release of reactive oxygen species (ROS) with a decreased level of detoxifying enzymes and antioxidant defenses has proposed a general pathological mechanism of major chronic neurodegenerative diseases. A shred of growing epidemiological evidence has suggested that diabetic subjects are at increased risk of cognitive decline and the development of dementia. The pathology associated with neurodegeneration involves chronic hyperglycemia, accelerating advanced glycation end products' (AGEs) formation. AGEs can then interact with the cell surface receptors (RAGE) leading to the elevation of cytosolic ROS, which causes nuclear factor-B (NF-B) nuclear translocation and cell apoptosis. Apoptosis is driven by the disruption in the balance between the pro-apoptotic protein and the antiapoptotic protein, resulting in an elevation of mitochondrial permeability and parallel with a reduction in mitochondrial transmembrane potential (MMP), thereby, with a concomitant release of mitochondrial protein cytochrome c, leading to caspases' activation. Inhibition of the AGE-RAGE signaling axis is now considered promising in the prevention of diabetes/hyperglycemia-mediated neurodegenerative diseases. An increasing number of studies have reported novel therapeutic interventions for neurodegenerative diseases. It has been documented that AMP-activated protein kinase (AMPK) activator metformin produces the neuroprotective effect during AGEs-mediated oxidative stress in human brain cells, suggesting that AMPK could be a critical therapeutic target against AGEs-mediated neuron damages. AMPK is generally known as a serine/threonine kinase, which controls cellular energy levels by balancing energy requirements and nutrient usage via regulation of proteins involved in glucose and lipid metabolism. AMPK is also expressed in neurons throughout the brain, where it might be involved in brain development, neuronal polarization, and neuronal activity. Thus, blocked AGEs-RAGE signals and activation of AMPK are emerging as potential therapeutic targets for these neurodegenerative diseases. There is growing evidence that many medicinal plants and natural compounds have potential adjunctive therapeutic effects on various neurodegenerative diseases. Moscatilin (4--2,6-dimethoxy-phenol) is one of the active compounds from Dendrobium species, which was traditionally used as an immunomodulatory remedy against various diseases. Besides, to show anticancer activity against many kinds of cancers, moscatilin has multiple pharmacological effects involving anti-inflammatory, antioxidant, and antiplatelet aggregation. Moscatilin at concentrations equal to or less than 1 mol/L has been reported to protect retinal cells from ischemia/hypoxia-induced damage and counteract methylglyoxal (MGO)-triggered oxidative damage and cell death in rat pheochromocytoma cells. MGO is a dicarbonyl compound produced as a side product during glycolysis and a potent precursor of AGEs. Thus, moscatilin might have a potential protective or restorative action on glycation that causes various neurodegenerative diseases, while the AMPK-dependent mechanisms mediating the beneficial effect of moscatilin remain to be fully elucidated. The SH-SY5Y-derived neurons have become a popular cell model for investigating neurodegenerative diseases. SH-SY5Y cells have also been utilized in neuropathy models, showing the effects of high glucose and AGEs. In the present study, AGEs-induced injury in SH-SY5Y neuronal cells was used as an in vitro diabetic/hyperglycemia-associated neurodegenerative disease. Metformin was used as a positive control to clarify the role of AMPK signaling in the beneficial effects of moscatilin on the neurodegenerative diseases augmented under conditions of glycation. Influences on the Decreased Cell Viability in AGEs-Treated SH-SY5Y Cells The cell viability was reduced from 85.3% to 58.6%, respectively, when SH-SY5Y cells were incubated with AGEs at concentrations from 5 to 100 g/mL for 24 h ( Figure 1A). A total of 50 g/mL AGEs reduced the cell viability in SH-SY5Y cells in a time-dependent tendency ( Figure 1B). Exposure of SH-SY5Y cells to 50 g/mL AGEs for 24 h used to induce cell injury in the following experiments. Molecules 2020, 25, x 3 of 16 mol/L) sustains the survival rate of the AGEs-treated SH-SY5Y cells to 86.7% and 90.3%, respectively ( Figure 1C). Compound C (5 mol/L), in contrast, blocked the protective effect of moscatilin (1 mol/L) or metformin (2 mol/L) on AGEs-induced cell death ( Figure 1D). Neither moscatilin nor metformin and Compound C alone affects SH-SY5Y cells ( Figure 1D). The results are presented as the mean ± SD of five independent experiments (n = 5), each of which was performed in triplicate. a p < 0.05 and b p < 0.01 compared to the data from untreated group (vehicle control). c p < 0.05 and d p < 0.01 when compared to the data from cells cultured under AGEs without any treatment. Changes in RAGE Expression and Oxidative Stress-Related Factors Induced by AGEs in SH-SY5Y Cells The RAGE expressed in AGEs cultured SH-SY5Y cells was 4.4-fold higher than in untreated controls ( Figure 2A). Pretreatment SH-SY5Y cells with moscatilin (1 mol/L) or metformin (2 mol/L) reduced the AGEs-induced upregulation of RAGE expression 52.6% or 57.8%, respectively, compared to the levels seen in the untreated controls. Compound C (5 mol/L) pretreatment abolished the effects of moscatilin and metformin ( Figure 2A). (B) SH-SY5Y cells were incubated with 50 g/mL AGEs for various timepoints. (C) SH-SY5Y cells were pretreated with different concentrations of moscatilin (0.1, 0.5 or 1 mol/L) or metformin (2 mol/L) for 1 h, followed by exposure to 50 g/mL AGEs for another 24 h. (D) Compound C (5 mol/L) was added 1 h before moscatilin (1 mol/L) or metformin (2 mol/L) were stimulated. Cell viability was determined using an MTT assay and expressed as a percentage of the untreated cells. The results are presented as the mean ± SD of five independent experiments (n = 5), each of which was performed in triplicate. a p < 0.05 and b p < 0.01 compared to the data from untreated group (vehicle control). c p < 0.05 and d p < 0.01 when compared to the data from cells cultured under AGEs without any treatment. Changes in RAGE Expression and Oxidative Stress-Related Factors Induced by AGEs in SH-SY5Y Cells The RAGE expressed in AGEs cultured SH-SY5Y cells was 4.4-fold higher than in untreated controls ( Figure 2A). Pretreatment SH-SY5Y cells with moscatilin (1 mol/L) or metformin (2 mol/L) reduced the AGEs-induced upregulation of RAGE expression 52.6% or 57.8%, respectively, compared to the levels seen in the untreated controls. Compound C (5 mol/L) pretreatment abolished the effects of moscatilin and metformin ( Figure 2A). AGEs significantly induced ROS generation, while the pretreatment of SH-SY5Y cells with moscatilin (1 mol/L) or metformin (2 mol/L) markedly inhibited AGEs-induced ROS generation ( Figure 2B). Compound C (5 mol/L) pretreatment reversed moscatilin or metformin against AGEs-induced ROS production ( Figure 2B). The cellular GSH-to-GSSG ratio was determined by qualified commercial assay kits. The results are presented as the mean ± SD of five independent experiments (n = 5), each of which was performed in triplicate. a p < 0.05 and b p < 0.01 compared to the data from untreated group (vehicle control). c p < 0.05 and d p < 0.01 when compared to the data from cells cultured under AGEs without any treatment. The intracellular levels of malondialdehyde (MDA) in SH-SY5Y cells cultured in AGEs medium were higher by 4.3-fold than the regular vehicle-treated group ( Figure 2C). Pretreatment SH-SY5Y cells with moscatilin (1 mol/L) or metformin (2 mol/L) resulted in a decrease in MDA levels by 39.4% and 44.1%, respectively, in AGEs-incubated SH-SY5Y cells relative to those observed in the vehicle-treated counterparts ( Figure 2C). Compound C pretreatment restored moscatilin and metformin's actions on the reduction in the intracellular MDA levels in AGEs-treated SH-SY5Y cells ( Figure 2C). It observed that the lower GSH/GSSG ratio in SH-SY5Y cells exposed to AGEs, as well as moscatilin (1 mol/L) or metformin (2 mol/L), reversed this declined GSH/GSSG ratio ( Figure 2D). Compound C obstructed moscatilin or metformin on the elevation GSH/GSSG ratio in AGEs-treated SH-SY5Y cells ( Figure 2D). The cellular GSH-to-GSSG ratio was determined by qualified commercial assay kits. The results are presented as the mean ± SD of five independent experiments (n = 5), each of which was performed in triplicate. a p < 0.05 and b p < 0.01 compared to the data from untreated group (vehicle control). c p < 0.05 and d p < 0.01 when compared to the data from cells cultured under AGEs without any treatment. Influences on Mitochondrial Functions in AGEs-Treated SH-SY5Y Cells The intracellular levels of malondialdehyde (MDA) in SH-SY5Y cells cultured in AGEs medium were higher by 4.3-fold than the regular vehicle-treated group ( Figure 2C). Pretreatment SH-SY5Y cells with moscatilin (1 mol/L) or metformin (2 mol/L) resulted in a decrease in MDA levels by 39.4% and 44.1%, respectively, in AGEs-incubated SH-SY5Y cells relative to those observed in the vehicle-treated counterparts ( Figure 2C). Compound C pretreatment restored moscatilin and metformin's actions on the reduction in the intracellular MDA levels in AGEs-treated SH-SY5Y cells ( Figure 2C). Influences on Mitochondrial Functions in AGEs-Treated SH-SY5Y Cells In AGEs-treated SH-SY5Y cells, the MMP was reduced by 56.8% of that in the regular group ( Figure 3A). Moscatilin (1 mol/L) or metformin (2 mol/L) reduced the disruption of MMP in AGEs-cultured SH-SY5Y cells, but the addition of Compound C abolished the protective effects ( Figure 3A). In AGEs-treated SH-SY5Y cells, the MMP was reduced by 56.8% of that in the regular group ( Figure 3A). Moscatilin (1 mol/L) or metformin (2 mol/L) reduced the disruption of MMP in AGEscultured SH-SY5Y cells, but the addition of Compound C abolished the protective effects ( Figure 3A). The results are presented as the mean ± SD of five independent experiments (n = 5), each of which was performed in triplicate. a p < 0.05 and b p < 0.01 compared to the data from untreated group (vehicle control). c p < 0.05 and d p < 0.01 when compared to the data from cells cultured under AGEs without any treatment. The ADP/ATP ratio markedly increased when SH-SY5Y cells were incubated with 50 g/mL AGEs for 24 h ( Figure 3B). The treatment of SH-SY5Y cells with moscatilin (1 mol/L) decreased the The results are presented as the mean ± SD of five independent experiments (n = 5), each of which was performed in triplicate. a p < 0.05 and b p < 0.01 compared to the data from untreated group (vehicle control). c p < 0.05 and d p < 0.01 when compared to the data from cells cultured under AGEs without any treatment. The ADP/ATP ratio markedly increased when SH-SY5Y cells were incubated with 50 g/mL AGEs for 24 h ( Figure 3B). The treatment of SH-SY5Y cells with moscatilin (1 mol/L) decreased the elevation of the ADP/ATP ratio induced by AGEs; it showed a similar result in the metformin (2 mol/L)-treated group ( Figure 3B). Compound C abrogated both the effects of moscatilin and metformin on the reversion of the AGEs, which induced a high ADP/ATP ratio ( Figure 3B). Increased cytosolic levels paralleled with the decreased mitochondrial cytochrome c in AGEs-cultured SH-SY5Y cells were observed ( Figure 3C). Similar to the effect produced by metformin (2 mol/L), the pretreatment of SH-SY5Y cells with moscatilin (1 mol/L) inhibited the release of cytochrome c into the cytoplasm from the mitochondrial fractions induced by AGEs ( Figure 3C). Compound C abolished the action of moscatilin (1 mol/L) or metformin (2 mol/L) on the reduction in mitochondrial cytochrome c release ( Figure 3C). There was a 5.3-fold elevation in the extent of apoptotic DNA fragmentation in the AGEs-cultured SH-SY5Y cells relative to the regular group. Following pretreatment with moscatilin (1 mol/L) or metformin (2 mol/L), the extent of apoptotic DNA fragmentation decreased by 42.3% and 50.6% in AGEs-cultured SH-SY5Y cells relative to the vehicle-treated counterpart group. In comparison, compound C lost the effect of moscatilin (1 mol/L) or metformin (2 mol/L) ( Figure 3D). Effects on the Pro-Apoptotic and Anti-Apoptotic Proteins in AGEs-Treated SH-SY5Y Cells The protein level of p53 in SH-SY5Y cells under AGEs stimulated was elevated to 4.5-fold of the regular group ( Figure 4A). Moscatilin (1 mol/L) or metformin (2 mol/L) pretreatment lowered the p53 level in AGEs-cultured SH-SY5Y cells by 39.8% and 47.3% of the vehicle-treated counterpart group, while both the effects of moscatilin and metformin were lost in the presence of Compound C ( Figure 4A). Molecules 2020, 25, x 6 of 16 elevation of the ADP/ATP ratio induced by AGEs; it showed a similar result in the metformin (2 mol/L)-treated group ( Figure 3B). Compound C abrogated both the effects of moscatilin and metformin on the reversion of the AGEs, which induced a high ADP/ATP ratio ( Figure 3B). Increased cytosolic levels paralleled with the decreased mitochondrial cytochrome c in AGEscultured SH-SY5Y cells were observed ( Figure 3C). Similar to the effect produced by metformin (2 mol/L), the pretreatment of SH-SY5Y cells with moscatilin (1 mol/L) inhibited the release of cytochrome c into the cytoplasm from the mitochondrial fractions induced by AGEs ( Figure 3C). Compound C abolished the action of moscatilin (1 mol/L) or metformin (2 mol/L) on the reduction in mitochondrial cytochrome c release ( Figure 3C). There was a 5.3-fold elevation in the extent of apoptotic DNA fragmentation in the AGEscultured SH-SY5Y cells relative to the regular group. Following pretreatment with moscatilin (1 mol/L) or metformin (2 mol/L), the extent of apoptotic DNA fragmentation decreased by 42.3% and 50.6% in AGEs-cultured SH-SY5Y cells relative to the vehicle-treated counterpart group. In comparison, compound C lost the effect of moscatilin (1 mol/L) or metformin (2 mol/L) ( Figure 3D). Effects on the Pro-Apoptotic and Anti-Apoptotic Proteins in AGEs-Treated SH-SY5Y Cells The protein level of p53 in SH-SY5Y cells under AGEs stimulated was elevated to 4.5-fold of the regular group ( Figure 4A). Moscatilin (1 mol/L) or metformin (2 mol/L) pretreatment lowered the p53 level in AGEs-cultured SH-SY5Y cells by 39.8% and 47.3% of the vehicle-treated counterpart group, while both the effects of moscatilin and metformin were lost in the presence of Compound C ( Figure 4A). AGEs lowed the Bcl-2/Bax ratio to 12.3% in SH-SY5Y cells compared to that seen in the regular group ( Figure 4A). The downregulation in the Bcl-2/Bax ratio observed in AGEs-cultured SH-SY5Y cells was significantly increased by pretreatment with moscatilin (1 mol/L) or metformin (2 mol/L) to 5.3-and 5.8-fold, respectively, relative to that of the vehicle-treated counterpart group ( Figure 4A). Compound C reversed the action of moscatilin (1 mol/L) or metformin (2 mol/L) in SH-SY5Y cells under AGEs stimulation ( Figure 4A). The cleaved caspase-9 was 3.3-fold higher in the AGEs-cultured SH-SY5Y cells than in the regular medium cultured group ( Figure 4B). In the presence of moscatilin (1 mol/L) or metformin (2 mol/L), cleaved caspase-9 levels in AGEs-cultured SH-SY5Y cells downregulated to 55.1% and 47.2% of those observed on the vehicle-treated counterparts ( Figure 4B). Compound C blocked the action of moscatilin or metformin on the regulation of cleaved caspase-9 expression ( Figure 4B). AGEs caused a 4.2-fold increase in cleaved caspase-3 protein expression in SH-SY5Y cells ( Figure 4B). The protein expression of cleaved caspase-3 in AGEs-cultured SH-SY5Y cells was markedly decreased (43.9% and 51.8% reduction, respectively) by pretreatment with moscatilin (1.0 mol/L) or metformin (2 mol/L) when compared to those of the vehicle-treated counterparts ( Figure 4B). The reduction in cleaved caspase-3 protein expression in AGEs-cultured SH-SY5Y cells by moscatilin or metformin was abrogated in the presence of Compound C ( Figure 4B). The protein level of cleaved PARP in AGEs-cultured SH-SY5Y cells was higher by 3.5-fold of those in the vehicle control group ( Figure 4B). Following the pretreatment of SH-SY5Y cells with moscatilin (1 mol/L) or metformin (2 mol/L), the higher PARP protein levels caused by AGEs were lowered to 51.4% and 34.2%, respectively; both the actions of moscatilin and metformin were blocked by Compound C ( Figure 4B). Effects on the AMPK and NF-B Signaling in AGEs-Treated SH-SY5Y Cells AGEs markedly decreased the p-AMPK/AMPK ratio in SH-SY5Y cells, which was about 32.6%, as seen in the normal group ( Figure 5A). This AGEs-induced downregulation in the p-AMPK/AMPK ratio was significantly increased (2.0-and 2.1-fold elevation, respectively), by treatment with moscatilin (1 mol/L) or metformin (2 mol/L) when compared to that of their vehicle-treated counterpart group ( Figure 5A). Compound C suppressed the effects of moscatilin or metformin on the elevation of the p-AMPK/AMPK ratio in AGEs-cultured SH-SY5Y cells ( Figure 5A). Neither moscatilin nor metformin and Compound C changes the AMPK protein levels in AGEs-cultured SH-SY5Y cells ( Figure 5A). Molecules 2020, 25, x 7 of 16 experiments (n = 5), each of which was performed in triplicate. a p < 0.05 and b p < 0.01 compared to the data from untreated group (vehicle control). c p < 0.05 and d p < 0.01 when compared to the data from cells cultured under AGEs without any treatment. AGEs lowed the Bcl-2/Bax ratio to 12.3% in SH-SY5Y cells compared to that seen in the regular group ( Figure 4A). The downregulation in the Bcl-2/Bax ratio observed in AGEs-cultured SH-SY5Y cells was significantly increased by pretreatment with moscatilin (1 mol/L) or metformin (2 mol/L) to 5.3-and 5.8-fold, respectively, relative to that of the vehicle-treated counterpart group ( Figure 4A). Compound C reversed the action of moscatilin (1 mol/L) or metformin (2 mol/L) in SH-SY5Y cells under AGEs stimulation ( Figure 4A). The cleaved caspase-9 was 3.3-fold higher in the AGEs-cultured SH-SY5Y cells than in the regular medium cultured group ( Figure 4B). In the presence of moscatilin (1 mol/L) or metformin (2 mol/L), cleaved caspase-9 levels in AGEs-cultured SH-SY5Y cells downregulated to 55.1% and 47.2% of those observed on the vehicle-treated counterparts ( Figure 4B). Compound C blocked the action of moscatilin or metformin on the regulation of cleaved caspase-9 expression ( Figure 4B). AGEs caused a 4.2-fold increase in cleaved caspase-3 protein expression in SH-SY5Y cells ( Figure 4B). The protein expression of cleaved caspase-3 in AGEs-cultured SH-SY5Y cells was markedly decreased (43.9% and 51.8% reduction, respectively) by pretreatment with moscatilin (1.0 mol/L) or metformin (2 mol/L) when compared to those of the vehicle-treated counterparts ( Figure 4B). The reduction in cleaved caspase-3 protein expression in AGEs-cultured SH-SY5Y cells by moscatilin or metformin was abrogated in the presence of Compound C ( Figure 4B). The protein level of cleaved PARP in AGEs-cultured SH-SY5Y cells was higher by 3.5-fold of those in the vehicle control group ( Figure 4B). Following the pretreatment of SH-SY5Y cells with moscatilin (1 mol/L) or metformin (2 mol/L), the higher PARP protein levels caused by AGEs were lowered to 51.4% and 34.2%, respectively; both the actions of moscatilin and metformin were blocked by Compound C ( Figure 4B). Effects on the AMPK and NF-B Signaling in AGEs-Treated SH-SY5Y cells AGEs markedly decreased the p-AMPK/AMPK ratio in SH-SY5Y cells, which was about 32.6%, as seen in the normal group ( Figure 5A). This AGEs-induced downregulation in the p-AMPK/AMPK ratio was significantly increased (2.0-and 2.1-fold elevation, respectively), by treatment with moscatilin (1 mol/L) or metformin (2 mol/L) when compared to that of their vehicle-treated counterpart group ( Figure 5A). Compound C suppressed the effects of moscatilin or metformin on the elevation of the p-AMPK/AMPK ratio in AGEs-cultured SH-SY5Y cells ( Figure 5A). Neither moscatilin nor metformin and Compound C changes the AMPK protein levels in AGEs-cultured SH-SY5Y cells ( Figure 5A). (A) The ratio of p-IB/IB in the cytosolic extract of AGEs-cultured SH-SY5Y cells was 37.8% lower than those in the vehicle control group, which was higher by 2.2-and 2.4-fold, respectively, in moscatilin (1 mol/L) or metformin (2 mol/L) pretreated group ( Figure 5B). Compound C suppressed the action of moscatilin or metformin on the upregulation of cytosolic p-IB/IB ( Figure 5B). The protein level of IB was not influenced by moscatilin or metformin and Compound C in AGEs-cultured SH-SY5Y cells ( Figure 5B). The ratio of nucleus p-p65/p65 was 4.3-fold higher in AGEs-cultured SH-SY5Y cells than in the vehicle control group ( Figure 5C). The pretreatment of AGEs-cultured SH-SY5Y cells with moscatilin (1 mol/L) or metformin (2 mol/L) lowered the ratio of nucleus p-p65/p65 by 61.5% and 51.5%, respectively, relative to that seen in their untreated counterparts ( Figure 5C). The protein expression of p65 was not altered by moscatilin or metformin in AGEs-cultured SH-SY5Y cells ( Figure 5C). Compound C did not change the p65 protein levels in AGEs-cultured SH-SY5Y cells but blocked the downregulation of moscatilin (1 mol/L) or metformin (2 mol/L) on the nucleus p-p65/p65 ratio in AGEs-cultured SH-SY5Y cells to 3.5-and 3.6-fold, respectively, of that in the vehicle control group ( Figure 5C). Discussion It has confirmed that AGEs' interactions with their receptors (RAGE) play a role in the pathogenesis of diabetic complications and neurodegenerative disorders. Anti-glycating systems, such as those preventing AGEs formation and AGEs/RAGE interactions acting to prevent the development of diabetic neuropathy or neurodegenerative diseases, could thus be considerable. AMPK is not only a multifunctional metabolic and energy sensor to regulate glucose and lipid homeostasis, its activation also inhibits cell death in several different cells, including neurons. AMPK activation protects against AGEs-mediated oxidative stress in neural cells, as has been documented. Metformin is the drug of choice for treating diabetes via AMPK activation. Due to its capacity to improve hyperglycemia and oxidative stress regulation, metformin protects the Figure 5. Effects on the AMPK and NF-B signaling in AGEs-treated SH-SY5Y cells. Cells were pretreated with moscatilin (1 mol/L) or metformin (2 mol/L) for 1 h, followed by exposure to 50 g/mL AGEs for another 24 h. Compound C (5 mol/L) was added 1 h before moscatilin or metformin were stimulated. The photographs represent the Western blots for (A) p-AMPK and AMPK, (B) p-IB and IB, (C) p-p65 and p65. The densities of protein bands were quantitated and the ratios of p-AMPK/AMPK, p-IB/IB and p-p65/p65 were calculated and shown in the bottom panels. The results are presented as the mean ± SD of five independent experiments (n = 5), each of which was performed in triplicate. a p < 0.05 and b p < 0.01 compared to the data from untreated group (vehicle control). c p < 0.05 and d p < 0.01 when compared to the data from cells cultured under AGEs without any treatment. The ratio of p-IB/IB in the cytosolic extract of AGEs-cultured SH-SY5Y cells was 37.8% lower than those in the vehicle control group, which was higher by 2.2-and 2.4-fold, respectively, in moscatilin (1 mol/L) or metformin (2 mol/L) pretreated group ( Figure 5B). Compound C suppressed the action of moscatilin or metformin on the upregulation of cytosolic p-IB/IB ( Figure 5B). The protein level of IB was not influenced by moscatilin or metformin and Compound C in AGEs-cultured SH-SY5Y cells ( Figure 5B). The ratio of nucleus p-p65/p65 was 4.3-fold higher in AGEs-cultured SH-SY5Y cells than in the vehicle control group ( Figure 5C). The pretreatment of AGEs-cultured SH-SY5Y cells with moscatilin (1 mol/L) or metformin (2 mol/L) lowered the ratio of nucleus p-p65/p65 by 61.5% and 51.5%, respectively, relative to that seen in their untreated counterparts ( Figure 5C). The protein expression of p65 was not altered by moscatilin or metformin in AGEs-cultured SH-SY5Y cells ( Figure 5C). Compound C did not change the p65 protein levels in AGEs-cultured SH-SY5Y cells but blocked the downregulation of moscatilin (1 mol/L) or metformin (2 mol/L) on the nucleus p-p65/p65 ratio in AGEs-cultured SH-SY5Y cells to 3.5-and 3.6-fold, respectively, of that in the vehicle control group ( Figure 5C). Discussion It has confirmed that AGEs' interactions with their receptors (RAGE) play a role in the pathogenesis of diabetic complications and neurodegenerative disorders. Anti-glycating systems, such as those preventing AGEs formation and AGEs/RAGE interactions acting to prevent the development of diabetic neuropathy or neurodegenerative diseases, could thus be considerable. AMPK is not only a multifunctional metabolic and energy sensor to regulate glucose and lipid homeostasis, its activation also inhibits cell death in several different cells, including neurons. AMPK activation protects against AGEs-mediated oxidative stress in neural cells, as has been documented. Metformin is the drug of choice for treating diabetes via AMPK activation. Due to its capacity to improve hyperglycemia and oxidative stress regulation, metformin protects the nerve from damages related to chronic hyperglycemia. Our data showed that decreased cell viability parallels with increased RAGE protein levels in SH-SY5Y cells after 24 h AGEs stimulation. Moscatilin exhibited a beneficial effect similar to metformin to rescue cell growth and downregulate RAGE expression, but Compound C, an antagonist of AMPK, blocked these actions. The moscatilin inhibition of AGEs/RAGE-induced response in SH-SY5Y cells through AMPK activation could be considerable. We thus elucidate the possible mechanisms of moscatilin by which the activation of AMPK-dependent signaling in SH-SY5Y cells reverses the AGEs-induced damage to prevent cell death. Intracellular ROS generated in neuronal cells exposed to AGEs is well known. Since AGEs-induced oxidative stress leads to a significant influence in the development of diabetic neuropathy and neurodegenerative disorders, a logical therapeutic approach is to prevent oxidative stress by increasing antioxidant defense. The antioxidant activity of moscatilin has been reported. Therefore, we investigated whether the action of moscatilin on the rescue cell growth was related to the amelioration of AGEs-induced ROS generation. Pretreatment of SH-SY5Y cells with moscatilin inhibited the AGEs-induced ROS generation and lipid peroxidation and abolished the reduction in the GSH/GSSG ratio. Moscatilin counteracts AGEs-triggered oxidative damage, and cell death in SH-SY5Y cells might be contributing to a balance between oxidative stress and the antioxidant defense system. The results support the idea that studies with antioxidants could be one of the strategies available to treat these conditions. More comprehensive studies are required to evaluate the mechanistic role of moscatilin in AGEs-induced oxidative stress and neuronal cellular damage. AGEs accumulation evokes carbonyl and oxidative stress, which subsequently damages mitochondrial membrane lipids and leads to a collapse of mitochondrial membrane potential and decrease in ATP. The loss of mitochondrial membrane potential increases mitochondrial permeability, leading to mitochondrial swelling and rupture of the outer mitochondrial membrane, followed by the release of cytochrome c from mitochondria into the cytosol to trigger activation of the caspases' cascade. Caspase-9 and caspase-3 activation are responsible for apoptosis execution, leading to DNA fragmentation and, eventually, cell death through cleaving intracellular targets. Besides, the DNA-repairing abilities were abolished after PARP cleavage by caspase-3. AGEs stimulation turned on the mitochondrial-mediated apoptotic pathway. We found that SH-SY5Y cells exposed to AGEs exhibited a loss of mitochondrial membrane potential with the elevation of ADP/ATP ratio and enhanced cytochrome c release. Meanwhile, cleaved forms of caspase-9, caspase-3, and PARP increased in SH-SY5Y cells following AGEs exposure. These results supported the hypothesis that dysfunctional mitochondria are a central mediator of neuronal apoptosis in diabetes complications. Similar to the actions of metformin, it is shown that moscatilin protected SH-SY5Y cells against AGEs-induced damage by alleviating all of these events, resulting in decreased cell apoptosis and increased cell viability. Our results thus revealed that moscatilin might act through AMPK activation, reversing the apoptotic cascade involving mitochondrial cytochrome c release and death caspase activation to produce a neuroprotective effect on AGEs-induced cell injury and apoptosis in SH-SY5Y cells. The mitochondrial pathway of apoptosis is mainly regulated by the expression of one or more members of the Bcl-2 protein family; among them, Bax and Bcl-2 are a pair of critical regulatory genes with different functions. The p53 protein is activated by DNA damage, which can directly start Bax protein by translocating to the mitochondria, allowing for mitochondrial membrane permeabilization and apoptosis. In the present study, SH-SY5Y cells' exposure to AGEs decreased Bcl-2 and accompanied by increasing Bax and p53 expression. Moscatilin prevented SH-SY5Y-induced Bcl-2 protein downregulation and also lowered Bax and p53 levels in SH-SY5Y cells; the actions were close to those of metformin. Therefore, moscatilin-induced reductions of the AGE-induced mitochondrial abnormalities may inhibit neuronal apoptosis, which was associated with restoring the balance between the pro-and anti-apoptotic proteins of the Bcl-2 family. AGEs/RAGE interactions lead to the activation and translocation of NF-B, which regulates the expression of genes that control multiple physiology and pathology processes, including cell proliferation and apoptosis, and other essential cell events. AMPK signaling suppresses NF-B activation has been reported. In the present study, pretreatment with Compound C abated the suppression of moscatilin on NF-B as well as RAGE expression induced by AGEs, indicating that the inhibition of moscatilin on AGEs caused oxidative stress, and neuronal cellular damage in SH-SY5Y cells was dependent on AMPK activation. The kinase activity of AMPK is supported by the phosphorylation of Thr172 in the -subunit. We observed a dramatic decrease in the phosphorylation level of AMPK in SH-SY5Y cells exposed to AGEs without an accompanying increase in the total protein level of AMPK. Compound C abolished the revision of moscatilin on the AGEs-induced reduction in AMPK phosphorylation. We propose that moscatilin suppresses AGEs induced RAGE expression by activating AMPK, which reduces intracellular formation ROS and NF-B activation. These above events finally reverse the apoptotic cascade caused by mitochondrial dysfunction. (Figure 6). Although moscatilin possesses the ability to facilitate tau phosphorylation in an in vitro Alzheimer's disease-like model developed by cotransfection with the amyloid precursor protein and tau-related plasmids, or is induced by okadaic acid, it cannot evaluate the effect of moscatilin on the mitigation of glycation mediated damages in neuronal cells. Here, we provide evidence that moscatilin alleviates AGEs-induced mitochondrial dysfunction. The mechanism is predicted to occur through modulating AMPK activation and AGEs/RAGE/NF-B suppression. Molecules 2020, 25, x 10 of 16 activation has been reported. In the present study, pretreatment with Compound C abated the suppression of moscatilin on NF-B as well as RAGE expression induced by AGEs, indicating that the inhibition of moscatilin on AGEs caused oxidative stress, and neuronal cellular damage in SH-SY5Y cells was dependent on AMPK activation. The kinase activity of AMPK is supported by the phosphorylation of Thr172 in the -subunit. We observed a dramatic decrease in the phosphorylation level of AMPK in SH-SY5Y cells exposed to AGEs without an accompanying increase in the total protein level of AMPK. Compound C abolished the revision of moscatilin on the AGEs-induced reduction in AMPK phosphorylation. We propose that moscatilin suppresses AGEs induced RAGE expression by activating AMPK, which reduces intracellular formation ROS and NF-B activation. These above events finally reverse the apoptotic cascade caused by mitochondrial dysfunction. (Figure 6). Although moscatilin possesses the ability to facilitate tau phosphorylation in an in vitro Alzheimer's disease-like model developed by cotransfection with the amyloid precursor protein and tau-related plasmids, or is induced by okadaic acid, it cannot evaluate the effect of moscatilin on the mitigation of glycation mediated damages in neuronal cells. Here, we provide evidence that moscatilin alleviates AGEs-induced mitochondrial dysfunction. The mechanism is predicted to occur through modulating AMPK activation and AGEs/RAGE/NF-B suppression. In conclusion, the present study results indicate that moscatilin could protect SH-SY5Y cells against AGEs-induced injury and mitochondrial dysfunction; the possible mechanisms involved in AMPK activation and RAGE/NF-B pathway suppression. Moscatilin might offer a promising therapeutic strategy to reduce the neurotoxicity or AMPK dysfunction induced by AGEs. It is This will provide a potential benefit for patients with AGE-modification in aging, neurodegenerative diseases, and diabetes. In conclusion, the present study results indicate that moscatilin could protect SH-SY5Y cells against AGEs-induced injury and mitochondrial dysfunction; the possible mechanisms involved in AMPK activation and RAGE/NF-B pathway suppression. Moscatilin might offer a promising therapeutic strategy to reduce the neurotoxicity or AMPK dysfunction induced by AGEs. It is This will provide a potential benefit for patients with AGE-modification in aging, neurodegenerative diseases, and diabetes. Cell Culture The human neuroblastoma SH-SY5Y cell line was obtained from American Type Culture Collection (Manassas, VA). Cells were cultured in growth media composed of Dulbecco's modified Eagle's medium (DMEM) containing 10% fetal bovine serum (FBS), 1% penicillin/streptomycin, and 8 mmol/L glucose for 24 h to allow for adherence. Following adherence, growth media was replaced with differentiating media of DMEM/F12 (1:1) medium supplemented with 1% FBS, 8 mmol/L glucose, and 10 mol/L retinoic acid for five days for neuronal cell phenotype development. Treatments for all experiments took place following the five-day differentiation period. AGEs Stimulation and Treatments Cells were seeded at a density of 2 10 6 cells/well in 6-well plates. Upon confluence, cultures were passaged by dissociation in 0.05% (w/v) trypsin (Sigma-Aldrich, St. Louis, MO, USA) in phosphate-buffered saline (PBS) pH 7.4. For AGEs-induced functional studies, cells were maintained in fresh medium containing 1% FBS for 2 h prior to use in the experiments. Later, cells were pretreated with moscatilin (HongKong PE Biosciences Limited., ShangHai, China, purity ≥ 98%) at different concentrations (0.1, 0.5 or 1.0 mol/L), or metformin hydrochloride (Abcam, Cambridge, UK; 2 mol/L) for 1 h followed by exposure to various concentrations of AGEs in bovine serum albumin (AGEs-BSA) (Sigma-Aldrich; 5, 25, 50, and 100 g/mL) for different timepoints (1, 3, 6, 12, 24 and 48 h) without medium change. The dosage regimen of moscatilin was selected based on a previous report demonstrating that this compound at these concentrations were able to significantly attenuate protect retinal cells from ischemia/hypoxia without cytotoxicity. Compound C (Sigma-Aldrich, 5 mol/L) was added 1 h before moscatilin or metformin were stimulated. Metformin at the indicated concentration on the inhibition of AGEs was served as the positive control group. Metformin was dissolved in water at a concentration of 50 mmol/L and further diluted with culture medium to the final concentrations. Powders of moscatilin or Compound C were dissolved in dimethyl sulfoxide (DMSO, Sigma-Aldrich) to create a 100-mol/L stock solution, which was subsequently diluted in culture medium to the appropriate concentrations for subsequent experiments. The final DMSO concentration was less than 0.1% (v/v), a concentration that did not affect cell viability. The following experiments were assessed after treatment. For each experimental repeat, each condition was tested with three wells of cells and each experiment was performed at least five times independently. Cell Viability Measurements The cell viability was determined by a c3-(4, 5-dimethylthiazol-2-yl)-2, 5 diphenyl tetrazolium bromide (MTT; Sigma-Aldrich) assay. Briefly, MTT was dissolved in PBS at a concentration of 5 mg/mL. After incubation for 48 h, the MTT solution (25 L) was added to each well of 96-well plates and incubated at 37 C in a 5% CO 2 atmosphere. At the end of the 4 h incubation period, the MTT solution was discarded and 100 L DMSO was added to all wells to solubilize the MTT formazan crystals. The absorbance of the samples was measured at 570 nm on a microplate reader (SpectraMax M5, Molecular Devices, Sunnyvale, CA, USA), and background optical densities were subtracted from that of each well. The optical densities were normalized in percentages relative to the drug-free control (100%). Intracellular ROS Production The oxidant-sensing fluorescent probe 2,7 -dichlorofluorescin diacetate (DCFH-DA) was used to detect intracellular ROS generation. After the treatment period, cells were harvested and incubated in cell-free medium with 10 mol/L DCFH-DA (Sigma-Aldrich) at 37 C for 30 min and then washed three times with PBS. After the centrifugation of lysates at 15,000 g for 15 min at 4 C, 50 L of the supernatant was transferred to a black 96-well plate for fluorescence measurement using a microplate reader (SpectraMax M5) with the excitation at 488 nm and emission at 530 nm. Lipid Peroxidation Measurement The thiobarbituric acid reactive substance (TBARS) formed as a by-product of oxidative lipid damage was measured in the cell homogenates by the lipid peroxidation assay kit (Abcam plc., Cambridge, MA, USA) to quantify lipid peroxidation. In brief, 0.5 mL cell lysate (6 10 6 cells/mL) was added to 1 mmol/L ethylene diamine tetraacetic acid (Sigma-Aldrich) and then was mixed with 1 mL cold 15% (w/v) thiobarbituric acid (TBA) to precipitate proteins. The supernatant mixed with 1 mL of 0.5% (w/v) TBA in a boiling water bath for 15 min, followed by rapid cooling. The concentration of TBARS in the sample solution was determined from the absorbance at 535 nm and was expressed as nmol/mg protein using a standard solution containing a known concentration of malondialdehyde (MDA). Total protein concentrations were measured according to the method described in Lowry et al.. Oxidized/Reduced Glutathione Ratio Measurement The ratios of reduced to oxidized glutathione (GSH/GSSG) were measured with a kit from Cayman (Ann Arbor, MI, USA), which used a spectrophotometric recycling assay to measure the cellular levels of GSH and GSSG. Briefly, cells were scrape-harvested in cold PBS on ice and centrifuged following treatments. Cells were homogenized in cold 2-(N-morpholino)ethanesulfonic acid (MES) buffer (0.2 mol/L MES, 50 mmol/L phosphate, 1 mmol/L EDTA, pH 6.0) and centrifuged at 10,000 g for 15 min at 4 C. The supernatants were removed for the assay according to the manufacturer's instruction. The absorbance was recorded at 405 nm. Data were normalized to total cellular protein content. Mitochondrial Membrane Potential (MMP) Measurement The cellular MMP was measured by MMP assay kit containing 5,5,6,6 -tetrachloro-1,1,3,3tetraethylbenzimi-dazolylcarbocyanine iodide (JC-1) dye (Abcam plc.). Cells were seed in a 96-well plate at a density of 1 10 4 cells/well and incubated with 20 mol/L JC-1 in growth medium at 37 C for 30 min, hereafter, the cells were collected by centrifugation at 2500 rpm for 5 min, and the pellets were subsequently resuspended in 0.5 mL PBS. The emissions of the aggregate green monomeric form (530 nm) and the aggregate red form (590 nm) were determined using a F-2500 fluorescence spectrophotometer (Hitachi High Technologies America, Inc., Pleasanton, CA, USA). Finally, the red/ green fluorescence intensity ratio was calculated to determine changes in MMP. ADP and ATP Levels Measurement The ADP/ATP bioluminescent assay kit from BioAssay Systems (Hayward, CA, USA) is based on luciferase's ability to produce light in the presence of its substrate luciferin, and ATP was used to measure the cellular ADP and ATP contents. In brief, at the end of treatment, cells were lysed with 10% tricholoroacetic acid, neutralized with 1 mol/L KOH and diluted with 100 mmol/L HEPES buffer (pH 7.4). The first step of the assay involved the luciferase-catalyzed reaction of cellular ATP and D-luciferin, which produced a luminescent signal. Then, ADP was converted into ATP through an enzyme reaction, and the newly formed ATP reacted with D-luciferin. The second light intensity represented the total ADP and ATP content. The calculated ADP/ATP ratio was normalized to the total protein contents in the samples. Cytochrome C Release Measurement Cells were seeded at a density of 2.4 10 5 cells/well in 6-well plates and then were scraped and spun twice at 600 g for 5 min at the end of the treatment. An ice-cold 1X cytosolic buffer was added into the cell pellet, which was resuspended and incubated on ice for 15 min. Cells were homogenized, and the lysate was spun twice at 800 g for 20 min. The resulting supernatant contained the cytosol, including mitochondria, was centrifuged at 10,000 g for 15 min to generate the mitochondria pellet. To obtain the mitochondrial fraction, the mitochondrial pellet was washed and spun with a 1X cytosolic buffer at 10,000 g for 10 min and then lysed by adding intact mitochondria buffer followed by incubation on ice for 15 min. The remaining supernatant was centrifuged at 16,000 g for 25 min; this centrifuged supernatant was the cytosolic fraction. After isolation of the mitochondria and cytosolic fraction, the cytochrome C ELISA kit (Abcam plc., Cambridge, MA, USA) was used to measure the level of cytochrome c, according to the manufacturer's instructions. The protein concentration was measured by using a Bio-Rad protein assay. Apoptotic DNA Fragmentation Analysis The cell death detection ELISA kit (Roche Molecular Biochemicals, Mannheim, Germany) was used to quantitatively detect the cytoplasmic histone-associated DNA fragments after induced cell death. Briefly, the cells were seeded at a density of 2.4 10 5 cells/well in 6-well plates. At the end of the treatment, cytoplasmic extracts from cells were used as an antigen source in a sandwich ELISA with a primary anti-histone mouse monoclonal antibody-coated to the microtiter plate and a second anti-DNA mouse monoclonal antibody coupled to peroxidase. The amount of peroxidase retained in the immunocomplex was determined photometrically by incubating with 2,2 -azino-di- (ABTS) as a substrate for 10 min at 20 C. The change in color was measured at a wavelength of 405 nm by using a Dynex MRX plate reader controlled through PC software (Revelation, Dynatech Laboratories, CA, USA). The optical density at 405 nm (OD405) reading was then normalized to milligrams of protein used in the assay and presented as an apoptotic DNA fragmentation index. Statistical Analysis Data are expressed as the mean ± standard deviation (SD). Statistically significant differences were evaluated by one-way analysis of variance and Dunnett range post-hoc comparisons using Systat SigmaPlot version 12.5 (Systat Software Inc., San Jose, CA, USA. Differences were considered statistically significant at p < 0.05. Conflicts of Interest: There are no conflicts of interest. |
Semi-supervised sequence classification through change point detection Sequential sensor data is generated in a wide variety of practical applications. A fundamental challenge involves learning effective classifiers for such sequential data. While deep learning has led to impressive performance gains in recent years in domains such as speech, this has relied on the availability of large datasets of sequences with high-quality labels. In many applications, however, the associated class labels are often extremely limited, with precise labelling/segmentation being too expensive to perform at a high volume. However, large amounts of unlabeled data may still be available. In this paper we propose a novel framework for semi-supervised learning in such contexts. In an unsupervised manner, change point detection methods can be used to identify points within a sequence corresponding to likely class changes. We show that change points provide examples of similar/dissimilar pairs of sequences which, when coupled with labeled, can be used in a semi-supervised classification setting. Leveraging the change points and labeled data, we form examples of similar/dissimilar sequences to train a neural network to learn improved representations for classification. We provide extensive synthetic simulations and show that the learned representations are superior to those learned through an autoencoder and obtain improved results on both simulated and real-world human activity recognition datasets. Introduction As devices ranging from smart watches to smart toasters are equipped with ever more sensors, machine learning problems involving sequential data are becoming increasingly ubiquitous. Sleep tracking, activity recognition and characterization, and machine health monitoring are just a few applications where machine learning can be applied to sequential data. In recent years, deep networks have been widely used for such tasks as these networks are able automatically learn suitable representations, helping them achieve state-ofthe-art performance. However, such methods typically require large, accurately labeled training datasets in order to obtain these results. Unfortunately, especially in the context of sequential data, it is often the case that despite the availability of huge amounts of unlabeled data, labeled data is often scarce and expensive to obtain. In such settings, semi-supervised techniques can provide significant advantages over traditional supervised techniques. Over the past decade, there have been great advances in semi-supervised learning methods. Impressive classification performance -particularly in the fields of computer vision -has been achieved by using large amounts of unlabeled data on top of limited labeled data. However, despite these advances, there has been comparatively much less work on semi-supervised classification of sequential data. A key intuition that most semi-supervised learning methods share is that the data should (in the right representation) exhibit some kind of clustering, where different classes correspond to different clusters. In the context of sequential data, the equivalent assumption is that data segments within a sequence corresponding to different classes should map to distinct clusters. In the context of sequential data, the challenge is that exploiting this clustering would require the sequence to be appropriately segmented, but segment boundaries are generally unknown a priori. If the start/end points of each segment were actually known, it would be much easier to apply traditional semi-supervised learning methods. In this paper, we show that standard (unsupervised) change point detection algorithms provide a natural and useful approach to segmenting an unlabeled sequence so that it can be more easily exploited in a semisupervised context. Specifically, change point-detection algorithms aim to identify instances in a sequence where the data distribution changes (indicating an underlying class change). We show that the resulting change points can be leveraged to learn improved representations for semi-supervised learning. We propose a novel framework for semi-supervised sequential classification using change point detection. We first apply unsupervised change point detection to the unlabeled data. We assume that segments between two change points belong to the same distribution and should be classified similarly, whereas adjacent segments which are on opposite sides of a change point belong to different distributions and should be classified differently. These similar/dissimilar pairs, derived from change points, can then be combined with similar/dissimilar pairs derived from labeled data. We use these combined similar/dissimilar constraints to train a neural network that preserves similarity/dissimilarity. The learned representation can then be fed into a multilayer feedforward network trained via existing semi-supervised techniques. We show that this approach leads to improved results compared to sequential auto-encoders in a semisupervised setting. We show that even if the final classifier is trained using standard supervised techniques that ignore the unlabeled data, the learned representations (which utilize both label and unlabeled data pairs) result in competitive performance, indicating the value of incorporating change points to learning improved representations. The proposed method method is completely agnostic with respect to the change point detection procedure to be used -any detection procedure can be used as long as it does well in detecting changes. Our main contribution is to show that pairwise information generated via change points helps neural networks achieve improved classification results in settings with limited labeled data. This, to the best of our knowledge, is the first work to recognize the utility of change points within the context of semisupervised sequence classification. The proposed method should not be considered a substitute for existing semi-supervised methods, but should be taken as a complementary procedure that produces representations which are better suited for existing semi-supervised methods. Related work The fundamental idea of semi-supervised learning is that unlabeled data contains useful information that can be leveraged to more efficiently learn from a small subset of labeled data. For example, in the context of classification, an intuitive justification for why this might be possible might involve an implicit expectation that instances belonging to different classes will map to different clusters. More concretely, most semisupervised approaches make assumptions on the data such as: that instances corresponding to different classes lie on different submanifolds, that class boundaries are smooth, or that class boundaries pass through regions of low data density. Perhaps the simplest semi-supervised learning method is to use transductive methods to learn a classifier on the unlabeled data and then assign "pseudo labels" to some or all of the unlabeled data, which can be used together with the labeled data to retrain the classifier. Transductive SVMs and graphical label propagation are examples of such methods. See for a survey of such methods. However, such self-training semi-supervised methods struggle when the initial model trained from limited labels is poor. A more common approach to semi-supervised learning is to employ methods that try to learn class boundaries that are smooth or pass through areas of low data density. Entropy regularization can be used to encourage class boundaries to pass through low density regions. Consistency-based methods such as denoising autoencoders, ladder networks and the method attempt to learn smooth class boundaries by augmenting the data. Specifically, unlabeled instances can be perturbed by adding noise, and while both the original and perturbed instances are unlabeled, we can ask that they both be assigned the same class. This approach is particularly effective in computer vision tasks, where rather than using only noise perturbations, we can exploit class-preserving augmentations such as rotation, mirroring, and other transformations. By enforcing the classifier to produce the same labels for original and transformed images, decision boundaries are encouraged to be smooth, leading to good generalization. Unfortunately, due to a lack of natural segmentation and the difficulty of defining class-preserving transformations, there has been comparatively little work on semi-supervised classification of sequences. Most prior work (e.g., ) use sequential autoencoders (or their variants) as a consistency-based method to learn representations that lead to improved classification performance. Such autoencoders have been exploited successfully in the context of semi-supervised classification for human activity recognition. However, while such consistency-based approaches do encourage smooth class boundaries, they do not necessarily promote the kind of clustering behavior that we need in cases where there are extremely few labels available. An alternative approach that more explicitly separates different classes involves learning representations that directly incorporate pairwise similarity information about different instances. One example of this approach is metric learning -as an early example, showed that improved classification could be achieved by learning a Mahalanobis distance using pairwise constraints based on class membership. The learned metric leads to a representation in which different classes map to different clusters. A similar approach learns a more general non-linear metric to encourage the formation of clusters while adhering to the provided pairwise constraints. Neural networks such as Siamese and Triplet networks also learn representations from available similar/dissimilar pairs. In it was shown that such similar/dissimilar pairs (obtained from labeled data) can be used for clustering data where each cluster belongs to a different class in the dataset. Similar Pairs Dissimilar Pairs Our approach is similar in spirit to that of. While this prior work used pairwise similarity constraints derived from labeled images to learn clustered representations, our goal is to apply this idea in the semisupervised context. At the core of our approach is the observation that pairwise similarity constraints on sequential data can be derived through unsupervised methods. Specifically, change point detection can be used to identify points within a sequence corresponding to distribution shifts, which can then be used to obtain pairwise similarity constraints. When the availability of labeled data is limited, this can be a valuable source of additional information. Proposed method 3.1 Change point detection Given a sequence X : x 1,..., x N of N vectors x i P R D, the first step in our procedure is to detect all change points within X in an unsupervised way. Note that this is a different problem than quickest change detection, where only a single change point is to be detected in the fastest possible manner. To detect a change at a point i in the sequence, two consecutive length-w windows (X i p and X i f ) are first formed: A change statistic, m i, is then computed via some function that quantifies the difference between the distributions generating X i p and X i f. If m i is greater than a specified constant, a change point is detected at the point i. As one example, many change point detection procedures assume a parametric form on the distributions generating X i p and X i f. In this case, the distribution parameters ( i p and i f ) can be estimated from X i p and X i f via, e.g., maximum likelihood estimation. Given these parameter estimates, a symmetrical KL-divergence can be used to quantify the difference between the distributions : More commonly in practice, the underlying distributions generating the sequence are unknown. In this case, non-parametric techniques can be used to estimate the difference between the distributions of X i p and X i f. One such approach uses the maximum mean discrepancy (MMD) as a change statistic. The MMD has been used to identify change points in and. The MMD statistic is given below, where K i a,b :" kpx i`a, x ib q represents a kernel-based measure of the similarity between x i`a and x ib : Throughout this paper, MMD with a radial basis function kernel is used to detect change points unless otherwise specified. However, we again emphasize that any change point detection method can be used as long as it performs well in identifying changes points. The labeled data can be used to set the change point detection threshold and the window size w to balance between false and missed change points. While we simply fix these parameters in advance using labeled data, these could also be considered as tuning parameters whose values can be set based on performance on a hold-out validation dataset. Pairwise constraints via change point detection Equipped with the detected change points, similar and dissimilar pairs of sub-sequences can be obtained in an unsupervised manner as shown in Figure 1. The idea is to form four consecutive non-overlapping sub-sequences. The first two sub-sequences pX p1, X p2 q both occur before the change point. Since the change point detection algorithm did not determine that there was a change point in the combined segment of pX p1, X p2 q, we assume these two segments are generated by the same distribution and should be classified similarly. Similarly, the last two sub-sequences pX f 1, X f 2 q both occur after the change point and are also taken as a similar pair. In contrast, the segments on opposite sides of the change point have been identified as having different underlying distributions. In order to lead to a balanced distribution of similar/dissimilar pairs, we only use the constraints that pX f 1, X p2 q and pX f 2, X p1 q should be classified differently. Each of the subsequences above is chosen to be of a fixed length s (determined by the spacing between change points). Clustered representations via pairwise constraints Using the approach described above, we can obtain similarity constraints from the unlabeled data. We can also obtain such constraints from labeled data via the assumption that sub-sequences corresponding to the same (different) class labels are similar (dissimilar) respectively. We can represent these as a set P S consisting of sub-sequence pairs pX 1, X 2 q that are similar and a set P D of dissimilar pairs. For compactness, we use the notation P " pX 1, X 2 q to refer to a sub-sequence pair belonging to P S or P D. These sub-sequences are then fed into a 1D temporal convolutional neural network, as illustrated in Figure 2. The neural network consists of 6 convolutional layers (or 3 temporal blocks as defined by ) followed by 1 linear layer. We use a RELU activation function after every convolutional layer. We choose this architecture because the dilated filter structure leads to improved performance at classifying time series while being less computationally expensive than recurrent networks such as RNNs and LSTMs, although our framework could also easily accommodate either of these alternate network architectures. Each instance x i, in the input sub-sequence X, is passed through the neural network where the final linear layer transforms the output from the last convolutional layer into R C, where C is the number of classes. A softmax function is then applied to obtain the empirical distribution f px i q for each instance x i. For a length-N sequence X, we define the mean empirical distribution as: We then compute the KL divergence between the mean empirical distributions for each sub-sequence within a pair P " pX 1, X 2 q. Our loss function is constructed applying a hinge loss (with margin parameter ) to this KL divergence: The network is then trained according to the loss function: Here, P L and P U denote the sets of sub-sequence pairs in P S Y P D formed from the labeled and unlabeled data, respectively, and r is a tuning parameter which controls the influence of the unsupervised part of the loss function. Training a classifier Once trained, the network f is fixed. The mean empirical distribution for an input sub-sequence X, f pXq, can then be used as a representation of X that can serve as input to classifier network f. We use a 2-layer feedforward neural network followed by a softmax function to obtain a distribution over the different classes. Labeled as well as unlabeled sub-sequences (which correspond to the generated pairs from change points) are passed through this classification network. Since the learned representations encourage unlabeled data points to cluster around provided labeled data points, known semi-supervised methods can be also used to incorporate unlabeled data while training f. We use entropy regularization to exploit the unlabeled data by encouraging the classifier boundary to pass through low density regions. The training data is comprised of two sets: X L and X U. Each element of X L consists of a pair pX, Y q, where X denotes a sequence x 1,..., x N of vectors in R D and Y denotes a one-hot encoding of the class label for X (and is hence in R C where C is the number of classes). Each element of X U consists of a sub-sequence X identified by the change point detection step (i.e., the individual sub-sequences in the set P U ). The loss function that we use to train f is given by: Here, C is a tuning parameter, L CE is the cross entropy loss, and L NE is the negative entropy loss: Above, f represents the output of the feedforward classification network which ends with a softmax distribution over C classes. The input to f is the mean empirical representations learned by network f for input sequence X. The negative entropy loss encourages the network f to produce low entropy empirical class distributions for unlabeled data. This encourages unlabeled data to be mapped to a distribution that concentrates on a single class, pushing the classifier boundary to f towards low-density regions. A summary of our overall approach to semi-supervised learning via change point detection is given in Algorithm 1. Algorithm 1 SSL via change point detection Inputs: Unlabeled sequence X, labeled sequences tX l, Y l }, CP detection parameters, w, Output: Trained networks: f, f Init: Add similar/dissimilar pairs from tX l u to P S, P D for i " 1 to lengthpXq do Form windows: Form two segments before CP: X i p1, X i p2 Form two segments after CP: Add pairs pX i p1, X i p2 q and pX i f 1, X i f 2 q to P S Add pairs (X i f 1, X i p2 ) and pX i f 2, X i p1 q to P D for j " 1 to num epochs do Train network f by optimizing loss L R for j " 1 to num epochs do Train network f by optimizing loss L C Baselines All of the following baselines use the same representation network f and classification network f architectures. Supervised In the supervised setting, only the labeled sequence is passed through through both the representation f and classifier networks f. We train the two networks in an end-to-end manner by minimizing: (d) True labels: SSL-CP Figure 3: T-SNE visualizations for the representations learned by the representation network (f ) on the Mackay-Glass example when 5 labels are provided from each class. Figure 3(a) shows representations learned by an autoencoder using both labeled and unlabeled data. It can be seen in 3(b) that different classes overlap in this representation. Figure 3(c) show the representations learned by SSL-CP, which are clustered and non-overlapping. This leads to improved classification when limited labels are provided. True labels for these representations are shown in Figure 3(d). Denoising autoencoder A denoising autoencoder or its variants such as the ladder network (where the reconstruction error for intermediate layers is also minimized) are often employed for semi-supervised learning with sequential data. Since it has been previously shown that the performance gap between these approaches is marginal -which we have observed as well -we focus only on the autoencoder as a baseline. In this approach, for every X P X U, we also consider a perturbed version p X produced by adding noise to X. Both X and p X are passed through an encoder network f to obtain embeddings which are used by a decoder network f 1 to reconstruct the unlabeled data. A reconstruction loss of the form CpXq " }Xf 1 pf p p Xqq} 2 is incorporated into the loss function to exploit the unlabeled data. The labeled data is first passed through the encoder network f to obtain embeddings, which are then fed into a classifier network f. We train the two networks in an end-to-end manner by minimizing: Synthetic experiments In all of the results below, we use the mean F1 score (unweighted) as an evaluation metric. In all synthetic simulations, we split the data in a 70/30 ratio where we use the larger split for training and the smaller split as a test dataset. We further split the training data in a ratio of 10/60/30. We use the smallest of these splits to obtain labeled data, the largest as unlabeled data for the semi-supervised setting, and the last split for validation. We use a small sub-sequence (comprising of 20 segments) in the unlabeled split to tune the parameters for change point detection. In our results, SSL-CP denotes our approach to semi-supervised learning via change points, but without the inclusion of the negative entropy term in the loss function. SSL-CP (ER) denotes our approach when including this entropy regularization term. Changing mean and variance This example consists of data generated by a univariate normal distribution that switches its parameters p, 2 q every 500 samples. We use 1500 such random switches to produce a sequence of data with five classes, correspond to the parameter settings tp2, 0.1q, p4, 0.1q, p4, 0.7q, p10, 0.1q, p0, 0.1qu. We use the symmetrical KL divergence from to detect change points in the unlabeled data. This is a simple change point detection problem where we detect all change points correctly. We use small sub-sequences of length 20 as labeled and unlabeled data. and we show the resulting performance in Table 1. This is a relatively simple sequence classification problem as it requires merely learning that the mean and variance determine class membership. Both the supervised and autoencoder baselines do reasonably well. However, classes 2 and 3 have the same mean but different variance, and both baselines struggle compared to SSL-CP in separating these classes when only 10 labels are provided. In a manner similar to, we generate a sequence by randomly switching between parameters p, q P tp0.2, 8q, p0.18, 16q, p0.2, 22q, p0.22, 30qu every 1400 samples. We define class membership according to the parameter settings of each segment. We generated 2000 such segments and added N p0, 0.1q noise to the entire sequence. A small sub-sequence is shown in Figure 4. We obtained pairs of sequences of size 100 using change points detected on the unlabeled dataset, where almost all true change points were detected correctly. There were about 4000 such pairs. We obtained 8100 non-overlapping windows of size 100 from the unlabeled-split for use by the autoencoder. Labeled data is also formed using non-overlapping windows of size 100 were used as labels. Table 2 shows results for different numbers of provided labels. We see that SSL-CP approach significantly outperforms the baselines. The representations learned by the autoencoder and SSL-CP are visualized in Figure 3, which illustrates that the autoencoder does not perform as well because it fails to learn representations that exhibit sufficient clustering. The influence of varying the number of provided pairs is shown in Table 3. We note that entropy regularization enhances the performance of SSL-CP when amount of unlabeled data is large. Real-world datasets HCI: Gesture recognition The HCI gesture recognition dataset consists of a user performing 5 different gestures using the right arm. Data is obtained from 8 IMUs placed on the arm. The gestures recorded included drawing triangle up, circle, infinity, square, and triangle down. We also consider the null case (where the user is not performing an activity) as a class. We use the free-hand subset from this dataset as it presents a relatively challenging classification problem when compared with the more controlled subset. Rather than using consecutive nonoverlapping windows (as the resulting sub-sequences are too small to contain a single class, since the duration of the null class can be very small), the sequential data is first divided into 100 segments using the labels. 30 segments are left as test data. This dataset presents a challenge to the SSL-CP approach in that most classes never appear adjacent to each other in the data set as they are always separated by a period in the null class. To obtain similarity constraints involving class pairs that do not include the null class, we generate a sequence by repeating a randomly sampled segment and concatenating it with another repeated randomly sampled segment. Change detection is then applied on this concatenated sequence to provide similar and dissimilar pairs. 600 of such similar dissimilar pairs were obtained. When all labels within the dataset are provided, the mean F1 score for the supervised approach is 0.88. Such a score can actually sometimes be achieved by the supervised classifier even when only 1 label from each class is provided. However in this setting, the results can vary dramatically depending on exactly which instances are labeled. We obtained classification results across 30 trials, with a different random choice of which instance in each class were labeled. We show the average results in Table 4. In Table 5 we show the percentage of trials in which each method performed best. WISDM: Activity recognition The WISDM activity recognition dataset consists of 36 users performing 6 activities which include running, walking, ascending stairs, descending stairs, sitting, and standing. Data is collected through an accelerometer mounted on the participant's chest which provides 3 dimensional data sampled at 20Hz. For our experiments, we retained data from users 33, 34, and 35 as test set. We split the data from the rest of the users in a 70/30 ratio, using the large split for training and the small split for validation. We used a small sub-sequence (consisting of about 20 change points) to tune the change detection parameters. Once tuned, we obtained change points on the entire training set to obtain pairs of size 50. We obtained a total of about 4000 such pairs. We used about 7000 non-overlapping windows of size 50 as unlabeled data for the autoencoder. We used non-overlapping windows of size 50 as labeled data. In all experiments, we used a balanced number of labels from each class. Table 6 shows results when 48 labels (6 from each class). When pairs from all detected change points within the training set (4000 in number) are used, the performance of SSL-CP is slightly worse than that of the autoencoder. This is because many false change points are detected (up to about 40% false change points) for a small number of users, leading to erroneous similarity constraints. After the removal of 10 such users, the number of falsely detected change points is reduced (to below 10% across all users) and about 1600 pairs are obtained. The performance of SSL-CP for this case (filtered users) is notably better than the autoencoder. The performance further improves when all true change points are provided. In such a case, the number of unlabeled pairs are larger leading to improved performance of entropy regularization as well. Figure 5 shows the relationship between classification performance and the number of labels available. In this experiment, only pairs derived from change points on the filtered users are used. Discussion and Conclusion As highlighted by the performance on the WISDM dataset, the performance of our proposed method depends critically on the successful detection of change points. The detection of too many false change points can lead to corrupt similarity/dissimiarity constraints, that can potentially deteriorate performance. The other main limitation of the SSL-CP approach is that obtaining a rich set of similarity/dissimilarity constraints across all possible combinations of classes requires that these classes appear adjacent in the data. However, as we observed in the HCI dataset, the generation of additional sequences can provide a synthetic solution to this problem that is effective in practice. Despite these limitations, SSL-CP consistently outperformed our baselines on both synthetic and realworld datasets. This clearly shows the potential utility of incorporating information from change points in semi-supervised learning. Moreover, the results on the WISDM dataset clearly illustrate the potential improvement that could be realized by a more robust change point detection procedures. Historically, change point detection has been mostly restricted to detecting anomalies or segmenting data. We hope that this work will encourage the community to recognize the utility of change point detection in semi-supervised learning and to devote more attention to developing improved non-parameteric change point detection procedures. Technical details on training neural networks Preprocessing Inputs to all the networks are scaled to be between 0 and 1. Network architecture and training details The neural network f used to learn representations from change points consists of three temporal blocks, where each of the blocks consists of 100 channels. Here a temporal block is defined as in where each temporal block consists of two convolution layers with the same filter dilation. Each convolution layer is followed by weight normalization which is followed by a RELU activation and a dropout layer of 0.2. For each successive temporal block, the filter was dilated by a factor of 2. The number of epochs needed to minimize training loss for f was reduced by multiplying a constant (temperature ) to the embedding provided to the final softmax layer. Details for these parameters can be found in Table 8. The first column refers to the different filters sizes (without dilation) used for each experiment. The second column lists the parameter for the hinge loss while the third parameter lists the temperature values used. 2000 epochs were provided to train f through pairwise change points. The ADAM optimizer with a learning rate of 0.0001 was used for all experiments to train f. The feedforward fully connected network f was trained using a learning rate of 0.001 through the ADAM optimizer and had two hidden layers of sizes 400 and 100 respectively. A RELU activation is used after each of these hidden layers. 400 epochs were provided to train the feed forward network. For both the autoencoder and the supervised baselines, 1000 epochs were provided for training as the loss (for both validation and training, the loss became constant at the 700 th iteration and was constant until the 1000 th epoch.) Each of the reported experiments was repeated 5 times, with mean and deviation (difference from the largest deviation from the mean) reported. The seed for functions based on randomness was fixed to a value 5. Detecting change points Change points are also detected on sequences that are scaled between 0 and 1. This is not necessary but makes it convenient to get scaled similar/dissimilar pairs for the neural network f directly from the sequence on which change points are detected. An example of detecting change points on the Mackay-Glass sequence can be seen in Figure 6. This is a short sequence consisting of about 15 segments which can be used to set parameters needed for detecting change points. The first subplot shows the Mackay-Glass sequence. The second subplot shows the values of the MMD function as well as the detected changes while the third subplot shows the labels corresponding to different segments within the sequence. Note the mountain/hill like features for the MMD statistic in the second subplot. These hills arise because the MMD function starts increasing when the future window X f starts overlapping with the segment belonging to the next class in the sequence. The peak value within this hill corresponds to the change point. The MMD function starts decreasing when the previous window X p starts overlapping with the sequence class corresponding to X f The peak function within the scipy python package can be applied on change statistics m i to obtain change points. The peak function is used with two options. One is the 'peak height' which is equivalent to Sequence labels Labels Figure 6: Detected change points on Mackay-Glass sequence the change detection threshold. The second argument is distance which specifies the minimum distance between detected change points. The parameters used for detecting change points are listed below. is the detection threshold, w is the size of the windows for X f and X p and distance is the minimum distance between change points provided to the peak function. |
Empowering educators through team-based staffing models During a time when teacher turnover is high, retention is low, and some positions go unfilled for years at a time, the conditions have never been more favorable to redesign the fundamental way we staff our nations schools. Brent W. Maddin and Randy L. Mahlerwein describe how Arizonas Mesa Public Schools and Arizona State University are working together to empower educators to design and implement innovative, team-based staffing models that make the job of being a teacher less isolating, more flexible, and, ultimately, more sustainable. |
<reponame>lechium/tvOS10Headers
/*
* This header is generated by classdump-dyld 1.0
* on Wednesday, March 22, 2017 at 9:09:22 AM Mountain Standard Time
* Operating System: Version 10.1 (Build 14U593)
* Image Source: /System/Library/PrivateFrameworks/HMFoundation.framework/HMFoundation
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@protocol HMFMemoryMonitorDelegate, OS_dispatch_queue, OS_dispatch_source;
@class NSObject;
@interface HMFMemoryMonitor : NSObject {
BOOL _monitoring;
long long _memoryState;
id<HMFMemoryMonitorDelegate> _delegate;
NSObject*<OS_dispatch_queue> _clientQueue;
NSObject*<OS_dispatch_queue> _propertyQueue;
NSObject*<OS_dispatch_source> _memoryPressure;
}
@property (nonatomic,readonly) NSObject*<OS_dispatch_queue> clientQueue; //@synthesize clientQueue=_clientQueue - In the implementation block
@property (nonatomic,readonly) NSObject*<OS_dispatch_queue> propertyQueue; //@synthesize propertyQueue=_propertyQueue - In the implementation block
@property (nonatomic,readonly) NSObject*<OS_dispatch_source> memoryPressure; //@synthesize memoryPressure=_memoryPressure - In the implementation block
@property (assign,getter=isMonitoring,nonatomic) BOOL monitoring; //@synthesize monitoring=_monitoring - In the implementation block
@property (__weak) id<HMFMemoryMonitorDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block
@property (nonatomic,readonly) long long memoryState; //@synthesize memoryState=_memoryState - In the implementation block
-(void)setDelegate:(id<HMFMemoryMonitorDelegate>)arg1 ;
-(void)dealloc;
-(id)init;
-(id<HMFMemoryMonitorDelegate>)delegate;
-(void)stop;
-(void)start;
-(NSObject*<OS_dispatch_queue>)clientQueue;
-(NSObject*<OS_dispatch_queue>)propertyQueue;
-(BOOL)isMonitoring;
-(void)setMonitoring:(BOOL)arg1 ;
-(NSObject*<OS_dispatch_source>)memoryPressure;
-(void)_handleMemoryStateChange:(long long)arg1 ;
-(long long)memoryState;
-(void)setMemoryState:(long long)arg1 ;
@end
|
<filename>core/search/boolean_filter.cpp
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 by EMC Corporation, 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.
///
/// Copyright holder is EMC Corporation
///
/// @author <NAME>
////////////////////////////////////////////////////////////////////////////////
#include "boolean_filter.hpp"
#include <boost/functional/hash.hpp>
#include "conjunction.hpp"
#include "disjunction.hpp"
#include "min_match_disjunction.hpp"
#include "exclusion.hpp"
namespace {
// first - pointer to the innermost not "not" node
// second - collapsed negation mark
std::pair<const irs::filter*, bool> optimize_not(const irs::Not& node) {
bool neg = true;
const irs::filter* inner = node.filter();
while (inner && inner->type() == irs::type<irs::Not>::id()) {
neg = !neg;
inner = static_cast<const irs::Not*>(inner)->filter();
}
return std::make_pair(inner, neg);
}
const irs::all all_docs_zero_boost = []() {irs::all a; a.boost(0); return a;}();
//////////////////////////////////////////////////////////////////////////////
/// @returns disjunction iterator created from the specified queries
//////////////////////////////////////////////////////////////////////////////
template<typename QueryIterator, typename... Args>
irs::doc_iterator::ptr make_disjunction(
const irs::sub_reader& rdr,
const irs::order::prepared& ord,
const irs::attribute_provider* ctx,
QueryIterator begin,
QueryIterator end,
Args&&... args) {
using scored_disjunction_t = irs::scored_disjunction_iterator<irs::doc_iterator::ptr>;
using disjunction_t = irs::disjunction_iterator<irs::doc_iterator::ptr>;
assert(std::distance(begin, end) >= 0);
const size_t size = size_t(std::distance(begin, end));
// check the size before the execution
if (0 == size) {
// empty or unreachable search criteria
return irs::doc_iterator::empty();
}
scored_disjunction_t::doc_iterators_t itrs;
itrs.reserve(size);
for (;begin != end; ++begin) {
// execute query - get doc iterator
auto docs = begin->execute(rdr, ord, ctx);
// filter out empty iterators
if (!irs::doc_limits::eof(docs->value())) {
itrs.emplace_back(std::move(docs));
}
}
if (ord.empty()) {
return irs::make_disjunction<disjunction_t>(
std::move(itrs), ord, std::forward<Args>(args)...);
}
return irs::make_disjunction<scored_disjunction_t>(
std::move(itrs), ord, std::forward<Args>(args)...);
}
//////////////////////////////////////////////////////////////////////////////
/// @returns conjunction iterator created from the specified queries
//////////////////////////////////////////////////////////////////////////////
template<typename QueryIterator, typename... Args>
irs::doc_iterator::ptr make_conjunction(
const irs::sub_reader& rdr,
const irs::order::prepared& ord,
const irs::attribute_provider* ctx,
QueryIterator begin,
QueryIterator end,
Args&&... args) {
typedef irs::conjunction<irs::doc_iterator::ptr> conjunction_t;
assert(std::distance(begin, end) >= 0);
const size_t size = std::distance(begin, end);
// check size before the execution
switch (size) {
case 0:
return irs::doc_iterator::empty();
case 1:
return begin->execute(rdr, ord, ctx);
}
conjunction_t::doc_iterators_t itrs;
itrs.reserve(size);
for (;begin != end; ++begin) {
auto docs = begin->execute(rdr, ord, ctx);
// filter out empty iterators
if (irs::doc_limits::eof(docs->value())) {
return irs::doc_iterator::empty();
}
itrs.emplace_back(std::move(docs));
}
return irs::make_conjunction<conjunction_t>(
std::move(itrs), ord, std::forward<Args>(args)...
);
}
} // LOCAL
namespace iresearch {
//////////////////////////////////////////////////////////////////////////////
/// @class boolean_query
/// @brief base class for boolean queries
//////////////////////////////////////////////////////////////////////////////
class boolean_query : public filter::prepared {
public:
typedef std::vector<filter::prepared::ptr> queries_t;
typedef ptr_iterator<queries_t::const_iterator> iterator;
boolean_query() noexcept : excl_(0) { }
virtual doc_iterator::ptr execute(
const sub_reader& rdr,
const order::prepared& ord,
const attribute_provider* ctx) const override {
if (empty()) {
return doc_iterator::empty();
}
assert(excl_);
auto incl = execute(rdr, ord, ctx, begin(), begin() + excl_);
// exclusion part does not affect scoring at all
auto excl = ::make_disjunction(rdr, order::prepared::unordered(), ctx,
begin() + excl_, end());
// got empty iterator for excluded
if (doc_limits::eof(excl->value())) {
// pure conjunction/disjunction
return incl;
}
return memory::make_managed<exclusion>(std::move(incl), std::move(excl));
}
virtual void prepare(
const index_reader& rdr,
const order::prepared& ord,
boost_t boost,
const attribute_provider* ctx,
std::span<const filter* const> incl,
std::span<const filter* const> excl) {
boolean_query::queries_t queries;
queries.reserve(incl.size() + excl.size());
// apply boost to the current node
this->boost(boost);
// prepare included
for (const auto* filter : incl) {
queries.emplace_back(filter->prepare(rdr, ord, boost, ctx));
}
// prepare excluded
for (const auto* filter : excl) {
// exclusion part does not affect scoring at all
queries.emplace_back(filter->prepare(
rdr, order::prepared::unordered(), irs::no_boost(), ctx));
}
// nothrow block
queries_ = std::move(queries);
excl_ = incl.size();
}
iterator begin() const { return iterator(queries_.begin()); }
iterator excl_begin() const { return iterator(queries_.begin() + excl_); }
iterator end() const { return iterator(queries_.end()); }
bool empty() const { return queries_.empty(); }
size_t size() const { return queries_.size(); }
protected:
virtual doc_iterator::ptr execute(
const sub_reader& rdr,
const order::prepared& ord,
const attribute_provider* ctx,
iterator begin,
iterator end) const = 0;
private:
// 0..excl_-1 - included queries
// excl_..queries.end() - excluded queries
queries_t queries_;
// index of the first excluded query
size_t excl_;
};
//////////////////////////////////////////////////////////////////////////////
/// @class and_query
/// @brief represent a set of queries joint by "And"
//////////////////////////////////////////////////////////////////////////////
class and_query final : public boolean_query {
public:
virtual doc_iterator::ptr execute(
const sub_reader& rdr,
const order::prepared& ord,
const attribute_provider* ctx,
iterator begin,
iterator end) const override {
return ::make_conjunction(rdr, ord, ctx, begin, end);
}
};
//////////////////////////////////////////////////////////////////////////////
/// @class or_query
/// @brief represent a set of queries joint by "Or"
//////////////////////////////////////////////////////////////////////////////
class or_query final : public boolean_query {
public:
virtual doc_iterator::ptr execute(
const sub_reader& rdr,
const order::prepared& ord,
const attribute_provider* ctx,
iterator begin,
iterator end) const override {
return ::make_disjunction(rdr, ord, ctx, begin, end);
}
}; // or_query
//////////////////////////////////////////////////////////////////////////////
/// @class min_match_query
/// @brief represent a set of queries joint by "Or" with the specified
/// minimum number of clauses that should satisfy criteria
//////////////////////////////////////////////////////////////////////////////
class min_match_query final : public boolean_query {
private:
using scored_disjunction_t = scored_min_match_iterator<doc_iterator::ptr>;
using disjunction_t = min_match_iterator<doc_iterator::ptr>; // FIXME use FAST version
public:
explicit min_match_query(size_t min_match_count)
: min_match_count_(min_match_count) {
assert(min_match_count_ > 1);
}
virtual doc_iterator::ptr execute(
const sub_reader& rdr,
const order::prepared& ord,
const attribute_provider* ctx,
iterator begin,
iterator end) const override {
assert(std::distance(begin, end) >= 0);
const size_t size = size_t(std::distance(begin, end));
// 1 <= min_match_count
size_t min_match_count = std::max(size_t(1), min_match_count_);
// check the size before the execution
if (0 == size || min_match_count > size) {
// empty or unreachable search criteria
return doc_iterator::empty();
} else if (min_match_count == size) {
// pure conjunction
return ::make_conjunction(rdr, ord, ctx, begin, end);
}
// min_match_count <= size
min_match_count = std::min(size, min_match_count);
disjunction_t::doc_iterators_t itrs;
itrs.reserve(size);
for (;begin != end; ++begin) {
// execute query - get doc iterator
auto docs = begin->execute(rdr, ord, ctx);
// filter out empty iterators
if (!doc_limits::eof(docs->value())) {
itrs.emplace_back(std::move(docs));
}
}
return make_min_match_disjunction(
std::move(itrs), ord, min_match_count);
}
private:
static doc_iterator::ptr make_min_match_disjunction(
disjunction_t::doc_iterators_t&& itrs,
const order::prepared& ord,
size_t min_match_count) {
const auto size = min_match_count > itrs.size() ? 0 : itrs.size();
switch (size) {
case 0:
// empty or unreachable search criteria
return doc_iterator::empty();
case 1:
// single sub-query
return std::move(itrs.front());
}
if (min_match_count == size) {
typedef conjunction<doc_iterator::ptr> conjunction_t;
// pure conjunction
return memory::make_managed<conjunction_t>(
conjunction_t::doc_iterators_t(
std::make_move_iterator(itrs.begin()),
std::make_move_iterator(itrs.end())), ord);
}
// min match disjunction
assert(min_match_count < size);
if (ord.empty()) {
return memory::make_managed<disjunction_t>(std::move(itrs), min_match_count);
}
return memory::make_managed<scored_disjunction_t>(std::move(itrs), min_match_count, ord);
}
size_t min_match_count_;
}; // min_match_query
// ----------------------------------------------------------------------------
// --SECTION-- boolean_filter
// ----------------------------------------------------------------------------
boolean_filter::boolean_filter(const type_info& type) noexcept
: filter(type) {}
size_t boolean_filter::hash() const noexcept {
size_t seed = 0;
::boost::hash_combine(seed, filter::hash());
std::for_each(
filters_.begin(), filters_.end(),
[&seed](const filter::ptr& f){
::boost::hash_combine(seed, *f);
});
return seed;
}
bool boolean_filter::equals(const filter& rhs) const noexcept {
const boolean_filter& typed_rhs = static_cast< const boolean_filter& >( rhs );
return filter::equals(rhs)
&& filters_.size() == typed_rhs.size()
&& std::equal(begin(), end(), typed_rhs.begin());
}
filter::prepared::ptr boolean_filter::prepare(
const index_reader& rdr,
const order::prepared& ord,
boost_t boost,
const attribute_provider* ctx) const {
// determine incl/excl parts
std::vector<const filter*> incl;
std::vector<const filter*> excl;
group_filters(incl, excl);
const irs::all all_docs_no_boost;
if (incl.empty() && !excl.empty()) {
// single negative query case
incl.push_back(&all_docs_no_boost);
}
return prepare(incl, excl, rdr, ord, boost, ctx);
}
void boolean_filter::group_filters(
std::vector<const filter*>& incl,
std::vector<const filter*>& excl) const {
incl.reserve(size() / 2);
excl.reserve(incl.capacity());
const irs::filter* empty_filter{ nullptr };
const auto is_or = type() == irs::type<Or>::id();
for (auto begin = this->begin(), end = this->end(); begin != end; ++begin) {
if (irs::type<irs::empty>::id() == begin->type()) {
empty_filter = &*begin;
continue;
}
if (irs::type<Not>::id() == begin->type()) {
#ifdef IRESEARCH_DEBUG
const auto& not_node = dynamic_cast<const Not&>(*begin);
#else
const auto& not_node = static_cast<const Not&>(*begin);
#endif
const auto res = optimize_not(not_node);
if (!res.first) {
continue;
}
if (res.second) {
if (irs::type<all>::id() == res.first->type()) {
// not all -> empty result
incl.clear();
return;
}
excl.push_back(res.first);
if (is_or) {
// FIXME: this should have same boost as Not filter.
// But for now we do not boost negation.
incl.push_back(&all_docs_zero_boost);
}
} else {
incl.push_back(res.first);
}
} else {
incl.push_back(&*begin);
}
}
if (empty_filter != nullptr) {
incl.push_back(empty_filter);
}
}
// ----------------------------------------------------------------------------
// --SECTION-- And
// ----------------------------------------------------------------------------
DEFINE_FACTORY_DEFAULT(And) // cppcheck-suppress unknownMacro
And::And() noexcept
: boolean_filter(irs::type<And>::get()) {
}
filter::prepared::ptr And::prepare(
std::vector<const filter*>& incl,
std::vector<const filter*>& excl,
const index_reader& rdr,
const order::prepared& ord,
boost_t boost,
const attribute_provider* ctx) const {
//optimization step
// if include group empty itself or has 'empty' -> this whole conjunction is empty
if (incl.empty() || incl.back()->type() == irs::type<irs::empty>::id()) {
return prepared::empty();
}
irs::all cumulative_all;
boost_t all_boost{ 0 };
size_t all_count{ 0 };
for (auto filter : incl) {
if (filter->type() == irs::type<irs::all>::id()) {
all_count++;
all_boost += filter->boost();
}
}
if (all_count != 0) {
const auto non_all_count = incl.size() - all_count;
auto it = std::remove_if(
incl.begin(), incl.end(),
[](const irs::filter* filter) {
return irs::type<all>::id() == filter->type();
});
incl.erase(it, incl.end());
// Here And differs from Or. Last 'All' should be left in include group only if there is more than one
// filter of other type. Otherwise this another filter could be container for boost from 'all' filters
if (1 == non_all_count) {
// let this last filter hold boost from all removed ones
// so we aggregate in external boost values from removed all filters
// If we will not optimize resulting boost will be:
// boost * OR_BOOST * ALL_BOOST + boost * OR_BOOST * LEFT_BOOST
// We could adjust only 'boost' so we recalculate it as
// new_boost = ( boost * OR_BOOST * ALL_BOOST + boost * OR_BOOST * LEFT_BOOST) / (OR_BOOST * LEFT_BOOST)
// so when filter will be executed resulting boost will be:
// new_boost * OR_BOOST * LEFT_BOOST. If we substitute new_boost back we will get
// ( boost * OR_BOOST * ALL_BOOST + boost * OR_BOOST * LEFT_BOOST) - original non-optimized boost value
auto left_boost = (*incl.begin())->boost();
if (this->boost() != 0 && left_boost != 0 && !ord.empty()) {
boost = (boost * this->boost() * all_boost + boost * this->boost() * left_boost)
/ (left_boost * this->boost());
} else {
boost = 0;
}
} else {
// create new 'all' with boost from all removed
cumulative_all.boost(all_boost);
incl.push_back(&cumulative_all);
}
}
boost *= this->boost();
if (1 == incl.size() && excl.empty()) {
// single node case
return incl.front()->prepare(rdr, ord, boost, ctx);
}
auto q = memory::make_managed<and_query>();
q->prepare(rdr, ord, boost, ctx, incl, excl);
return q;
}
// ----------------------------------------------------------------------------
// --SECTION-- Or
// ----------------------------------------------------------------------------
DEFINE_FACTORY_DEFAULT(Or)
Or::Or() noexcept
: boolean_filter(irs::type<Or>::get()),
min_match_count_(1) {
}
filter::prepared::ptr Or::prepare(
std::vector<const filter*>& incl,
std::vector<const filter*>& excl,
const index_reader& rdr,
const order::prepared& ord,
boost_t boost,
const attribute_provider* ctx) const {
// preparing
boost *= this->boost();
if (0 == min_match_count_) { // only explicit 0 min match counts!
// all conditions are satisfied
return all().prepare(rdr, ord, boost, ctx);
}
if (!incl.empty() && incl.back()->type() == irs::type<irs::empty>::id()) {
incl.pop_back();
}
if (incl.empty()) {
return prepared::empty();
}
irs::all cumulative_all;
size_t optimized_match_count = 0;
// Optimization steps
boost_t all_boost{ 0 };
size_t all_count{ 0 };
const irs::filter* incl_all{ nullptr };
for (auto filter : incl) {
if (filter->type() == irs::type<irs::all>::id()) {
all_count++;
all_boost += filter->boost();
incl_all = filter;
}
}
if (all_count != 0) {
if (ord.empty() && incl.size() > 1 && min_match_count_ <= all_count) {
// if we have at least one all in include group - all other filters are not necessary
// in case there is no scoring and 'all' count satisfies min_match
assert(incl_all != nullptr);
incl.resize(1);
incl.front() = incl_all;
optimized_match_count = all_count - 1;
} else {
// Here Or differs from And. Last All should be left in include group
auto it = std::remove_if(
incl.begin(), incl.end(),
[](const irs::filter* filter) {
return irs::type<all>::id() == filter->type();
});
incl.erase(it, incl.end());
// create new 'all' with boost from all removed
cumulative_all.boost(all_boost);
incl.push_back(&cumulative_all);
optimized_match_count = all_count - 1;
}
}
// check strictly less to not roll back to 0 min_match (we`ve handled this case above!)
// single 'all' left -> it could contain boost we want to preserve
const auto adjusted_min_match_count = (optimized_match_count < min_match_count_) ?
min_match_count_ - optimized_match_count :
1;
if (adjusted_min_match_count > incl.size()) {
// can't satisfy 'min_match_count' conditions
// having only 'incl.size()' queries
return prepared::empty();
}
if (1 == incl.size() && excl.empty()) {
// single node case
return incl.front()->prepare(rdr, ord, boost, ctx);
}
assert(adjusted_min_match_count > 0 && adjusted_min_match_count <= incl.size());
memory::managed_ptr<boolean_query> q;
if (adjusted_min_match_count == incl.size()) {
q = memory::make_managed<and_query>();
} else if (1 == adjusted_min_match_count) {
q = memory::make_managed<or_query>();
} else { // min_match_count > 1 && min_match_count < incl.size()
q = memory::make_managed<min_match_query>(adjusted_min_match_count);
}
q->prepare(rdr, ord, boost, ctx, incl, excl);
return q;
}
// ----------------------------------------------------------------------------
// --SECTION-- Not
// ----------------------------------------------------------------------------
DEFINE_FACTORY_DEFAULT(Not)
Not::Not() noexcept
: irs::filter(irs::type<Not>::get()) {
}
filter::prepared::ptr Not::prepare(
const index_reader& rdr,
const order::prepared& ord,
boost_t boost,
const attribute_provider* ctx) const {
const auto res = optimize_not(*this);
if (!res.first) {
return prepared::empty();
}
boost *= this->boost();
if (res.second) {
all all_docs;
const std::array<const irs::filter*, 1> incl{ &all_docs };
const std::array<const irs::filter*, 1> excl{ res.first };
auto q = memory::make_managed<and_query>();
q->prepare(rdr, ord, boost, ctx, incl, excl);
return q;
}
// negation has been optimized out
return res.first->prepare(rdr, ord, boost, ctx);
}
size_t Not::hash() const noexcept {
size_t seed = 0;
::boost::hash_combine(seed, filter::hash());
if (filter_) {
::boost::hash_combine<const irs::filter&>(seed, *filter_);
}
return seed;
}
bool Not::equals(const irs::filter& rhs) const noexcept {
const Not& typed_rhs = static_cast<const Not&>(rhs);
return filter::equals(rhs)
&& ((!empty() && !typed_rhs.empty() && *filter_ == *typed_rhs.filter_)
|| (empty() && typed_rhs.empty()));
}
} // ROOT
|
/* Copyright (c) Microsoft Corporation.
Licensed under the MIT License. */
#ifndef _RX_NETWORKING_H
#define _RX_NETWORKING_H
#include "nx_api.h"
#include "nxd_dns.h"
#include "azure_config.h"
extern NX_IP nx_ip;
extern NX_PACKET_POOL nx_pool;
extern NX_DNS nx_dns_client;
UINT rx_network_init(CHAR* ssid, CHAR* password, WiFi_Mode mode);
UINT rx_network_connect();
#endif // _RX_NETWORKING_H |
import os
import pytest
from trinity.utils.filesystem import is_same_path
@pytest.mark.parametrize(
'path_a,path_b,expected',
(
# same paths
('path-a', 'path-a', True),
('path-a', 'path-a/', True),
('path-a', 'path-a/.', True),
('path-a', 'path-a/sub-path/..', True),
('path-a', 'path-a/sub-path/../', True),
('path-a', 'path-a/sub-path/../.', True),
# different paths
('path-a', 'path-b', False),
('path-a', 'path-b/', False),
('path-a', 'path-b/.', False),
('path-a/', 'path-b', False),
('path-a/.', 'path-b', False),
# rel vs abs paths
('path-a', os.path.abspath('path-a'), True),
# both abs
('/path-a/sub-path', '/path-a/sub-path', True),
('/path-a/sub-path', '/path-a/sub-path/', True),
('/path-a/sub-path', '/path-a/sub-path/.', True),
)
)
@pytest.mark.parametrize('invert', (True, False))
def test_is_same_path(path_a, path_b, expected, invert):
if invert:
actual = is_same_path(path_b, path_a)
else:
actual = is_same_path(path_a, path_b)
assert actual is expected
|
def clip(x, min_value, max_value):
if max_value is not None and max_value < min_value:
max_value = min_value
if max_value is None:
max_value = np.inf
return T.clip(x, min_value, max_value) |
<filename>src/browser/components/auth/register-form.tsx
import "./register-form.scss";
import { inject, observer } from "mobx-react";
import * as React from "react";
import { Link } from "react-router";
import { Recaptcha } from "browser/components/recaptcha";
import * as config from "common/config";
import { I18nProps, IAuthProps, IRouterProps } from "common/createStores";
import { IFormModel, RegisterForm } from "common/forms/register.form";
@inject("authStore", "i18nStore", "routerStore")
@observer
export class RegisterFormComponent extends React.Component<IProps, IState> {
private form: RegisterForm;
constructor(props: any) {
super(props);
this._handleSubmit = this._handleSubmit.bind(this);
this._handleRecaptchaCallback = this._handleRecaptchaCallback.bind(this);
this.form = new RegisterForm();
this.state = {
process: false,
};
}
_handleRecaptchaCallback(value: any) {
this.form.$("recaptcha").resetValidation();
this.form.update({ recaptcha: value });
}
_handleSubmit() {
this.form.submit({
onError: (form: RegisterForm) => { return; },
onSuccess: (form: RegisterForm) => {
const values = form.values<IFormModel>();
this._handleRegister(
values.firstname,
values.lastname,
values.email,
values.password,
values.recaptcha,
);
},
});
}
_handleRegister(firstname: string, lastname: string, email: string, password: string, gReacaptchaResponse: string) {
this.setState({ process: true });
this.props.authStore.handlerRegister(firstname, lastname, email, password, gReacaptchaResponse)
.then(() => {
this.setState({ process: false });
const { location, replace } = this.props.routerStore;
if (location.state && location.state.nextPathname) {
replace(location.state.nextPathname);
} else {
replace("/");
}
})
.catch((err) => {
this.setState({ process: false });
this.form.invalidate(err.message);
this.form.$("password").clear();
});
}
render() {
const form = this.form;
return (
<div className="register-form">
<div className="section-content">
<form autoComplete="on" className="form-horizontal">
{
form.error &&
<div className="form-group">
<small className="form-text text-danger">{form.error}</small>
</div>
}
<div className="form-group">
<label
className="col-sm-4 control-label"
htmlFor={form.$("firstname").id}
data-toggle="tooltip"
title={form.$("firstname").label}>{form.$("firstname").label}</label>
<div className="col-sm-8">
<input
className="form-control"
{...form.$("firstname").bind() } />
{
form.$("firstname").hasError &&
<small className="form-text text-danger">{form.$("firstname").error}</small>
}
</div>
</div>
<div className="form-group">
<label
className="col-sm-4 control-label"
htmlFor={form.$("lastname").id}
data-toggle="tooltip"
title={form.$("lastname").label}>{form.$("lastname").label}</label>
<div className="col-sm-8">
<input
className="form-control"
{...form.$("lastname").bind() } />
{
form.$("lastname").hasError &&
<small className="form-text text-danger">{form.$("lastname").error}</small>
}
</div>
</div>
<div className="form-group">
<label
className="col-sm-4 control-label"
htmlFor={form.$("email").id}
data-toggle="tooltip"
title={form.$("email").label}>{form.$("email").label}</label>
<div className="col-sm-8">
<input
className="form-control"
{...form.$("email").bind() } />
{
form.$("email").hasError &&
<small className="form-text text-danger">{form.$("email").error}</small>
}
</div>
</div>
<div className="form-group">
<label
className="col-sm-4 control-label"
data-toggle="tooltip"
htmlFor={form.$("password").id}
title={form.$("password").label}>{form.$("password").label}</label>
<div className="col-sm-8">
<input
className="form-control"
{...form.$("password").bind() } />
{
form.$("password").hasError &&
<small className="form-text text-danger">{form.$("password").error}</small>
}
</div>
</div>
<div className="form-group">
<div className="col-sm-8 col-sm-offset-4">
<Recaptcha
sitekey={config.recaptcha.siteKey}
language={this.props.i18nStore.lang}
tabindex={4}
size="400px"
verifyCallback={this._handleRecaptchaCallback}
expiredCallback={() => {
form.$("recaptcha").reset();
form.$("recaptcha").validate();
}} />
{
form.$("recaptcha").hasError &&
<small className="form-text text-danger">{form.$("recaptcha").error}</small>
}
</div>
</div>
<div className="form-group">
<div className="col-sm-8 col-sm-offset-4">
<button
data-hittype="event"
data-event-category="User"
data-event-action="signup"
disabled={this.state.process}
type="button"
className="btn btn-primary btn-block"
onClick={this._handleSubmit}>
{
this.state.process &&
<i className="fa fa-spinner fa-pulse fa-fw"></i>
}
{
this.state.process
? " กำลังลงทะเบียน..."
: "ลงทะเบียน"
}</button>
</div>
</div>
<div className="text-center">
<small>คลิก "ลงทะเบียน" แสดงว่ายอมรับ <Link to="/terms">เงื่อนไขการให้บริการ</Link> และ <Link to="/terms">ข้อตกลงการใช้งาน</Link></small>
</div>
</form>
<hr />
<p className="text-center">
มีบัญชีแล้ว <Link to="/login">ล็อกอินเดี้ยวนี้</Link>
</p>
</div>
</div>
);
}
}
interface IProps extends I18nProps, IAuthProps, IRouterProps {
}
interface IState {
process: boolean;
}
|
Microbiological survey of ready-to-eat foods and associated preparation surfaces in cafeterias of public sector universities ABSTRACT A microbiological and sanitation survey of ready-to-eat (RTE) food samples, cutlery, utensils, and hands of food handlers, food preparation surfaces, serving counters, washing areas, and refrigerator handles were conducted. The samples were collected using environmental swabs, and these samples were analyzed using standard plating techniques. Samples were characterized after aerobic plate counts (APC) and isolated for mesophilic aerobic bacteria (MAB), total coliforms, Staphylococcus aureus, Escherichia coli., Salmonella spp., Shigella spp., Pseudomonas spp., Enterobacter spp., Klebsiella spp., and yeast. This study suggested that good-hygiene practices can minimize bacterial counts, thereby decreasing the reservoirs for bacterial contamination. It also improves the hygienic condition of RTE-foods in the cafeteria of Universities. Introduction The Food and Agricultural Organization reported that approximately 1.3 billion tons/yr of food waste are generated globally, therefore signifying one-third of the global annual food generation. The changing world trends and recent economic and food crisis alarmed policymakers, government officials, and common people to think again critically on depleting sources of harvesting and food security. Many developing countries are experiencing perpetual food shortages; around 925 million people are hungry because of extreme poverty and are often victimized by malnutrition, starvation, and stunted growth. Approximately 2 billion people are consuming insecure food. Pakistan is ranked at 59 by the International Food Policy Institute with a 27.5% prevalence of underweight children below five years; this figure is targeted below 20 in Millennium Development Goals for 2015, 26% of the undernourished population, 20.7% Global Hunger Index, and 8.7% mortality rate under the age of 5. The recent global shift towards consumption of readyto-eat (RTE) foods has increased exponentially due to its prompt availability and nutritious meals. On the contrary, the safety and microbiological quality of that food have always been questioned, especially when considering local retailers. Microbial load on raw material is always an important factor that increases with transportation, handling, processing, and displaying RTE foods. RTE foods like Burger, Chaat, chatni (sauce), salad, and sandwiches are prepared on-site with bare hands, which provide transmission of hand microflora and associated food-borne pathogens to enter the food chain and may cause food intoxication or food poisoning. These incidences are reported throughout the world. This study aimed to evaluate the microbiological quality of ready-to-eat foods served to the students, employees, and faculty members in the cafeteria of public sector universities in Pakistan. The study's main focus was to examine RTE foods for Aerobic Colony Count (ACC or CC), E.coli count (EC), and identification of Escherichia coli, Klebsiellae, Shigella, Salmonella, Streptococcus and Staphylococcus spp., Pseudomonas spp. and yeasts. Description of RTE foods Ready to eat foods are mostly prepared in the cafeterias and sold among the University students, Employees, and Faculty daily. The raw material is brought from the vicinity, whereas some RTE foods are also brought from outside, where they are displayed for sale. This study was conducted to evaluate RTE food available in a public sector university cafeteria during the spring session. Seven canteens were surveyed twice, and later on, random samples were also assessed to minimize the chances of error. The samples of RTE foods; Biryani, burger, cake, ketchup, chaat (Sauce), patties, samosa, roll, salad, salan (curry), and swabs of associated utensils like preparation knives, spoons, plates, glasses, cutting boards, preparation surfaces, cleaning cloths, serving counter, washing area, refrigerator handle and hands of food handlers. A total of twenty-three different categories were selected, and samples were collected at different intervals of time (Table 1). Out of these RTE food samples: the highest number of samples was the Biryani, followed by the Burger. Samosa samples were analyzed in two portions: the outer part named as samosa (B) and the inner part containing the potato mash material with added other ingredients named as samosa (A). Table 1 also shows the number of samples collected for associated preparation surfaces (APS). A total of eleven APS, including food serving utensils and hands of food handlers, were analyzed; the highest numbers of samples were taken from food handlers' hands. Sample collection After acquiring the cafeteria owners' consent, RTE foods were purchased, and a portion of each required sample was aseptically transferred to sterile containers to minimize the risk of cross-contamination. Similarly, commercially available sterile swabs (Oxford, UK) were used for sampling of associated preparation surfaces, utensils, and hands of food handlers by moistening the swab with synthetic transport medium containing meat extract 1 g per er(gL −1 ), riboflavin 0.2 gL −1, biotin 0.2 gL −1, asparagine 0.1 gL −1, peptone 1 gL −1, glucose 1 gL −1 of distilled water prepared in sterile test tubes containing 5 mL of this medium. The medium's pH was adjusted to 7.2 using a portable pH meter, internally calibrated using pH buffer solution of 4, 7, and 9. The pH of solutions was adjusted using acidic and basic solutions considering the cross-reactivity and binding affinities of the anions. Samples were aseptically collected by placing the tip on the surface of the sampling portion and slightly rotating the swab between the thumb and point the finger in to and fro direction at a right angle to each other for 15 seconds. Later, all samples were transported to the laboratory and were analyzed on the same day of collection. Sample processing and analysis For RTE foods processing, 20 g of each sample was weighed and dissolved in 180 mL of a sterile peptonesaline solution containing 0.1% of peptone and 0.85% NaCl. Samples were homogenized after vigorous shaking for 30-45 seconds. Whereas, for the assessment of utensils, associated preparation surfaces, and hands of food handlers; each swab sample was aseptically shifted from transport medium to 10 mL tube of sterile nutrient broth (Merck, Germany) same homogenization procedure was repeated. After mixing, the serial dilutions were prepared for all RTE food samples in sterile peptone saline solution, which were then cultured on agar plates duplicated through the standard spread plate and pour plate method. These cultured agar plates were then incubated aerobically at 37°C ± 2°C for 24 hours. Whereas for fungi isolation Sabraud Dextrose Agar SDA (Scharlau, Spain) plates were kept at room temperature (25°C) for one week. Colony-forming units (CFU) were counted through the colony counter (Suntex, Taiwan) and calculated per mL for each RTE food sample and per cm 2 for associated preparation surfaces, including the hands of food handlers. RTE foods and swabs of associated preparation surfaces, utensils, and hands of food handlers were analyzed for aerobic bacteria, including Enterobacteriaceae family, Staphylococcus aureus, and Streptococcus spp. Results The emphasis of this study was to evaluate the level of microbial contamination in; (a). Food samples of readyto-eat available in the cafeteria of a public sector university, (b). Associated preparation surfaces including cutlery, utensils, and (c). Hygiene of food handlers with respect to their hands. A total of 445 RTE food samples of 11 categories and 505 samples of associated preparation surfaces, including, cutlery, utensils, and the hands of food handlers, have been analyzed for aerobic colony count and later for further isolation and identification. CFU Samples of RTE, APS, and hand hygiene were separately processed through dilution in the heterotrophic plate count (HPC). The results for aerobic plate count, APC of all the representative samples was counted, and later, an average log of CFU per mL (mL −1 ) or CFU per gram (g −1 ) or CFU per square cm (cm −2 ) was calculated ( Figure 1)..52, respectively. The samples collected from hand were counted for APC as 7.9 logCFU/g indicating hand hygiene played a significant role in the overall preparation and serving of cafeterias' food items. Furthermore, tap water in the washing of vegetables and preparation of salad, burgers, and other food items impact the microbial community. Gram-positive species (GP) RTE foods of a total of 11 commonly used items were focused in this study, among them 11.11% samples cultured positive for Biryani, with maximum isolates of non-pathogenic species ( of patties were cultured as positive for microbial contamination, which identified 25% Gram-positive species including 10% Pseudomonas spp., In Samosa part (A), among all positive samples, 60% were identified as GP and isolated as (Staphylococcus aureus 10%,Streptococcus spp. 20%, and non-pathogens 30%). In contrast, for Samosa part (B), only two samples showed growth with no GP pathogen. Salan samples were cultured 30%, GP, which were isolated (Streptococcus spp. 30%, and Staphylococcus saprophyticus 10%), whereas 38.10% of all roll samples were cultured positive, among them 62.5% were GP with no pathogenic species (Figure 2). Gram-negative species (GN) As Microorganisms isolated from associated preparation surfaces In this category, 10 parameters were selected, Aerobic plate counts APC for each of them was calculated. Later on, they were further identified for coliform bacteria, including E.coli, Staphylococcus spp. and Streptococcus spp. All preparation knife samples were found positive with APC range 7 log of CFUcm −2. Among these 35.71% were identified as GP with a maximum of Pseudomonas spp, 45% and hemolytic streptococci 5%. Spoon samples showed 47.62% of microbial growth with no GP pathogen. Among all plate samples, 45.45% were identified as GP with 4.55% -haemolytic Streptococci; similarly for glass, preparation area, refrigerator and serving counter samples 11.76%, 27.27%, 27.50%, 23.68% of Pseudomonas spp. and 5.88%, 4.55%, 15%, 10.53% -haemolytic Streptococci were isolated. In refrigerator handle, 2.5% Staphylococcus aureus was isolated, and in cleaning cloth, 11.36% Staphylococcus aureus and 13.64% -haemolytic Streptococci were isolated, whereas, in the washing area, 7.69% haemolytic Streptococci were identified (Figure 3). All associated preparation surfaces, including cutlery and utensils, were analyzed for Gram-negative (GN) species. The main emphasis of the study was to evaluate microbial status for analysing the chances of food-borne infections. Therefore Enterobacteriaceae was focused upon. In the knives samples used for preparation, 35% isolates were identified as Escherichia coli, 10% Klebsiella spp., 5% Shigella spp. 10% Morganella spp.; in all spoon samples categorized as GN had 40% E.coli and 10% Klebsiella spp; samples of the plate had 22.73% isolates of E.coli and 4.55% Shigella spp. In glass samples, cutting board, refrigerator handle, preparation area, and serving counter was 11.76%, 30%, 20%, 22.73%, and 5.26% E.coli was isolated. Similarly, 9.09%, 2.63% Klebsiella spp. were isolated from preparation area and serving counter, respectively. Meanwhile, from cleaning cloth 27.27% E. coli, 4.5% Shigella spp., and 4.5% Enterobacter spp. was isolated and at washing area 11.54% E. coli, 3.85% Shigella spp. were isolated. In addition, isolates of Pseudomonas spp. were identified from the samples of knife, glass, cutting board, preparation areas, refrigerator handle, serving counter, and washing area with an accumulative percentile of 5%, 11.76%, 50%, 27.27%, 27.50%, 23.68%, and 34.62%. A relatively high prevalence of GN isolates indicated contamination primality from preparation materials and water used for washing. Since the knife was infrequently used, it was observed, cutting material stuck its edges and might be a transfer source. The water quality of the tap was separately assessed and prepared separately; the results have deliberately not been included in this manuscript. Among all plate samples, 52.38% showed growth with microbial colonies ranging 7.672 log of CFUmL −1, glass samples were positive for 40.48% with CFU log 7.74 mL −1, the cutting board showed growth for 66.67% with 7.5 log of CFUmL −1. whereas all samples of cleaning cloth, preparation area, refrigerator handle, and washing area showed heavy growth on nutrient agar media (Merck, Germany) with Aerobic plate count of 8.45, 7.69, 7.63, and 8.12 log of CFUmL −1 respectively ( Figure 1). Discussion During preparation and serving of foods in the cafeterias, hygienic conditions must strictly be followed ; otherwise, chances of food-borne disease increase to consumers. Biryani is a rice-based food made with spices, rice, meat, fish, eggs, or vegetables. This dish is popular in all Asian. Biryani is taken very often at lunchtime by 90% of people working in every environment; therefore, special precautionary measures must be obtained for providing maximum food safety and security. While survey, we found 11% samples positive for microbial growth having log of CFU 6.4, 4.8, and 3.1 per gram of APC, CC, and EC. Usually, biryani is kept in a closed container to keep warm but may be due to frequent opening, air microbes, and the use of bare unwashed hands might contaminate it. Samples of burger showed 7.3 log CFU/g, which indicate microbial accumulation from unwashed hands, preparation surfaces, utensils, salads, vegetables, tap water, and open containers. All samples of ketchup were found sterile, probably due to its packing. Comparing to results of salad vegetable samples reported by 38, our results differed invariably as 68% showed microbial accumulation with 8.1, 5, 4, and 1.2 log CFUg −1 of APC, CC, EC, and SAC, respectively. Variability in results was characterized by associated preparation surfaces, including utensils and hands of food handlers and tap water quality. Comparative results of preparation knives for APC, CC, and EC were double than previously reported by 13. During the survey, it was found in most of the cafeterias that preparation knives were exchanged among food handlers for preliminary processing of RTE foods. It seemed as these knives were in use for a long period without maintenance and proper cleaning, which increases chances of microbial accumulation and easy transfer among workers and in the food. Results for spoon samples were almost the same as previously reported by 13, with variation in coliform count from 2.2 to 5.6 log CFUcm −2. Other utensils as plate and glass showed high APC as 5 and 3 log CFUcm −2. After these results, cafeterias were surveyed again to know the cause of such increased contamination. In response to the question related to the washing of utensils, cafeterias owners responded well, which indicated their cleaning concern. However, at two sampling points, haphazard washing and improper placement of washed plates, spoons, and glass were observed. Samples of tap water were also taken for analysis to know the status of water used for washing and other purposes. These water samples were analyzed in the Laboratory of water quality in the Department of Environmental Engineering NED University of Engineering and Technology. Results showed a high number of total and faecal coliforms. Relevant authorities were informed of these findings. Water disinfection dosage was suggested for implementation in the main underground water tank to achieve desired water quality levels in the overall University. Cutting boards were found less often to be utilized to prepare food, some of them in poor condition; some were having cracks, which may enhance microbial accumulation and formation of biofilms. 4.2 log CFUcm −2 APC was calculated, which was a little lower than previously reported by 13. The refrigerator handle showed log CFUcm −2 for APC, CC, EC, and SAC as 6.7, 3.4, and 3.2, respectively. It was noticed that the refrigerator was frequently used by cafeteria staff and consumers for taking of their required items (often soft drinks, cold water, juices, ice cream, and others). Due to the frequent and diverse utility of refrigerators, the chances of contamination would often be increased. Aesthetics showed as these handles were not cleaned for an extended period. Whereas serving counters were often found in good condition due to display and the main serving area, it was cleaned after every 15 to 20 minutes. However, APC was calculated as 3logCFUcm −2. The educated response was received from owners and food handlers for daily cleaning of the cafeteria and periodic cleaning of benches where food was being served. Despite their concern and proper reply for using new cleaning cloth every day, it was observed that cleaning cloth was in deplorable condition. We got three random samples for microbial analysis of those clothes. We found a high APC of 8.2 Log CFUcm −2 with mixed bacterial growth (MBG), along with yeast which was further isolated and reported in results. The washing area was also found congested, but managed very well in some cafeterias. Others have poor conditions; hand washing soap was found at its proper location in some cafeterias, whereas detergents were often used to wash utensils and hands. We collected samples of null and washbasin, where workers used to place utensils for washing. APC for this parameter was calculated very high, as reported in Figure 1. Hands of food handlers showed higher APC than previously reported as 7 log CFUcm −2 this showed poor hygienic practices that may lead to any gastrointestinal outbreak. While sampling it was found that food handlers were not aware of food safety and security. Few of the workers were observed practicing proper handwashing practices, but their clothes were mostly dirty. These workers were handling food with improperly washed hands, which seemed to be their common practice. During the survey, some of the food handlers had large hair and large nails. Dust observed in overgrown nails might be one of the causes of transmitting microbes in RTE foods prepared by those food handlers. Sometimes, it was also observed that a person having coughed and flu also process food with bare hands and without a mask. Most food handlers use aprons, but their aesthetics were poor, which ultimately increases food contamination chances. Pseudomonas spp. Overgrowth was determined from many of the utensils used in one of the sampling points where one more visit was made for further investigation and resampling. It was found that the knife, cutting board, preparation surface, washing area, and refrigerator handle were having pseudomonas spp. All workers jointly shared contamination as all these places in the cafeteria, and one was ill. Escherichia coli was isolated in salads, sauce, Chaat, and other associated preparation surfaces; the same was isolated in fully cooked RTE foods, but their number was comparatively lower. After investigation, it was observed that tap water used in all food processing showed increased total and faecal coliforms. Conclusion In conclusion, it has been identified that water serves a role in hygiene; it is suggested to use clean water, preferably filtered for all sorts of processing and preparation of food materials. Washing of all associated food preparing and serving items should be conducted with great care. Properly cleaned utensils would minimize the risk of crosscontamination. The cleaning cloth should be used once every time and should not be reused, since it cannot attain a level of sterility after washing. Washing of hands after every step of processing should be promoted and hands should be properly sanitized to reduce the chances of contamination in the food chain. Display of RTE foods should be made in a closed area where surrounding dust, aerosols, and cross-hand contamination may be minimized. |
def pretty_print_accuracy(max_vel, std):
max_vel_knots = max_vel * 1.94384
max_vel_mph = max_vel * 2.23694
max_vel_str = str(round(max_vel, 2))
max_vel_knots_str = str(round(max_vel_knots, 2))
max_vel_mph_str = str(round(max_vel_mph, 2))
std_cm_str = pretty_print_m_per_sec(std)
result = ""
error_msg = ""
result += "-The boat and water speed combined cannot exceed " + max_vel_str + " m/s or " + max_vel_knots_str + " knots or " + max_vel_mph_str + " mph\n"
result += "-The accuracy of the measurement is +/- " + std_cm_str + "\n"
if max_vel < 2.8:
error_msg += "*If you are collecting data with a boat, you may want to adjust your settings to increase the maximum velocity to exceed 2.8 m/s.\n"
return result, error_msg |
<reponame>Lucas-Bignon/bbk
// -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
// -- main.cpp --
// Copyright (c) 2001 - 2003 Jason 'vanRijn' Kasper <vR at movingparts dot net>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// E_O_H_VR
#include "KeyClient.h"
#include "version.h"
#include <string.h>
#include "main.h"
//--------------------------------------------------------
// parseOptions
//--------------------------------------------------------
void parseOptions (int argc, char **argv, Config & _config)
{
for (int i = 1; i < argc; i++) {
if ( (!strcmp(argv[i], "-d"))
|| (!strcmp(argv[i], "--display")) ) {
if (++i == argc) {
usage();
exit(2);
};
_config.setOption("display", argv[i]);
// Applications we exec will need the proper display
string disp = (string)"DISPLAY=" + argv[i];
putenv((char *)disp.c_str());
} else if ((!strcmp(argv[i], "--config")) ||
(!strcmp(argv[i], "-c"))) {
if (++i == argc) {
usage();
exit(2);
};
_config.setOption("config", argv[i]);
} else if ((!strcmp(argv[i], "-D"))
|| (!strcmp(argv[i], "--debug"))) {
_config.setOption("debug", "true");
} else if ((!strcmp(argv[i], "-v"))
|| (!strcmp(argv[i], "--version"))) {
cout << BBTOOL << " version: [" << BBTOOL_VERSION << "]" << endl;
exit(2);
} else if ((!strcmp(argv[i], "-h")) || (!strcmp(argv[i], "-help"))) {
usage();
exit(2);
} else {
usage();
exit(2);
};
}
}
void usage() {
cout << BBTOOL << " version: [" << BBTOOL_VERSION << "]" << endl
<< "Usage: " << BBTOOL << " [options]" << endl
<< "Options:" << endl
<< " -d or --display <display name> X server to connect to" << endl
<< " -D or --debug print debugging information" << endl
<< " -c or --config <filename> configuration file" << endl
<< " (default is ~/.bbkeysrc)" << endl
<< " -v or --version Display version number" << endl
<< " -h or --help Display this help" << endl;
}
int main(int argc, char **argv)
{
Config * _config = new Config();
parseOptions(argc, argv, *_config);
std::string dpy_name = _config->getStringValue("display",
getenv("DISPLAY"));
KeyClient * _k=new KeyClient(argc, argv, *_config, dpy_name);
_k->run();
delete _k;
delete _config;
return 0;
}
|
<reponame>ess-dmsc/NeXus-Streamer
#pragma once
#include <string>
struct TopicNames {
explicit TopicNames(const std::string &instrumentName)
: sampleEnv(instrumentName + "_sampleEnv"),
event(instrumentName + "_events"),
histogram(instrumentName + "_histograms"),
runInfo(instrumentName + "_runInfo"),
detSpecMap(instrumentName + "_detSpecMap"){};
const std::string sampleEnv;
const std::string event;
const std::string histogram;
const std::string runInfo;
const std::string detSpecMap;
};
|
def update_adjust_tables(self):
survey = self.obsTreeModel.itemFromIndex(self.index_current_survey)
if survey:
self.delta_model.init_data(survey.deltas)
self.datum_model.init_data(survey.datums)
self.results_model.init_data(survey.results)
stats_model = QtGui.QStandardItemModel()
if survey.adjustment.adjustmentresults.n_unknowns > 0:
stats_model.setColumnCount(2)
stats_model.setHorizontalHeaderLabels(["", ""])
for line in survey.adjustment.results_string():
try:
line_elems = line.split(":")
if len(line_elems) == 2:
stats_model.appendRow(
[
QtGui.QStandardItem(line_elems[0]),
QtGui.QStandardItem(line_elems[1].strip()),
]
)
else:
text = line_elems[0].strip()
qt_item = QtGui.QStandardItem(text)
if "rejected" in text:
qt_item.setForeground(Qt.red)
stats_model.appendRow([qt_item, QtGui.QStandardItem("")])
except:
pass
self.tab_adjust.stats_view.setModel(stats_model)
self.tab_adjust.stats_view.setColumnWidth(0, 350)
self.tab_adjust.stats_view.setColumnWidth(1, 150)
elif survey.adjustment.adjustmentresults.text:
for line in survey.adjustment.adjustmentresults.text:
stats_model.appendRow([QtGui.QStandardItem(line)])
self.tab_adjust.stats_view.setModel(stats_model)
self.tab_adjust.stats_view.setColumnWidth(0, 600)
stats_model.setColumnCount(1)
stats_model.setHorizontalHeaderLabels([""])
self.tab_adjust.update_col_widths() |
<filename>raytracer/archyrt-core/src/intersectables/sphere.rs
use crate::{
renderers::path_tracer::Material,
textures::color_provider::SolidColor,
utilities::{
math::{solve_quadratic, QuadraticResult, Vec3},
ray::{Intersectable, Intersection, IntersectionBuilder, Ray},
},
vector,
};
pub struct Sphere {
pub origin: Vec3,
pub radius: f64,
pub color: Vec3,
pub material: Material,
}
impl Default for Sphere {
fn default() -> Self {
Self {
origin: vector!(0.0, 0.0, 0.0),
radius: 1.0,
color: vector!(1.0, 1.0, 1.0),
material: Material::default(),
}
}
}
fn find_closest(solutions: QuadraticResult) -> Option<f64> {
match solutions {
QuadraticResult::TwoResults(a, b) => {
match (a, b) {
//If they are both valid and b is smaller, return b
(a, b) if a >= 0.0 && b >= 0.0 && b < a => Some(b),
//Else, if they are both valid, return a
(a, b) if a >= 0.0 && b >= 0.0 => Some(a),
//Else, if a is valid, return a
(a, _) if a >= 0.0 => Some(a),
//Else, if b is valid, return a
(_, b) if b >= 0.0 => Some(b),
//If neither of them are valid
_ => None,
}
}
QuadraticResult::OneResult(a) => {
if a >= 0.0 {
Some(a)
} else {
None
}
}
QuadraticResult::NoResults => None,
}
}
impl Intersectable for Sphere {
type C = SolidColor;
fn intersect(&self, ray: Ray) -> Option<Intersection<Self::C>> {
//Solving the equation |ray.origin+ray.direction*t-self.origin|=self.radius for t
//Rewritten: t^2*(ray.direction^2) + t*(2*ray.origin*ray.direction-2*ray.direction*self.origin)+(ray.origin^2+self.origin^2-2*ray.origin*self.origin)=self.radius^2
let t2 = 1.0; //Assuming ray is normalized. Otherwise ray.direction.length_squared()
let t = 2.0 * ray.direction.dot(ray.origin - self.origin);
let c = ray.origin.length_squared() + self.origin.length_squared()
- 2.0 * ray.origin.dot(self.origin)
- self.radius.powi(2);
let solutions = solve_quadratic(t2, t, c);
let distance = find_closest(solutions)?;
let pos = ray.direction * distance + ray.origin;
let normal = (pos - self.origin) / self.radius;
Some(
IntersectionBuilder {
distance: Some(distance),
pos: Some(pos),
ray,
normal,
color_provider: SolidColor(self.color, self.material),
..Default::default()
}
.build(),
)
}
}
|
A union of incoherent spaces model for classification We present a new and computationally efficient scheme for classifying signals into a fixed number of known classes. We model classes as subspaces in which the corresponding data is well represented by a dictionary of features. In order to ensure low misclassification, the subspaces should be incoherent so that features of a given class cannot represent efficiently signals from another. We propose a simple iterative strategy to learn dictionaries which are are the same time good for approximating within a class and also discriminant. Preliminary tests on a standard face images database show competitive results. |
PROTECTION OF CHILDREN VICTIMS OF VIOLENCE IN THE FAMILY PERSPECTIVE OF ISLAMIC FAMILY LAW AND POSITIVE LAW (Study at the Lampung Province Child Protection Institute, the Damar Lampung Child Advocacy Institute and the Regional Technical Implementation Uni A child protection refers to any efforts aimed at ensuring and protecting children and their rights so that they can grow, develop, and contribute to their full potential while remaining safe from violence and discrimination. Child protection is handled by a number of organizations, namely the Child Protection Institute, Lampung, the child advocacy institution of Damar Lampung, and the Technical Implementation Unit for the Protection of Women and Children, Lampung. Despite the fact that these three organizations exist and operate, family violence against children continues to rise. The conclusions are Threats, compulsion, fear, opportunity, power relations, economy, patriarchy, lack of morals, inability to control themselves, retribution, and lack of attention from biological moms to children's behavior are all prevalent reasons of violence against children in three institutions. The difference is that there is a sexual disorder, husband is afraid of his old wife, lack of communication between children and mother, home environment, access to meet is cut off, mother dies, revenge, persuasion, habit of having sexual relations. Study/add insight into Islam and practice it, learn and practice good morals, hang out a lot with pious and pious people, exercise self-control, psychological approach, intensity of education are some of the solutions to decrease them. The types of services provided by child protection institutions, child advocacy institutions, and the Technical Implementation Unit for the Protection of Women and Children (UPTD PPA) are similar in terms of type of service, legal basis, service principle, Standard Operating Procedure (SOP) for mentoring, code of ethics, and ethics, but each has its own characteristics in terms of technical assistance, human resources, funding sources, and facilities. The hadhanah concept (care, care, and education) is reflected in the perspective of Islamic family law and positive law on child protection carried out by three institutions, referring to Law No. 4 of 1979 concerning Child Welfare, Law No. 35 of 2014 on Child Protection, Law No. 11 of 2012 on Child Criminal Justice, Law No. 23 of 2004 on Marriage, Compilation of Islamic Law leading to District Courts (Criminal), Religious Courts (Civil), and Mediation. |
/*============================================================================
*
* ModemTxSetPermanentData
*
* Initializes non-HDLC data transmission. Configures the modem
* to the indicated speed, init's sending data, sends
* the training sequence, and returns.
*
* Input: configure = TRUE if need to reconfigure
* data = The byte to send repeatedly
* speed = desired data mode (index into modem speed table)
* training = long or short train
*
* Index Speed
* 0 V.21, 300
* 1 V.27, 2400
* 2 V.27, 4800
* 3 V.29, 7200
* 4 V.29, 9600
* 5 V.17, 7200
* 6 V.17, 9600
* 7 V.17, 12000
* 8 V.17, 14400
*
* Output: ModemControl->State = T4_TX_MODE
* TDBIE = 1
*============================================================================*/
void ModemTxSetPermanentData( UINT8 configure, UINT8 data,
UINT8 speed, UINT8 training )
{
if ( configure )
{
ModemControl->Status = NO_ERROR;
ModemSetTraining( training );
ModemTxConfigHiSpeed( speed );
ModemClearIRQ();
ModemControl->State = T4_TX_MODE;
}
MDM_WRITE( MODEM_TBUFF, data );
} |
Oscar Pistorius, Ellie Simmonds and Natalie du Toit are among the stars featuring at the London Paralympic Games - BBC Sport picks out some of the likely highlights from 11 days of sporting action.
Athletics - Britain's leading wheelchair racers David Weir and Shelly Woods will hope to finish the Paralympics on a high in the marathon (men 11:30, women 11.32), with the action due to end on The Mall at around 13:00.
Wheelchair Rugby - Great Britain failed to make it through the group stage and so will not be involved in the medal matches at the Basketball Arena, with the battle for bronze at 12:00 and the gold medal match at 14:15.
Football 7-a-side - The final medals of London 2012 will be decided at the Riverbank Arena, with Brazil v Iran for bronze (13:30) before Russia v Ukraine in the gold medal match (16:00). Great Britain play the USA in the 7th-8th place classification match (08:30).
Closing ceremony - After 10 days of competition, the curtain comes down on the 2012 London Paralympics. Kim Gavin, artistic director of the Olympic and Paralympic closing ceremonies, says: "It will be a festival of flame. Through Coldplay's music we are going to take you through the seasons from autumn to summer. There will be a tribute to Help for Heroes and the Union Jack will be revealed for the national anthem in a special way." |
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::FSM_MODE {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct RESERVED20R {
bits: u16,
}
impl RESERVED20R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u16 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct RDV_SUBMODER {
bits: u8,
}
impl RDV_SUBMODER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct PGM_SUBMODER {
bits: u8,
}
impl PGM_SUBMODER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct ERA_SUBMODER {
bits: u8,
}
impl ERA_SUBMODER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct SUBMODER {
bits: u8,
}
impl SUBMODER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct SAV_PGM_CMDR {
bits: u8,
}
impl SAV_PGM_CMDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct SAV_ERA_MODER {
bits: u8,
}
impl SAV_ERA_MODER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct MODER {
bits: u8,
}
impl MODER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct CMDR {
bits: u8,
}
impl CMDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _RESERVED20W<'a> {
w: &'a mut W,
}
impl<'a> _RESERVED20W<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
const MASK: u16 = 4095;
const OFFSET: u8 = 20;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _RDV_SUBMODEW<'a> {
w: &'a mut W,
}
impl<'a> _RDV_SUBMODEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 18;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _PGM_SUBMODEW<'a> {
w: &'a mut W,
}
impl<'a> _PGM_SUBMODEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 16;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _ERA_SUBMODEW<'a> {
w: &'a mut W,
}
impl<'a> _ERA_SUBMODEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 14;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _SUBMODEW<'a> {
w: &'a mut W,
}
impl<'a> _SUBMODEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _SAV_PGM_CMDW<'a> {
w: &'a mut W,
}
impl<'a> _SAV_PGM_CMDW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _SAV_ERA_MODEW<'a> {
w: &'a mut W,
}
impl<'a> _SAV_ERA_MODEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _MODEW<'a> {
w: &'a mut W,
}
impl<'a> _MODEW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _CMDW<'a> {
w: &'a mut W,
}
impl<'a> _CMDW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 7;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 20:31 - 31:20\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn reserved20(&self) -> RESERVED20R {
let bits = {
const MASK: u16 = 4095;
const OFFSET: u8 = 20;
((self.bits >> OFFSET) & MASK as u32) as u16
};
RESERVED20R { bits }
}
#[doc = "Bits 18:19 - 19:18\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn rdv_submode(&self) -> RDV_SUBMODER {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 18;
((self.bits >> OFFSET) & MASK as u32) as u8
};
RDV_SUBMODER { bits }
}
#[doc = "Bits 16:17 - 17:16\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn pgm_submode(&self) -> PGM_SUBMODER {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 16;
((self.bits >> OFFSET) & MASK as u32) as u8
};
PGM_SUBMODER { bits }
}
#[doc = "Bits 14:15 - 15:14\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn era_submode(&self) -> ERA_SUBMODER {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 14;
((self.bits >> OFFSET) & MASK as u32) as u8
};
ERA_SUBMODER { bits }
}
#[doc = "Bits 12:13 - 13:12\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn submode(&self) -> SUBMODER {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) as u8
};
SUBMODER { bits }
}
#[doc = "Bits 9:11 - 11:9\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn sav_pgm_cmd(&self) -> SAV_PGM_CMDR {
let bits = {
const MASK: u8 = 7;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) as u8
};
SAV_PGM_CMDR { bits }
}
#[doc = "Bits 6:8 - 8:6\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn sav_era_mode(&self) -> SAV_ERA_MODER {
let bits = {
const MASK: u8 = 7;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) as u8
};
SAV_ERA_MODER { bits }
}
#[doc = "Bits 3:5 - 5:3\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn mode(&self) -> MODER {
let bits = {
const MASK: u8 = 7;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) as u8
};
MODER { bits }
}
#[doc = "Bits 0:2 - 2:0\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn cmd(&self) -> CMDR {
let bits = {
const MASK: u8 = 7;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
CMDR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 20:31 - 31:20\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn reserved20(&mut self) -> _RESERVED20W {
_RESERVED20W { w: self }
}
#[doc = "Bits 18:19 - 19:18\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn rdv_submode(&mut self) -> _RDV_SUBMODEW {
_RDV_SUBMODEW { w: self }
}
#[doc = "Bits 16:17 - 17:16\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn pgm_submode(&mut self) -> _PGM_SUBMODEW {
_PGM_SUBMODEW { w: self }
}
#[doc = "Bits 14:15 - 15:14\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn era_submode(&mut self) -> _ERA_SUBMODEW {
_ERA_SUBMODEW { w: self }
}
#[doc = "Bits 12:13 - 13:12\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn submode(&mut self) -> _SUBMODEW {
_SUBMODEW { w: self }
}
#[doc = "Bits 9:11 - 11:9\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn sav_pgm_cmd(&mut self) -> _SAV_PGM_CMDW {
_SAV_PGM_CMDW { w: self }
}
#[doc = "Bits 6:8 - 8:6\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn sav_era_mode(&mut self) -> _SAV_ERA_MODEW {
_SAV_ERA_MODEW { w: self }
}
#[doc = "Bits 3:5 - 5:3\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn mode(&mut self) -> _MODEW {
_MODEW { w: self }
}
#[doc = "Bits 0:2 - 2:0\\] Internal. Only to be used through TI provided API."]
#[inline]
pub fn cmd(&mut self) -> _CMDW {
_CMDW { w: self }
}
}
|
Beware of white matter hyperintensities causing systematic errors in FreeSurfer gray matter segmentations! Abstract Volumetric estimates of subcortical and cortical structures, extracted from T1weighted MRIs, are widely used in many clinical and research applications. Here, we investigate the impact of the presence of white matter hyperintensities (WMHs) on FreeSurfer gray matter (GM) structure volumes and its possible bias on functional relationships. T1weighted images from 1,077 participants (4,321 timepoints) from the Alzheimer's Disease Neuroimaging Initiative were processed with FreeSurfer version 6.0.0. WMHs were segmented using a previously validated algorithm on either T2weighted or Fluidattenuated inversion recovery images. Mixedeffects models were used to assess the relationships between overlapping WMHs and GM structure volumes and overall WMH burden, as well as to investigate whether such overlaps impact associations with age, diagnosis, and cognitive performance. Participants with higher WMH volumes had higher overlaps with GM volumes of bilateral caudate, cerebral cortex, putamen, thalamus, pallidum, and accumbens areas (p<.0001). When not corrected for WMHs, caudate volumes increased with age (p<.0001) and were not different between cognitively healthy individuals and agematched probable Alzheimer's disease patients. After correcting for WMHs, caudate volumes decreased with age (p<.0001), and Alzheimer's disease patients had lower caudate volumes than cognitively healthy individuals (p<.01). Uncorrected caudate volume was not associated with ADAS13 scores, whereas corrected lower caudate volumes were significantly associated with poorer cognitive performance (p<.0001). Presence of WMHs leads to systematic inaccuracies in GM segmentations, particularly for the caudate, which can also change clinical associations. While specifically measured for the Freesurfer toolkit, this problem likely affects other algorithms. On T1-weighted (T1w) MRI sequences, WMHs appear hypointense with respect to the normal-appearing white matter, with intensities that can be very similar to cortical and subcortical gray matter (GM). The T1w intensity of WMHs is also associated with severity of damage to the tissue, with areas of higher damage appearing more hypointense (Dadar, Maranzano, Ducharme, & Collins, 2019). As T1w images are the most commonly used structural MRI sequences in clinical and neuroscience applications, especially for purposes of segmentation and estimation of volumes for all or specific structures of interest (), the similarity in T1w intensity profiles of WMHs and GM gives rise to an important methodological question: can T1w MRI-based GM structure segmentation differentiate between WMHs and GM? If not, how much of WMHs will be tagged as GM in their segmentation estimates, and if so, is this error systematic enough to bias results? Simulating lesions with varying volumes and intensity ranges, Chard et al showed that both GM and WM volumes estimated by SPM were affected by presence of WM lesions (). Similarly, using both real and simulated data, Gelineau-Morel showed that presence of WM lesions can influence volume and shape estimations of GM measures in segmentations from FSL FAST (). In the context of MS, lesion filling approaches are generally employed before tissue classification and GM segmentation steps, to avoid the segmentations errors caused by presence of MS lesions (Battaglini, Jenkinson, & Stefano, 2012;;;;;;Valverde, Oliver, & Llad, 2014). To answer this question, we propose our study of WMHs segmentation bias in subcortical and cortical GM structures. More specifically, we investigated (a) whether there was any systematic overlap between WMHs and GM segmentations, and therefore volumetric biases; and (b) whether this overlap affected clinical findings (i.e., associations with cognitive scores). To these ends we used two segmentation tools, the first being FreeSurfer, one of the most commonly used publicly available brain segmentation tools, and a previously validated tool for WMHs segmentation on multicontrast MRIs | WMH segmentations T1w, T2w/PDw, and FLAIR scans were pre-processed as follows: (a) image denoising (Manjn, Coup, Mart-Bonmat, Collins, & Robles, 2010); (b) intensity inhomogeneity correction; and (c) intensity normalization to a 0-100 range. For each subject, the T2w, PDw, or FLAIR scans were then co-registered to the structural T1w scan of the same timepoint using a 6-parameter rigid registration and a mutual information objective function (Dadar, Fonov, Collins, & Initiative, 2018). We used a previously validated WMH segmentation method that employs a set of location and intensity features in combination with a random forests classifier to detect WMHs using either T1w + FLAIR or T1w + T2w/ PDw images. The training library consisted in manual, expert segmentations of WMHs from 100 subjects from ADNI (not included in the current sample) (Dadar, Pascoal, et al., 2017;Dadar, Maranzano, Misquitta, et al., 2017;. WMHs were automatically segmented at all timepoints and then co-registered to the T1w images using the obtained rigid registrations, in order to assess overlaps between WMHs and GM segmentations. | Cognitive evaluations All subjects received a comprehensive battery of clinical assessments and cognitive testing based on a standardized protocol (adni.loni.usc. edu) (). At each visit, participants underwent a series of assessments including the Alzheimer's Disease Assessment Scale-13 (ADAS13) (Mohs & Cohen, 1987), which was used to assess cognitive performance. | Statistical analyses Overlaps between GM and WMH segmentations were calculated (number of overlapping voxels in mm 3 ) for each subcortical and cortical GM region. The following mixed effects models were used to assess whether the WMH-GM overlaps were associated with overall WMH burden, controlling for age and sex. Since both WMHs and GM volumes are highly correlated with age, and WMHs might have a different prevalence between men and women, we controlled for age and sex, to account for the likelihood that (a portion of) the relationships might be driven by intercorrelations between these factors. Mixed effects models were also used to assess the relationships between GM volumes and age and diagnostic cohort, and GM volumes and cognition, once using the GM volume estimates obtained directly from the FreeSurfer segmentation, and once after removing the regions overlapping with the WMH segmentations. GM volume 1 + Age + Sex + Cohort + Scanner Manufacturer ADAS13 1 + Age + Sex + GM volume + Scanner Manufacturer All volumes were normalized by the individual's intracranial volume. manufacturers. The results were corrected for multiple comparisons using the false discovery rate (FDR) controlling method with a significance threshold of p =.05 (Benjamini & Hochberg, 1995). | Data and code availability statement Data used in this article is available at http://adni.loni.usc.edu/. | Study participants Preprocessed and registered images were visually assessed for quality control (presence of imaging artifacts, failure in registrations). WMH segmentations were also visually assessed for missing hyperintensities or over-segmentation. Either failures resulted in the participant being removed from the analyses. All MRI processing, segmentation and quality control steps were blinded to clinical outcomes. All cases passed co-registration QC. Figure 1 summarizes the QC information for the subjects that were excluded. The final sample included 1,077 participants (4,321 timpoints) with WMH and FreeSurfer segmentations. Uncorrected caudate volumes were not significantly associated with ADAS13 scores (Table 4), whereas lower corrected caudate volumes were significantly associated with higher ADAS13 scores (i.e., poorer cognitive performance, p <.0001). The uncorrected and corrected results were similar in terms of effect size and direction of associations for other regions, with the corrected volumes having slightly larger effects sizes for putamen. Table S3 shows the associations between ADAS13 and GM volumes for all regions, before and after removing the voxels overlapping with WMHs. Figure 5 shows the associations between uncorrected and corrected caudate volumes and ADAS13 scores. | DISCUSSION In this study, we investigated the impact of WMHs on GM segmentations, specifically for the Freesurfer segmentation tool, in order to determine whether WMHs might lead to systematic segmentation errors in certain GM regions, and whether such errors might impact associations between GM volumes and clinical outcomes. We found such errors in a number of regions, and in the caudate in particular it propagated to the association with clinical variables. We found that overlapping voxel volumes between WMH and GM segmentations were significantly associated with overal WMH burden ( F I G U R E 3 The association between overlapping GM and WMH volumes and overall WMH burden (Table 2). Subjects with higher WMH loads also have greater amounts of WMH overlap with FreeSurfer GM segmentations in bilateral caudate, cerebral cortex, and putamen. GM = Gray Matter. WMH = White Matter Hyperintensity has been developed and extensively validated for use in multi-site and multi-scanner studies, and has been previously used in several multisite datasets, including ADNI (Anor, Dadar, Collins, & Tartaglia, 2020;;Dadar, Camicioli, Duchesne, Collins, & Initiative, 2020;Dadar, Gee, Shuaib, Duchesne, & Camicioli, 2020;;). The training library used consists of manually segmented labels from the same dataset (ADNI), to ensure optimal classifier performance (Dadar, Maranzano, Misquitta, et al., 2017). Further, all automatic WMH segmentations were visually assessed by an expert, and cases that failed this QC step were removed from this analysis. FreeSurfer is one of the most widely used publicly available brain segmentation tools. Large databases such as the UK Biobank provide GM structure volumes derived from FreeSurfer to researchers. In line with our findings, other researchers have reported a positive association between WMH load and FreeSurfer caudate volumes in the UK biobank participants (Morys, Dadar, & Dagher, 2020) and in another large sample of cognitively healthy individuals (Potvin, Dieumegarde, Duchesne, & Initiative, 2017). Studies investigating a larger age range report a U-shape curve for caudate volumes, decreasing from early adulthood to the 60s, and then increasing afterwards ((Fjell et al.,, 2013Goodro, Sameti, Patenaude, & Fein, 2012;;b;). Given that WMHs generally occur in this same age range (i.e., after 60s), these results are also likely due to the segmentation errors cau- (;;;Jenkinson, Beckmann, Behrens, Woolrich, & Smith, 2012). In other words, misclassification of lesions as GM might lead to an overall increase in the mean GM intensities, causing GM boundaries to shift toward lighter (WM) regions, further increasing overall GM volume estimates (;). The WMHs that are observed in the aging and neurodegenerative populations have a different pathogenesis from MS lesions. They generally co-occur with (extensive) atrophy, and have more varying loads and less well-shaped borders than MS lesions (). |
Ulcerlike lesions of the aorta: imaging features and natural history. PURPOSE To document the natural history of ulcerlike aortic lesions and determine whether any computed tomographic (CT) features predict outcome. MATERIALS AND METHODS CT scans from 1994 to 1998 that depicted an ulcerlike aortic lesion were retrospectively evaluated. Features evaluated included lesion and aortic size and intramural hematoma. Initial CT findings were correlated with clinical data and subsequent CT findings. RESULTS There were 56 lesions in 38 patients. Follow-up (mean, 18.4 months) CT scans were available for 33 lesions. Stability of the lesion and adjacent aorta was noted in 21 lesions. Two lesions were unchanged, although associated intramural hematoma regressed over 1-2 months. Ten lesions showed mild to moderate increase in aortic diameter (mean follow-up, 19.8 months) either with (seven lesions) or without (one lesion) increase in size of the lesion or with incorporation of the lesion into the aortic wall contour (two lesions). Of all 56 lesions, 37 were clinically stable, two were associated with recurrent chest and/or back pain, eight underwent surgical resection or stent placement, and two were in patients who died. Seven lesions were in patients lost to follow-up. No initial CT feature was predictive of CT outcome, although lack of pleural effusion correlated with clinical stability. CONCLUSION Most ulcerlike aortic lesions are asymptomatic and do not enlarge. About one-third of lesions progress, generally resulting in mild interval aortic enlargement. |
<filename>vendor/github.com/Azure/azure-sdk-for-go/arm/relay/models.go
package relay
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/date"
"github.com/Azure/go-autorest/autorest/to"
"net/http"
)
// AccessRights enumerates the values for access rights.
type AccessRights string
const (
// Listen specifies the listen state for access rights.
Listen AccessRights = "Listen"
// Manage specifies the manage state for access rights.
Manage AccessRights = "Manage"
// Send specifies the send state for access rights.
Send AccessRights = "Send"
)
// PolicyKey enumerates the values for policy key.
type PolicyKey string
const (
// PrimaryKey specifies the primary key state for policy key.
PrimaryKey PolicyKey = "PrimaryKey"
// SecondaryKey specifies the secondary key state for policy key.
SecondaryKey PolicyKey = "SecondaryKey"
)
// RelaytypeEnum enumerates the values for relaytype enum.
type RelaytypeEnum string
const (
// HTTP specifies the http state for relaytype enum.
HTTP RelaytypeEnum = "Http"
// NetTCP specifies the net tcp state for relaytype enum.
NetTCP RelaytypeEnum = "NetTcp"
)
// UnavailableReason enumerates the values for unavailable reason.
type UnavailableReason string
const (
// InvalidName specifies the invalid name state for unavailable reason.
InvalidName UnavailableReason = "InvalidName"
// NameInLockdown specifies the name in lockdown state for unavailable
// reason.
NameInLockdown UnavailableReason = "NameInLockdown"
// NameInUse specifies the name in use state for unavailable reason.
NameInUse UnavailableReason = "NameInUse"
// None specifies the none state for unavailable reason.
None UnavailableReason = "None"
// SubscriptionIsDisabled specifies the subscription is disabled state for
// unavailable reason.
SubscriptionIsDisabled UnavailableReason = "SubscriptionIsDisabled"
// TooManyNamespaceInCurrentSubscription specifies the too many namespace
// in current subscription state for unavailable reason.
TooManyNamespaceInCurrentSubscription UnavailableReason = "TooManyNamespaceInCurrentSubscription"
)
// AuthorizationRule is description of a Namespace AuthorizationRules.
type AuthorizationRule struct {
autorest.Response `json:"-"`
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"`
*AuthorizationRuleProperties `json:"properties,omitempty"`
}
// AuthorizationRuleKeys is namespace/Relay Connection String
type AuthorizationRuleKeys struct {
autorest.Response `json:"-"`
PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"`
SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"`
PrimaryKey *string `json:"primaryKey,omitempty"`
SecondaryKey *string `json:"secondaryKey,omitempty"`
KeyName *string `json:"keyName,omitempty"`
}
// AuthorizationRuleListResult is the response of the List Namespace operation.
type AuthorizationRuleListResult struct {
autorest.Response `json:"-"`
Value *[]AuthorizationRule `json:"value,omitempty"`
NextLink *string `json:"nextLink,omitempty"`
}
// AuthorizationRuleListResultPreparer prepares a request to retrieve the next set of results. It returns
// nil if no more results exist.
func (client AuthorizationRuleListResult) AuthorizationRuleListResultPreparer() (*http.Request, error) {
if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(client.NextLink)))
}
// AuthorizationRuleProperties is authorizationRule properties.
type AuthorizationRuleProperties struct {
Rights *[]AccessRights `json:"rights,omitempty"`
}
// CheckNameAvailability is description of a Check Name availability request
// properties.
type CheckNameAvailability struct {
Name *string `json:"name,omitempty"`
}
// CheckNameAvailabilityResult is description of a Check Name availability
// request properties.
type CheckNameAvailabilityResult struct {
autorest.Response `json:"-"`
NameAvailable *bool `json:"nameAvailable,omitempty"`
Reason UnavailableReason `json:"reason,omitempty"`
Message *string `json:"message,omitempty"`
}
// ErrorResponse is error reponse indicates Relay service is not able to
// process the incoming request. The reason is provided in the error message.
type ErrorResponse struct {
Code *string `json:"code,omitempty"`
Message *string `json:"message,omitempty"`
}
// HybridConnection is description of HybridConnection Resource.
type HybridConnection struct {
autorest.Response `json:"-"`
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"`
*HybridConnectionProperties `json:"properties,omitempty"`
}
// HybridConnectionListResult is the response of the List HybridConnection
// operation.
type HybridConnectionListResult struct {
autorest.Response `json:"-"`
Value *[]HybridConnection `json:"value,omitempty"`
NextLink *string `json:"nextLink,omitempty"`
}
// HybridConnectionListResultPreparer prepares a request to retrieve the next set of results. It returns
// nil if no more results exist.
func (client HybridConnectionListResult) HybridConnectionListResultPreparer() (*http.Request, error) {
if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(client.NextLink)))
}
// HybridConnectionProperties is properties of the HybridConnection.
type HybridConnectionProperties struct {
CreatedAt *date.Time `json:"createdAt,omitempty"`
UpdatedAt *date.Time `json:"updatedAt,omitempty"`
ListenerCount *int32 `json:"listenerCount,omitempty"`
RequiresClientAuthorization *bool `json:"requiresClientAuthorization,omitempty"`
UserMetadata *string `json:"userMetadata,omitempty"`
}
// Namespace is description of a Namespace resource.
type Namespace struct {
autorest.Response `json:"-"`
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"`
Location *string `json:"location,omitempty"`
Tags *map[string]*string `json:"tags,omitempty"`
Sku *Sku `json:"sku,omitempty"`
*NamespaceProperties `json:"properties,omitempty"`
}
// NamespaceListResult is the response of the List Namespace operation.
type NamespaceListResult struct {
autorest.Response `json:"-"`
Value *[]Namespace `json:"value,omitempty"`
NextLink *string `json:"nextLink,omitempty"`
}
// NamespaceListResultPreparer prepares a request to retrieve the next set of results. It returns
// nil if no more results exist.
func (client NamespaceListResult) NamespaceListResultPreparer() (*http.Request, error) {
if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(client.NextLink)))
}
// NamespaceProperties is properties of the Namespace.
type NamespaceProperties struct {
ProvisioningState *string `json:"provisioningState,omitempty"`
CreatedAt *date.Time `json:"createdAt,omitempty"`
UpdatedAt *date.Time `json:"updatedAt,omitempty"`
ServiceBusEndpoint *string `json:"serviceBusEndpoint,omitempty"`
MetricID *string `json:"metricId,omitempty"`
}
// NamespaceUpdateParameter is parameters supplied to the Patch Namespace
// operation.
type NamespaceUpdateParameter struct {
Tags *map[string]*string `json:"tags,omitempty"`
Sku *Sku `json:"sku,omitempty"`
}
// Operation is a EventHub REST API operation
type Operation struct {
Name *string `json:"name,omitempty"`
Display *OperationDisplay `json:"display,omitempty"`
}
// OperationDisplay is the object that represents the operation.
type OperationDisplay struct {
Provider *string `json:"provider,omitempty"`
Resource *string `json:"resource,omitempty"`
Operation *string `json:"operation,omitempty"`
}
// OperationListResult is result of the request to list EventHub operations. It
// contains a list of operations and a URL link to get the next set of results.
type OperationListResult struct {
autorest.Response `json:"-"`
Value *[]Operation `json:"value,omitempty"`
NextLink *string `json:"nextLink,omitempty"`
}
// OperationListResultPreparer prepares a request to retrieve the next set of results. It returns
// nil if no more results exist.
func (client OperationListResult) OperationListResultPreparer() (*http.Request, error) {
if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(client.NextLink)))
}
// RegenerateKeysParameters is parameters supplied to the Regenerate
// Authorization Rule operation.
type RegenerateKeysParameters struct {
PolicyKey PolicyKey `json:"policyKey,omitempty"`
}
// Resource is the Resource definition
type Resource struct {
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"`
}
// Sku is sku of the Namespace.
type Sku struct {
Name *string `json:"name,omitempty"`
Tier *string `json:"tier,omitempty"`
}
// TrackedResource is definition of Resource
type TrackedResource struct {
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"`
Location *string `json:"location,omitempty"`
Tags *map[string]*string `json:"tags,omitempty"`
}
// WcfRelay is description of WcfRelays Resource.
type WcfRelay struct {
autorest.Response `json:"-"`
ID *string `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"`
*WcfRelayProperties `json:"properties,omitempty"`
}
// WcfRelayProperties is properties of the WcfRelay Properties.
type WcfRelayProperties struct {
RelayType RelaytypeEnum `json:"relayType,omitempty"`
CreatedAt *date.Time `json:"createdAt,omitempty"`
UpdatedAt *date.Time `json:"updatedAt,omitempty"`
ListenerCount *int32 `json:"listenerCount,omitempty"`
RequiresClientAuthorization *bool `json:"requiresClientAuthorization,omitempty"`
RequiresTransportSecurity *bool `json:"requiresTransportSecurity,omitempty"`
IsDynamic *bool `json:"isDynamic,omitempty"`
UserMetadata *string `json:"userMetadata,omitempty"`
}
// WcfRelaysListResult is the response of the List WcfRelays operation.
type WcfRelaysListResult struct {
autorest.Response `json:"-"`
Value *[]WcfRelay `json:"value,omitempty"`
NextLink *string `json:"nextLink,omitempty"`
}
// WcfRelaysListResultPreparer prepares a request to retrieve the next set of results. It returns
// nil if no more results exist.
func (client WcfRelaysListResult) WcfRelaysListResultPreparer() (*http.Request, error) {
if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(client.NextLink)))
}
|
With our national fixation on Obama and the White House, it's easy to overlook local results and the real progressive mandate.
A month after Barack Obama's triumphant victory, we are still celebrating America's only authentic national religion, and it isn't Christianity -- it's presidentialism, the worship of the president as an all-powerful, all-knowing deity who is the only important political actor in our country.
This theology explains why both the public and the press corps seem far more interested in the Obama family dog and the Obama daughters' choice of elementary school than what happened down-ticket on Election Day. In our nation, presidential pooches and prep schools are front-page stories. Local democracy is, at best, filler surrounding classified ads and comic strips.
That said, the Founding Fathers would be happy to know that, though their efforts to constitutionally constrain presidentialism failed, we still go to the trouble of holding non-presidential elections. And those contests could mean as much policy progress as what happens at 1600 Pennsylvania Avenue.
For example, 2008 capped off a stunning string of state legislative victories that leaves one-third of Americans now living in 17 Democratic "trifecta" states -- those where Democrats control the governorship, state House and state Senate. Trifecta-state Democratic legislators and governors now have the unobstructed opportunity to play a pivotal role on everything from setting national energy and health industry standards to addressing rampant wealth inequality.
Chief among these trifecta victories was the one giving Democrats control of New York's government for the first time since the New Deal. The Empire State is home to the financial industry and one of the largest economies in the world, meaning Albany Democrats can make a particularly huge impact with their state laws. They will need to be pushed, though -- and that's where the Working Families Party (WFP) comes in.
The third party, which is organized around a narrow set of populist economic positions, has leveraged its ballot line in New York's fusion voting system to help progressive Democrats win key elections. Because of the party's decisive work in recent campaigns, Democrats "owe a heavy debt to the WFP," as the Albany Times Union reports, and the WFP will be calling in that debt by demanding passage of priorities like a millionaires tax -- a major revenue raiser in a place that domiciles Wall Street. With the party's additionally important 2008 gains in Connecticut and Oregon, the WFP may be the model for a new kind of third-party politics -- one that isn't defined by attention-hungry presidential gadflies, actually does the unglamorous work of local organizing and ultimately wields significant power.
Here out West, the election represented both legislative changes and paradigmatic earthquakes that bode well for the rest of the country.
As the Denver Post reported, Democrat Mark Udall's resounding U.S. Senate victory in the face of Republican Bob Schaffer's relentless criticism of him as a "Boulder liberal" has effectively defanged the entire "liberal" attack in a once reliable GOP stronghold. Additionally, not only did Colorado become the first state in history to elect both a state House and state Senate headed by African-Americans, it saw a grass-roots campaign led by the Colorado Progressive Coalition make it the first state to reject a ballot initiative that has gutted affirmative action and equal pay laws in other locales. According to the Ballot Initiative Strategy Center, that was one of 22 out of 26 national conservative ballot initiatives that went down to defeat in 2008.
These are just some of the structural shifts that happened beneath the Electoral College vote maps wallpapering our church of presidentialism. They may seem obscure, unimportant and small in comparison to the Beltway's palace dramas. But they have set the stage for precisely the kind of nationwide "bottom-up" change that Washington's filibusters and fighting all too often prevent. |
Henry J. Miller, Fire and Police Commissioner, Village of Lincolnwood. Beloved husband of Lillian, nee Seigh; loving father of Claudia and Bob; dear brother of the late Margaret (late John) Melehes. Funeral Thursday 9:30 a.m. from Smith-Corcoran Funeral Home, 6150 N. Cicero Ave., to Queen of All Saints Basilica for mass at 10 a.m. Interment St. Joseph Cemetery. Visitation Wednesday 3 to 9 p.m. 773-736-3833. |
/**
* Created by akonopko on 13.02.15.
*/
public class FixTableComparer implements FixtureComparer {
private final FixObjectCreator<FixTable> expectedDataCreator;
private final FixObjectCreator<FixTable> actualDataCreator;
private final boolean columnNamesOrdered;
private final boolean respectRowOrder;
public FixTableComparer(FixObjectCreator<FixTable> expectedDataCreator, FixObjectCreator<FixTable> actualDataCreator, boolean columnNamesOrdered, boolean respectRowOrder) {
this.expectedDataCreator = expectedDataCreator;
this.actualDataCreator = actualDataCreator;
this.columnNamesOrdered = columnNamesOrdered;
this.respectRowOrder = respectRowOrder;
}
public FixObjectCreator<FixTable> getExpectedDataCreator() {
return expectedDataCreator;
}
public FixObjectCreator<FixTable> getActualDataCreator() {
return actualDataCreator;
}
public boolean isColumnNamesOrdered() {
return columnNamesOrdered;
}
public boolean isRespectRowOrder() {
return respectRowOrder;
}
@Override
public FixObjectCompareResult check(TestRun testRun) throws Exception {
FixTable expected = expectedDataCreator.create(testRun);
FixTable actual = actualDataCreator.create(testRun);
List<String> expectedColumns = expected.getColumnNames();
List<String> actualColumns = actual.getColumnNames();
boolean wrongColNames = columnNamesOrdered && !expectedColumns.equals(actualColumns);
wrongColNames |= !columnNamesOrdered && !equalsIgnoreOrder(expectedColumns, actualColumns);
if (wrongColNames) {
String expectedColDesc = StringUtils.join(expectedColumns, ", ");
String actualColDesc = StringUtils.join(actualColumns, ", ");
return FixObjectCompareResult.failed(
"Column Names for expected and actual data set differed: expected [" +
expectedColDesc + "] but was [" + actualColDesc + "]"
);
}
if (expected.getRows().size() != actual.getRows().size()) {
return FixObjectCompareResult.failed(
"Data set size for expected and actual data set differed: expected has " +
expected.getRows().size() + " while actual data has " + actual.getRows().size() + " rows"
);
}
if (respectRowOrder) {
Map<String, FixObjectCompareResult> fails = compareRespectOrder(expected, actual);
if (!fails.isEmpty()) {
return FixObjectCompareResult.wrapFailed(fails, "");
}
return FixObjectCompareResult.SUCCESS;
} else {
Map<FixTable.FixRow, Integer> expectedRes = countEntries(expected);
Map<FixTable.FixRow, Integer> actualRes = countEntries(actual);
return CompareHelper.compareEntityNumber(testRun, actualDataCreator, expectedDataCreator, expectedRes, actualRes);
}
}
private Map<FixTable.FixRow, Integer> countEntries(FixTable expected) {
Map<FixTable.FixRow, Integer> expEntryCount = Maps.newHashMap();
for (FixTable.FixRow row : expected.getRows()) {
Integer count = expEntryCount.get(row);
if (count == null) {
count = 1;
} else {
count = count + 1;
}
expEntryCount.put(row, count);
}
return expEntryCount;
}
private Map<String, FixObjectCompareResult> compareRespectOrder(FixTable expected, FixTable actual) {
Map<String, FixObjectCompareResult> fails = Maps.newLinkedHashMap();
ListIterator<FixTable.FixRow> expIter = expected.getRows().listIterator();
ListIterator<FixTable.FixRow> actIter = actual.getRows().listIterator();
while (expIter.hasNext()) {
FixTable.FixRow expRow = expIter.next();
FixTable.FixRow actRow = actIter.next();
FixObjectCompareResult result = compareFixRows(expected.getColumnNames(), expRow, actRow);
if (result.getStatus() == FixObjectCompareResult.Status.FAIL) {
fails.put("Row #" + expIter.previousIndex(), result);
}
}
return fails;
}
private FixObjectCompareResult compareFixRows(List<String> columnNames, FixTable.FixRow expRow, FixTable.FixRow actRow) {
if (expRow.equals(actRow)) {
return FixObjectCompareResult.SUCCESS;
}
List<String> expDesc = Lists.newArrayList();
List<String> actDesc = Lists.newArrayList();
for (String key: columnNames) {
String expValue = expRow.getCells().get(key);
String actValue = actRow.getCells().get(key);
if (!expValue.equals(actValue)) {
expDesc.add(key + "=" + expValue);
actDesc.add(key + "=" + actValue);
}
}
String differenctDescription =
"Cells in expected data set: [" + StringUtils.join(expDesc, ", ") + "], " +
"cells in actual data set: [" + StringUtils.join(actDesc, ", ") + "]";
return FixObjectCompareResult.failed(differenctDescription);
}
private boolean equalsIgnoreOrder(Collection col1, Collection col2) {
return col1.containsAll(col2) && col2.containsAll(col1);
}
} |
A multi-megabit memory compiler: tomorrow's IP Millions of bits of memory are sometimes required in today's system-on-a-chip designs. The scarcity of large ASIC memories forces designers to build their multi-megabit memories from smaller ones, with a concoction of design and analysis tools. This method can lead to many problems. We have developed a multi-megabit memory compiler that carries the full burden of the design assembly, verification and characterization for the ASIC designers. It saves valuable time and alleviates the risk for ASIC designers. In this paper, we describe the creation of the multi-megabit memory compiler with a set of commercially available EDA (electronic design automation) tools. |
package com.reignstudios.reignnative;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Images.ImageColumns;
import android.util.Log;
public class StreamNative implements ReignActivityCallbacks
{
private static final String logTag = "Reign_Streams";
private static StreamNative singleton;
private static boolean saveImageDone, saveImageSucceeded;
private static boolean loadImageDone, loadImageSucceeded;
public static int LoadImageIntentID = 123, LoadCameraPickerIntent = 124;
private static byte[] loadImageData;
private static Uri cameraImagePath;
public static void Init()
{
singleton = new StreamNative();
ReignAndroidPlugin.AddCallbacks(singleton);
}
public static void SaveImage(final byte[] data, final String title, final String desc)
{
saveImageSucceeded = false;
saveImageDone = false;
ReignAndroidPlugin.RootActivity.runOnUiThread(new Runnable()
{
public void run()
{
try
{
Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length);
//MediaStore.Images.Media.insertImage(ReignAndroidPlugin.RootActivity.getContentResolver(), image, title, desc);
insertImage(ReignAndroidPlugin.RootActivity.getContentResolver(), image, title, desc);// Google implementation saves at 50% quality
saveImageSucceeded = true;
saveImageDone = true;
}
catch (Exception e)
{
Log.d(logTag, "SaveImage Error: " + e.getMessage());
saveImageSucceeded = false;
saveImageDone = true;
}
}
});
}
public static final String insertImage(ContentResolver cr, Bitmap source, String title, String description)
{
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
long date = System.currentTimeMillis();
values.put(Images.Media.DATE_TAKEN, date);
values.put(Images.Media.DATE_ADDED, date / 1000);
Uri url = null;
String stringUrl = null; /* value to be returned */
try
{
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null)
{
OutputStream imageOut = cr.openOutputStream(url);
try
{
source.compress(Bitmap.CompressFormat.JPEG, 100, imageOut);
}
finally
{
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id,
Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
Bitmap microThumb = StoreThumbnail(cr, miniThumb, id, 50F, 50F,
Images.Thumbnails.MICRO_KIND);
}
else
{
Log.e(logTag, "Failed to create thumbnail, removing original");
cr.delete(url, null, null);
url = null;
}
}
catch (Exception e)
{
Log.e(logTag, "Failed to insert image", e);
if (url != null)
{
cr.delete(url, null, null);
url = null;
}
}
if (url != null) stringUrl = url.toString();
return stringUrl;
}
private static final Bitmap StoreThumbnail(ContentResolver cr, Bitmap source, long id, float width, float height, int kind)
{
// create the matrix to scale it
Matrix matrix = new Matrix();
float scaleX = width / source.getWidth();
float scaleY = height / source.getHeight();
matrix.setScale(scaleX, scaleY);
Bitmap thumb = Bitmap.createBitmap(source, 0, 0,
source.getWidth(),
source.getHeight(), matrix,
true);
ContentValues values = new ContentValues(4);
values.put(Images.Thumbnails.KIND, kind);
values.put(Images.Thumbnails.IMAGE_ID, (int)id);
values.put(Images.Thumbnails.HEIGHT, thumb.getHeight());
values.put(Images.Thumbnails.WIDTH, thumb.getWidth());
Uri url = cr.insert(Images.Thumbnails.EXTERNAL_CONTENT_URI, values);
try
{
OutputStream thumbOut = cr.openOutputStream(url);
thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
thumbOut.close();
return thumb;
}
catch (FileNotFoundException ex)
{
return null;
}
catch (IOException ex)
{
return null;
}
}
private static float[] fitInViewIfLarger(float objectWidth, float objectHeight, float viewWidth, float viewHeight)
{
if (objectWidth <= viewWidth && objectHeight <= viewHeight) return new float[]{objectWidth, objectHeight};
float objectSlope = objectHeight / objectWidth;
float viewSlope = viewHeight / viewWidth;
if (objectSlope >= viewSlope) return new float[]{(objectWidth/objectHeight) * viewHeight, viewHeight};
else return new float[]{viewWidth, (objectHeight/objectWidth) * viewWidth};
}
private static int LoadImage_maxWidth, LoadImage_maxHeight;
public static void LoadImage(final int maxWidth, final int maxHeight)
{
loadImageSucceeded = false;
loadImageDone = false;
LoadImage_maxWidth = maxWidth;
LoadImage_maxHeight = maxHeight;
ReignAndroidPlugin.RootActivity.runOnUiThread(new Runnable()
{
public void run()
{
try
{
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
ReignAndroidPlugin.RootActivity.startActivityForResult(photoPickerIntent, LoadImageIntentID);
}
catch (Exception e)
{
Log.d(logTag, "LoadImage Error: " + e.getMessage());
loadImageSucceeded = false;
loadImageDone = true;
}
}
});
}
public static void LoadCameraPicker(final int maxWidth, final int maxHeight)
{
loadImageSucceeded = false;
loadImageDone = false;
LoadImage_maxWidth = maxWidth;
LoadImage_maxHeight = maxHeight;
ReignAndroidPlugin.RootActivity.runOnUiThread(new Runnable()
{
public void run()
{
try
{
// Older devices (Android 2) may need this method! (Don't know how to make that determination though)
/*String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM", "IMG_" + timeStamp + ".jpg");
file.mkdirs();
cameraImagePath = Uri.fromFile(file);
Log.d(logTag, "LoadCameraPicker cameraImagePath: " + cameraImagePath);*/
// get camera image file path
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
ContentValues values = new ContentValues();
String name = "IMG_" + timeStamp + ".jpg";
values.put(MediaStore.Images.Media.TITLE, name);
cameraImagePath = ReignAndroidPlugin.RootActivity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
String path = getRealPathFromURI(cameraImagePath);
Log.d(logTag, "LoadCameraPicker cameraImagePath: " + path);
// invoke camera
Intent photoPickerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImagePath);
ReignAndroidPlugin.RootActivity.startActivityForResult(photoPickerIntent, LoadCameraPickerIntent);
}
catch (Exception e)
{
Log.d(logTag, "LoadCameraPicker Error: " + e.getMessage());
loadImageSucceeded = false;
loadImageDone = true;
}
}
});
}
private static String getRealPathFromURI(Uri contentUri)
{
Cursor cursor = null;
try
{
String[] proj = { MediaStore.Images.Media.DATA };
cursor = ReignAndroidPlugin.RootActivity.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
finally
{
if (cursor != null) cursor.close();
}
}
@Override
public boolean onActivityResult(int requestCode, int resultcode, Intent intent)
{
if (requestCode == LoadImageIntentID)
{
if (resultcode != Activity.RESULT_OK)
{
loadImageSucceeded = false;
loadImageDone = true;
return true;
}
try
{
if (intent != null)
{
Uri data = intent.getData();
if (data == null)
{
Log.d(logTag, "LoadImage onActivityResult Error: Intent was null");
loadImageSucceeded = false;
loadImageDone = true;
return true;
}
Cursor cursor = ReignAndroidPlugin.RootActivity.getContentResolver().query(data, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(ImageColumns.DATA);
String fileName = cursor.getString(idx);
loadImageData = readFile(fileName);
// resize image if needed
if (LoadImage_maxWidth != 0 && LoadImage_maxHeight != 0)
{
Bitmap bmp = BitmapFactory.decodeByteArray(loadImageData, 0, loadImageData.length);
float[] newSize = fitInViewIfLarger(bmp.getWidth(), bmp.getHeight(), LoadImage_maxWidth, LoadImage_maxHeight);
bmp = Bitmap.createScaledBitmap(bmp, (int)newSize[0], (int)newSize[1], true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 95, stream);
loadImageData = stream.toByteArray();
stream.close();
}
loadImageSucceeded = true;
loadImageDone = true;
// REMEMBER for getting pixel data...
//Bitmap bitmapPreview = BitmapFactory.decodeFile(fileName);
//bitmapPreview.copyPixelsToBuffer(dst)// <<< REMEMBER
}
else
{
Log.d(logTag, "LoadImage onActivityResult Error: Intent was null");
loadImageSucceeded = false;
loadImageDone = true;
}
}
catch (Exception e)
{
Log.d(logTag, "LoadImage onActivityResult Error: " + e.getMessage());
loadImageSucceeded = false;
loadImageDone = true;
}
}
else if (requestCode == LoadCameraPickerIntent)
{
if (resultcode != Activity.RESULT_OK)
{
loadImageSucceeded = false;
loadImageDone = true;
return true;
}
try
{
loadImageData = readFile(getRealPathFromURI(cameraImagePath));
// resize image if needed
if (LoadImage_maxWidth != 0 && LoadImage_maxHeight != 0)
{
Bitmap bmp = BitmapFactory.decodeByteArray(loadImageData, 0, loadImageData.length);
float[] newSize = fitInViewIfLarger(bmp.getWidth(), bmp.getHeight(), LoadImage_maxWidth, LoadImage_maxHeight);
bmp = Bitmap.createScaledBitmap(bmp, (int)newSize[0], (int)newSize[1], true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 95, stream);
loadImageData = stream.toByteArray();
stream.close();
}
loadImageSucceeded = true;
loadImageDone = true;
}
catch (Exception e)
{
Log.d(logTag, "LoadCameraPicker onActivityResult Error: " + e.getMessage());
loadImageSucceeded = false;
loadImageDone = true;
}
}
return true;
}
@Override
public void onPause()
{
// do nothing...
}
@Override
public void onResume()
{
// do nothing...
}
private static byte[] readFile(String fileName) throws IOException
{
// Open file
RandomAccessFile f = null;
try
{
f = new RandomAccessFile(fileName, "r");
// Get and check length
long longlength = f.length();
int length = (int)longlength;
if (length != longlength) throw new IOException("File size >= 2 GB");
// Read file and return data
byte[] data = new byte[length];
f.readFully(data);
return data;
}
catch (Exception e)
{
Log.d(logTag, "readFile Error: " + e.getMessage());
return null;
}
finally
{
if (f != null) f.close();
}
}
public static boolean CheckSaveImageDone()
{
Boolean d = saveImageDone;
saveImageDone = false;
return d;
}
public static boolean CheckSaveImageSucceeded()
{
return saveImageSucceeded;
}
public static boolean CheckLoadImageDone()
{
Boolean d = loadImageDone;
loadImageDone = false;
return d;
}
public static boolean CheckLoadImageSucceeded()
{
return loadImageSucceeded;
}
public static byte[] GetLoadedImageData()
{
byte[] data = loadImageData;
loadImageData = null;
return data;
}
}
|
def expected_value(
self,
variables: Iterable[str],
context: Dict[str, Outcome],
intervention: Dict[str, Outcome] = None,
) -> List[float]:
factor = self.query(variables, context, intervention=intervention)
factor.normalize()
ev = np.array([0.0 for _ in factor.variables])
for idx, prob in np.ndenumerate(factor.values):
ev += prob * np.array(
[factor.state_names[variable][idx[var_idx]] for var_idx, variable in enumerate(factor.variables)]
)
if np.isnan(ev).any():
raise RuntimeError(
"query {} | {} generated Nan from idx: {}, prob: {}, \
consider imputing a random decision".format(
variables, context, idx, prob
)
)
return ev.tolist() |
// GetPreferredAudioPlaybackDeviceId
//
// Determine the preferred audio playback device as a wave out device ID.
// If the registry has been set, use that setting;
// otherwise, use the first mappable device
//
static int GetPreferredAudioPlaybackDeviceId()
{
int id = GetPreferredAudioDeviceReg();
if (id != -1)
{
return id;
}
return GetFirstMappableDevice();
} |
package com.goldcat.soulbreaker;
import org.cocos2d.layers.CCColorLayer;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.opengl.CCBitmapFontAtlas;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor3B;
import org.cocos2d.types.ccColor4B;
import android.view.MotionEvent;
public class RankLayer extends CCColorLayer {
public static CCScene scene() {
CCScene scene = CCScene.node();
CCLayer layer = new RankLayer(ccColor4B.ccc4( 255, 255, 255, 255));
scene.addChild(layer);
scene.setUserData("RankLayer");
return scene;
}
CGSize winSize = CCDirector.sharedDirector().displaySize();
float scaleX = SB_Util.GetScaleX();
float scaleY = SB_Util.GetScaleY();
public RankLayer(ccColor4B color) {
super(color);
this.setIsTouchEnabled(true);
CCBitmapFontAtlas rank = CCBitmapFontAtlas.bitmapFontAtlas("Rank", "madokaletters.fnt");
rank.setScaleX(scaleX); rank.setScaleY(scaleY);
rank.setColor(ccColor3B.ccBLACK);
rank.setPosition(winSize.getWidth()/2.0f, winSize.getHeight()/2.0f);
addChild(rank);
}
@Override
public boolean ccTouchesBegan(MotionEvent event) {
SB_Util.ReplaceScene(TitleLayer.scene(SB_Constants.TITLE_MENU_EXIT));
return true;
}
}
|
MARTYN WAGHORN grabbed the winner as in-form Wigan continued their march up the table with a stirring comeback.
The Latics fell behind against the run of play when Lewis McGugan rifled a shot beyond Ali Al Habsi on 36 minutes.
But the hosts levelled when Jean Beausejour nodded in at the second attempt.
And Waghorn completed the turnaround on 57 minutes when he took advantage of James McArthur’s miss-hit shot to slot into the far corner.
Wigan boss Uwe Rosler said: “We had the majority of the possession and far more attempts than them, so we deserved it.
Wigan had seen their eight-match winning run end in midweek but there was no sign of a hangover.
First, Beausejour saw his low shot blocked by the advancing Manuel Almunia before Ivan Ramis’ bullet header was blocked on the line.
McClean then missed a sitter inside the six-yard box and had a fierce attempt blocked.
The Hornets offered little on the counter but stole in front when McGugan flashed a low shot into the far corner.
The lead lasted four minutes as Beausejour headed in the rebound after Almunia had kept his first effort out.
Wigan deservedly grabbed the lead just shy of the hour.
McArthur miscued with a drive from the edge of the area, allowing Waghorn to intercept and steer in his sixth of the season.
Jordi Gomez then came close to extending the advantage when his rasping shot flew over.
Watford rallied but their winless run on the road now stretches to 14 matches. |
Sedentary behaviour levels in adults with an intellectual disability: a systematic review and meta-analysis. Background: Sedentary behaviour (SB), which is characterised by low levels of energy expenditure, has been linked to increased cardio-metabolic risks, obesity and mortality, as well as cancer risk. No firm guidelines are established on safe levels of SB. Adults with an intellectual disability (ID) have poorer health than their counterparts in the general population with higher rates of multi-morbidity, inactivity, and obesity. The reasons for this health disparity are unclear however it is known that SB and overall inactivity contribute to poorer health. There is no clear picture of the levels of SB among individuals with ID therefore SB levels in this vulnerable population need to be examined. The aim of this systematic review is to investigate the prevalence of sedentary behaviour in adults with an ID. Methods: The PRISMA-P framework was applied to identify high quality articles. An extensive search was carried out in four databases and grey literature sources. In total, 1,972 articles were retrieved of which 48 articles went forward for full review after duplicate removal and screening by title and abstract. The National Institute of Health's quality assessment tools were used to assess article quality. Two reviewers independently assessed each article. An excel spreadsheet was created to guide the data extraction process. The final review included 25 articles. A meta-analysis was completed using REVMAN. Results: Different SB assessment types were identified in studies. These included steps, time, questionnaires, and screen time. Studies were heterogeneous. Observed daily steps per individual ranged from 44 to above 30,000, with an average of approximately 6,500 steps. Mean daily time spent in SBs was more than 60% of available time, with observed screen time of more than 3 hours. Conclusion: There is a high prevalence of SB in adults with an intellectual disability. . |
// LoadNodeKey loads NodeKey located in filePath.
func LoadNodeKey(filePath string) (NodeKey, error) {
jsonBytes, err := ioutil.ReadFile(filePath)
if err != nil {
return NodeKey{}, err
}
nodeKey := NodeKey{}
err = tmjson.Unmarshal(jsonBytes, &nodeKey)
if err != nil {
return NodeKey{}, err
}
nodeKey.ID = NodeIDFromPubKey(nodeKey.PubKey())
return nodeKey, nil
} |
Sparking Creativity: Composition in Middle School General Music Middle school students are old enough to be capable of abstract thought and critical thinking while still being playful and joyfully goofy! Through music composition in general music classes, middle school students can be challenged to make musical decisions. Composition can be especially exciting in middle school because they will be motivated to think critically through music that is relevant to their lives. Composition activities also afford teachers the flexibility to adapt to various learning levels and styles in our classroom. In this article, I will offer concrete ideas for composing in middle school general music, including thoughts on notation and assessment. |
D-Dimer Is a Predictive Factor of Cancer Therapeutics-Related Cardiac Dysfunction in Patients Treated With Cardiotoxic Chemotherapy Background D-dimer is a sensitive biomarker for cancer-associated thrombosis, but little is known about its significance on cancer therapeutics-related cardiac dysfunction (CTRCD). Methods Consecutive 169 patients planned for cardiotoxic chemotherapy were enrolled and followed up for 12 months. All patients underwent echocardiography and blood test at baseline and at 3-, 6-, and 12 months. Results The patients were divided into two groups based on the level of D-dimer (>1.65 g/ml or ≦ 1.65 g/ml) at baseline before chemotherapy: high D-dimer group (n = 37) and low D-dimer group (n = 132). Left ventricular ejection fraction (LVEF) decreased at 3- and 6 months after chemotherapy in high D-dimer group , but no change was observed in low D-dimer group. The occurrence of CTRCD within the 12-month follow-up period was higher in the high D-dimer group than in the low D-dimer group (16.2 vs. 4.5%, p = 0.0146). Multivariable logistic regression analysis revealed that high D-dimer level at baseline was an independent predictor of the development of CTRCD . Conclusion We should pay more attention to elevated D-dimer levels not only as a sign of cancer-associated thrombosis but also the future occurrence of CTRCD. INTRODUCTION Recent advances in the diagnosis and treatment of cancers improve its prognosis. However, anticancer drugs, namely, anthracyclines, monoclonal antibodies, tyrosine kinase inhibitors, etc., induce cardiac dysfunction, resulting in poor prognosis in cancer survivors. Several cardiac biomarkers and echocardiographic parameters, such as troponins, myeloperoxidase, interleukin-1 (IL-1), Nucleotide-binding domain-like receptor family pyrin domain containing 3, and reduced global longitudinal strain, are proposed to detect the early phase of cancer therapeutics-related cardiac dysfunction (CTRCD) and prompt cardioprotective treatment can improve cardiac function. Although those parameters are useful, careful monitoring is required for all patients to detect early signs of CTRCD. Thus, a novel biomarker that identifies high-risk patients before chemotherapy is desirable to perform effective clinical monitoring. D-dimer is a sensitive biomarker for cancer-associated thrombosis, but accumulating evidence suggests that pretreatment D-dimer can be used as a prognostic biomarker for patients with solid tumors. In cardiovascular fields, elevated D-dimer is associated with not only thromboembolic events but also heart failure mortality in heart failure patients with reduced and preserved ejection fraction (EF). Although D-dimer is a promising biomarker in the cardiooncology field, little is known about the relationship between D-dimer and CTRCD. The present study aimed to evaluate the predictive impact of D-dimer before chemotherapy on the development of CTRCD. Study Subjects and Protocol We enrolled 202 consecutive cancer patients, planned for cardiotoxic chemotherapy, such as anthracyclines, human epidermal growth factor receptor 2 (HER2) inhibitors, tyrosine kinase inhibitors, and proteasome inhibitors, at Fukushima Medical University hospital from November 2016 to March 2019 (Figure 1). Patients were excluded if they died or were transferred to other hospitals within 12 months follow-up period (n = 33). The remaining 169 patients were divided into two groups based on the cut-off value of D-dimer, which was defined by the receiver operator characteristic curve analysis to detect the occurrence of CTRCD (Figure 2). Hypertension was defined as a history of use of an antihypertensive drug or systolic blood pressure of ≥140 mmHg and/or diastolic blood pressure ≥90 mmHg. Diabetes was defined as recent use of insulin treatment or hypoglycemic drug or hemoglobin A1c ≥6.5%. Dyslipidemia was defined as a history of use of cholesterol-lowering drugs, or triglyceride was ≥150 mg/dl, low-density lipoprotein cholesterol was ≥140 mg/dl, and/or high-density lipoprotein cholesterol was ≤40 mg/dl. A cumulative dose of anthracycline was expressed as a doxorubicin equivalent. HER2 inhibitors included trastuzumab and pertuzumab. Tyrosine kinase inhibitors included dabrafenib, trametinib, lenvatinib, sorafenib, dasatinib, bevacizumab, and pazopanib. Proteasome inhibitors included carfilzomib and bortezomib. Radiation therapy was defined as irradiation to the mediastinum and/or the heart field within the follow-up period. Transthoracic echocardiography and blood sampling test were performed at baseline as well as at 3, 6, and 12 months after the administration of cardiotoxic chemotherapy. All procedures used in this research were approved by the Ethical Committee of Fukushima Medical University. Echocardiography Transthoracic echocardiography was performed by a trained sonographer, and images were checked by another trained sonographer and an echo-cardiologist. We measured cardiac function using EPIQ 7G (Philips Healthtech, Best, The Netherlands). Left ventricular (LV) EF was calculated using the modified Simpson's method according to the guideline from the American Society of Echocardiography and the European Association of Cardiovascular Imaging. The LV mass was calculated using the following formula: Cancer therapeutics-related cardiac dysfunction was defined as a decrease in EF by more than 10% points, to a value <53%. The LV end-diastolic volume index, LV end-systolic volume index, LV mass index, and left atrial volume index were measured using the B-mode ultrasound. Blood Sampling High sensitivity cardiac troponin I (TnI) was measured using an assay based on Luminescent Oxygen Channeling Immunoassay technology and run on a Dimension EXL Integrated Chemistry System (Siemens Healthcare Diagnostics, Deerfield, IL, USA). B-type natriuretic peptide (BNP) levels were measured using a specific immunoradiometric assay (Shionoria BNP kit, Shionogi, Osaka, Japan). D-dimer was measured using a latex agglutination method (Lias Auto D-dimer Neo, Sysmex, Kobe, Japan). Statistical Analysis All statistical analyses were performed using Prism 9 (GraphPad Software, San Diego, CA, USA) or R software packages version 3.6.3 (R core team 2020, Vienna, Austria). We used the Shapiro-Wilk test to discriminate which variables were normally or not normally distributed. Normally distributed variables were shown as mean ± SD. Non-normally distributed variables were indicated by a median with interquartile range. Category variables were shown in numbers and percentages. Student's ttest was used for variables following a normal distribution, the Mann-Whitney U-test was used for variables of the non-normal distribution, and the chi-square test was used for categorical variables. The time course of EF (baseline, 3-, 6-, and 12 months after the administration of anthracyclines) was evaluated using the Friedman test. Logistic regression analysis was performed to identify the variables to predict the occurrence of CTRCD. We selected variables relating to the general condition and cardiac function, i.e., age, echocardiographic parameters, use of anthracyclines, BNP, hemoglobin, estimated glomerular filtration ratio, and the elevation of D-dimer. The variables presenting p < 0.05 in the univariable analysis were entered into the multivariable analysis. A receiver operating characteristic curve analysis was performed to determine the optimal cut-off value of the D-dimer for predicting the occurrence of CTRCD. The p of 0.05 or less was defined as significant. RESULTS First, we performed a receiver operating characteristic curve analysis to identify the threshold level of D-dimer to predict the occurrence of CTRCD (Figure 2). A total of 12 patients suffered from CTRCD within 12 months follow-up period. When we set the cut-off value of D-dimer at 1.65 g/ml, sensitivity, specificity, and area under the curve to predict CTRCD were 50.0%, 80.3%, and 0.661, respectively. Then, we divided the patients into two groups based on the cut-off value. Table 1 shows patient characteristics at the baseline before chemotherapy. There were no statistical differences in age, sex, and the usage of angiotensinconverting enzyme inhibitors/angiotensin II receptor blockers and -blockers. The high D-dimer group included a lower rate of breast cancer (35 vs. 67%, p = 0.0005), a higher rate of ovarian/uterine cancer (19 vs. 6%, p = 0.0151), and a higher rate of leukemia (16 vs. 4%, p = 0.0068) than low D-dimer group. Echocardiographic data demonstrated that EF was slightly higher in the high D-dimer group (67 ± 5 vs. 64 ± 5%, p = 0.0019). In laboratory data, the high D-dimer group showed lower hemoglobin values and higher BNP values. DISCUSSION In the present study, we revealed the predictive features of D-dimer in patients treated with cardiotoxic agents. First, the threshold level of D-dimer was 1.65 g/ml to predict the development of CTRCD. Second, EF was decreased time-dependently in high D-dimer patients. Third, the occurrence of CTRCD was significantly higher in high D-dimer patients. D-dimer is a pivotal biomarker of hypercoagulability and thrombosis. Fibrin-bound plasmin degrades the fibrin network into soluble fragments D-dimers and E fragments, thus increased levels of D-dimer represent a global activation of coagulation and fibrinolysis. Cancers produce hypercoagulable and prothrombotic situations by secreting several prothromboembolic factors, such as mucins, cysteine protease, and tissue factors. Therefore, thrombi are easily generated in patients with cancer, and thromboembolism is the second leading cause of cancer-related morbidity and mortality. Although D-dimer is an established and widely used biomarker for the screening of thrombus formation in patients with cancer, prognostic features of D-dimer have become clinically overt recently. The link between D-dimer and cancer progression is reported in several papers, and higher levels of D-dimer are associated with poor prognosis in cancer patients. Although the precise mechanisms are still complex and uncovered, the pro-coagulable state may produce a suitable milieu for cancer progression by recruitment of pro-metastatic leukocytes, adhesion to the endothelium, transendothelial migration, and restriction in natural killer cell-mediated clearance of micrometastasis. Accumulating evidence showed that abnormal inflammation and oxidative stress are key factors to the development of heart failure, and these also play important roles in cancer progression and thrombus formation. For example, IL-1, a representative inflammatory cytokine, induces cardiac dysfunction and thrombus formation. IL-1 activates myddosome complex, such as nuclear factor B, myeloid differentiation factor 88, cryopyrin, and p38-MAPK, in cardiomyocytes, leading to dysregulates metabolism in the sarcoplasmic reticulum, calcium homeostasis, and myocardial apoptosis and necrosis. In addition, IL-1 increased pro-coagulant state through activating tissue factor-dependent mechanisms in endothelial cells. Gomes et al. reported that blockade of IL-1 receptor abolished the neutrophil extracellular traps-dependent prothrombotic state and attenuated cancer-associated thrombosis in murine breast cancer model. Considering the fact that inflammation is a major contributor to cardiac dysfunction and thrombus formation, cancer patients with high D-dimer may be predisposed to cardiac dysfunction due to a chronic inflammatory state. Cardiotoxic chemotherapeutic agents are crucial and indispensable to performing cancer treatment. Anthracyclines induce pro-inflammatory responses by increasing tumor necrosis factor (TNF-), IL-1, and IL-6, leading to tumor cell death. Not only anthracyclines but also targeted chemotherapy, such as trastuzumab and bevacizumab, increased inflammatory cytokines after the treatment. In the present study, the patients with a high D-dimer group may already have been exposed to an inflammatory state before chemotherapy and were vulnerable to additional inflammatory stress by cardiotoxic agents, resulting in the development of CTRCD. To elucidate the precise mechanisms was beyond this study, but the importance of D-dimer should be noted in the cardio-oncology field. Intervention with Pravastatin in Ischemic Disease (LIPID) study revealed that elevated D-dimer levels predict long-term risk of arterial and venous events, cardiovascular disease mortality, in addition to that, increased cancer incidence and mortality rate. To the best of our knowledge, this is the first report assessing the relationship between D-dimer levels and the development of CTRCD. The importance of D-dimer should be taken into account when managing patients with cancer who are treated with cardiotoxic chemotherapy. LIMITATION This study has several limitations. First, this study was performed using a relatively small number of patients and a short followup period by a single center. Slight differences in EF at baseline may be due to the small sample size of the high D-dimer group. Second, although not statistically significant, a higher proportion of patients in the high D-dimer group received anthracycline-containing chemotherapies. This might affect the results in the reduction in EF in the high D-dimer group. Longer follow-up and larger population data were needed to confirm the importance of D-dimer to the development of CTRCD and cardiovascular prognosis. Third, D-dimer has modest sensitivity and specificity to predict CTRCD in the present study. The mechanisms by which CTRCD development must be complicated, thereby predicting CTRCD by a single biomarker is still challenging. D-dimer is frequently analyzed in daily clinical practice to detect cancer-associated thrombosis. Therefore, we think D-dimer is easy and useful for predicting both CTRCD and thrombus formation. CONCLUSION Elevated D-dimer is a pivotal biomarker to predict CTRCD. D-dimer should be taken into account when managing cancer patients treated with cardiotoxic chemotherapy. DATA AVAILABILITY STATEMENT The raw data supporting the conclusions of this article will be made available by the authors, without undue reservation. ETHICS STATEMENT The studies involving human participants were reviewed and approved by Ethical Committee of Fukushima Medical University Hospital. The patients/participants provided their written informed consent to participate in this study. AUTHOR CONTRIBUTIONS MO created the study design, analyzed the data, and drafted the manuscript. DY created the study design and analyzed the data. TM, TS, TK, and AK acquired the data. AY, KN, TI, and YT interpreted the data and revised the manuscript. All authors contributed to the conception, design, critical revision, and final approval of this manuscript. |
The effect of drip irrigation on the formation of the root system of raspberry seedlings in the conditions of the Non-black soil zone of Russia Relevance. Currently, there is an acute problem of meeting the growing demand for berry and fruit products. One of the ways to intensify agricultural production in the field of horticulture and crop production is to increase the efficiency of environmental management through the use of resource-saving technologies. One of these technologies is drip irrigation, which improves the quality of crop production.Materials and methods. Field studies were carried out on the territory of the educational and experimental farm of the laboratory "Michurinsky Garden" of the Russian State Agrarian University Moscow Timiryazev Agricultural Academy. The experiment was established in the fall of 2018 and is a two-factor study of various levels of moisture on the growth and development of raspberry seedlings. The first factor included options for maintaining soil moisture in the range: 1) control (without irrigation); 2) not less than 60% of the lowest moisture capacity; 3) not less than 70% of the lowest moisture capacity; 4) not less than 80% of the lowest moisture capacity. The second factor was the raspberry varieties Solnyshko and Nagrada.Results. Constructed moisture contours according to the study options showed that drip irrigation contributes to the optimum moisture concentration in the soil for seedlings. The most developed root system in comparison with the control was obtained on irrigated variants with maintaining a moisture content of at least 70 and 80% of the lowest moisture capacity. Here, the maximum values of the volume of the root system, the number of roots, and the average length of the root were obtained. It was revealed that in variants with irrigation, the root system of seedlings spreads in the upper layer (mainly 5-15 cm). |
North Korea continues to issue threats as combined military exercises continue.
The first joint US-South Korean military exercises began last month in an operation code-named "Invincible Spirit".
About 8,000 US and South Korean troops, 20 ships and submarines and 200 aircraft took part in the drill, which the US and South Korea have said is aimed at curbing the North's "aggressive" behaviour.
The sinking of the Cheonan frigate in March with the loss of 46 South Korean sailors raised tensions across the Korean peninsula, with a multinational inquiry determining that it was caused by a North Korean torpedo.
The North has vehemently denied it was involved in the sinking and threatened retaliation for this week's military exercises, which it branded preparations for a full-scale "military invasion".
The Korean peninsula remains in a technical state of war because the Korean War ended in a truce, not a peace treaty. |
/*
* Copyright (C) 2020-present the original author or authors.
*
* 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 org.javaloong.kongmink.petclinic.vets;
import org.javaloong.kongmink.pf4j.spring.boot.SharedDataSourceSpringBootstrap;
import org.javaloong.kongmink.pf4j.spring.boot.SpringBootPlugin;
import org.javaloong.kongmink.pf4j.spring.boot.SpringBootstrap;
import org.pf4j.PluginWrapper;
/**
* @author <NAME>
*/
public class VetPlugin extends SpringBootPlugin {
public VetPlugin(PluginWrapper wrapper) {
super(wrapper);
}
@Override
protected SpringBootstrap createSpringBootstrap() {
return new SharedDataSourceSpringBootstrap(this, VetPluginStarter.class);
}
}
|
<reponame>rakovpublic/algebraphysicsflows<gh_stars>1-10
package operations.simple;
import algebra.IAlgebraItem;
import operations.IAbsOperation;
import java.io.Serializable;
/**
* Created by <NAME> on 28.03.2017.
*/
public interface ITransferOperation<K> extends Serializable, IAbsOperation {
/**
* transfer element from one algebra to other
*
* @param input
* @return IAlgebraItem parametrized V
* @see IAlgebraItem
*/
<V> IAlgebraItem<V> performOperation(K input);
}
|
import requests
import base64
from json.decoder import JSONDecodeError
def main():
'''
通用文字识别测试
'''
source = {"http://127.0.0.1:8000/ocr/general_basic/": "case1.jpeg",
"http://127.0.0.1:8000/ocr/accurate_basic/": "case1.jpeg",
"http://127.0.0.1:8000/ocr/general/": "case1.jpeg",
"http://127.0.0.1:8000/ocr/accurate/": "case1.jpeg",
"http://127.0.0.1:8000/ocr/general_enhanced/": "case1.jpeg",
}
for request_url, img_path in source.items():
f = open(img_path, 'rb')
image = base64.b64encode(f.read())
params = {"image": image}
response = requests.post(url=request_url, data=params)
try:
if response.json().get("result"):
print(response.json()["result"])
else:
print(response.json())
except JSONDecodeError:
print(response.content)
if __name__ == '__main__':
main()
|
# !/usr/bin/env python
# -*- coding:utf-8 -*-
from pylab import *
from numpy import *
from minoritygame import *
fig = figure(1, figsize=(6,4))
N = 101
syms = ['ro-','gs-','bd-']
s = [2, 4, 6]
for i in range(len(s)):
Y = []
X = []
for m in range(1, 15):
x = []
y = []
for t in range(10):
sim = World(T=200, N=N, m=m, s=s[i])
sim.act()
x.append(float(2**m)/float(N))
y.append(var(sim.D)/float(N))
X.append(mean(x))
Y.append(mean(y))
print('m='+str(m))
plot(X, Y, syms[i], label='s='+str(s[i]))
print('s='+str(s[i]))
xscale('log')
yscale('log')
xlabel(r'$2^{m}/N$')
ylabel(r'$\sigma^2/N$')
legend(loc='best')
fig.set_tight_layout(True)
savefig('variance-vs-m.png', format='png', bbox_inches='tight')
fig.clf()
|
The outcry over child separation has revealed a disturbing bigger picture. America’s immigration enforcement system is a complex patchwork involving multiple federal agencies, local sheriffs, nonprofits and, increasingly, politically influential corporations like Florida-based GEO Group.
Your browser does not support the iframe HTML tag. Try viewing this in a modern browser like Chrome, Safari, Firefox or Internet Explorer 9 or later.
The system exists in a bureaucratic netherworld. Neither Scott’s office nor the Department of Children and Families provided a complete list of federal immigration facilities in Florida, because they said the immigrants are not in the state system.
Yet getting federal officials to provide details about the system is difficult — and made more so by outsourcing. Most requests for information must go through a formal process that takes months or even years.
Florida’s key role in the national detention system wasn’t publicly known until news broke in mid-June that more than 1,000 children were housed in a dorm-like former job training center in Homestead, including at least 70 kids who were taken from their families.
Politicians, mainly Democrats, rushed to the shelters and demanded action. Others, including the Republican governor, said they opposed child separation but have not taken much action, seeming to underscore the treacherous politics of immigration in an election year.
Part of the challenge in understanding the system is how scattered it has become, with two different tracks for children and adults and various layers to each.
Children from poverty and violence-torn Guatemala, Honduras and El Salvador began to flood the border in 2014, mostly unaccompanied by adults. President Barack Obama’s administration sent them to shelters across the country to be cared for while a family member or sponsor in the U.S. could be located.
Trump added a new and explosive factor, by splitting children who arrived with adults — a hardball tactic to deter other immigrants from making the dangerous journey across the border.
Undocumented children are overseen by a federal HHS division called the Office of Refugee Resettlement. Care can be outsourced, either to nonprofits or for-profit companies such as Comprehensive Health Services of Cape Canaveral, which runs the Homestead shelter under a contract worth more than $30 million.
Many more undocumented adults are apprehended at the border, picked up after traffic stops or for committing a crime or simply swept up in raids across the country, which have grown more frequent since Trump took office.
Some are held in county jails in Florida in such far-flung places as Crawfordville, Macclenny, Naples and the Keys, making it difficult for families to reach them.
Florida saw the largest percentage increase of immigration arrests in the country in 2017, according to a Pew Research Center report. These adults are processed through the Immigration and Customs Enforcement, or ICE, a division of Homeland Security.
ICE has several detention centers in Florida, but only one is directly operated by the agency: Krome Service Processing Center, a 600-bed facility in Miami-Dade that used to be a Cold War missile base. The biggest, 700-bed Broward Transitional Center in Pompano Beach, is run by The GEO Group, which has immigration contracts across the country in addition to running numerous private prisons, including five in Florida.
The pink-painted Broward facility, which GEO operates on a contract of more than $20 million annually, has been a magnet for controversy in recent years as it has handled hundreds of people subjected to long stays despite being detained for minor offenses.
In 2012, a detainee from Argentina went on hunger strike. Americans for Immigrant Justice, a Miami group that provides support to undocumented immigrants, produced a report three years ago that said detainees were sexually assaulted, denied legal assistance and given substandard medical care.
Paez referred a request for contracts, inspection reports and audits to ICE. That agency, in turn, said the Times must request them under the Freedom of Information Act, a process that can take months or longer.
ICE standards vary by location and can be advisory in nature, experts say, and even material that is made public may not include all details as the private groups assert commercial trade secret protections.
Other ICE detention centers are contracted through a handful of county sheriffs who rent space in jails. Those counties include Baker, near Jacksonville; Glades, on the rim of Lake Okeechobee; Collier, in southwest Florida; Monroe, in the Keys; Wakulla, south of Tallahassee; and Pinellas in Tampa Bay, which generally houses 50 to 60 detainees a day and is paid $80 per day for each.
But it’s wrong for immigrants to be housed in jails with people accused of criminal violations, argued Jessica Shulruff Schneider, an attorney and director of detention for Americans for Immigrant Justice.
Still, many Americans agree with a tougher approach that Trump made a centerpiece of his campaign.
Critics say this is costly and ineffective. U.S. Rep. Ted Deutch, D-Boca Raton, points to a Congressionally-directed mandate to fund 34,000 detention beds per day, a quota no other law enforcement agency faces. An alternative to the $2 billion annual detention cost, Deutch said, is to require the use of GPS ankle bracelets and other less costly monitoring measures while immigrants await court hearings.
“Are we including these provisions in the appropriations bill to ensure undocumented immigrants show up for proceedings or is it for a guaranteed funding source for private contractors?” Deutch said in an interview.
Nationally, about 70 percent of detainees are in privately run facilities — and that could grow. Last week the Trump administration said it was looking to add 15,000 beds for family detention, a potential boon to GEO Group and CoreCivic, a private prison operator formerly known as Corrections Corporation of America.
Both have become heavy players in the political process, donating to candidates, largely Republicans, and spending millions on influencing policy; among the lobbyists it employs is Florida resident Brian Ballard, who is close to Trump.
Trump has reversed the child separation policy but the job of reuniting more than 2,000 kids with their parents remains outstanding and protests continue. HHS has launched a review of shelters and training of contractors, overseeing 12,000 migrant children overall.
Tampa Bay Times staff writers Kirby Wilson and Langston Taylor contributed to this report.
Sen. Joe Gruters’ bill would prohibit ‘sanctuary cities’ in Florida and require state and local law enforcement to comply with U.S. Immigration and Customs Enforcement, or ICE.
Did Trump administration break law by blocking Florida reps from entering migrant shelter? |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import React from 'react';
import { shallow } from 'enzyme';
import { EuiSelect } from '@elastic/eui';
import { SortingView } from '.';
describe('SortingView', () => {
beforeEach(() => {
jest.clearAllMocks();
});
const props = {
options: [{ label: 'Label', value: 'Value' }],
value: 'Value',
onChange: jest.fn(),
};
it('renders', () => {
const wrapper = shallow(<SortingView {...props} />);
expect(wrapper.find(EuiSelect).length).toBe(1);
});
it('maps options to correct EuiSelect option', () => {
const wrapper = shallow(<SortingView {...props} />);
expect(wrapper.find(EuiSelect).prop('options')).toEqual([{ text: 'Label', value: 'Value' }]);
});
it('passes through the value if it exists in options', () => {
const wrapper = shallow(<SortingView {...props} />);
expect(wrapper.find(EuiSelect).prop('value')).toEqual('Value');
});
it('does not pass through the value if it does not exist in options', () => {
const wrapper = shallow(
<SortingView
{...{
...props,
value: 'This value is not in Options',
}}
/>
);
expect(wrapper.find(EuiSelect).prop('value')).toBeUndefined();
});
it('passes through an onChange to EuiSelect', () => {
const wrapper = shallow(<SortingView {...props} />);
const onChange: any = wrapper.find(EuiSelect).prop('onChange');
onChange({ target: { value: 'test' } });
expect(props.onChange).toHaveBeenCalledWith('test');
});
});
|
Snap will report its second quarterly results as a public company late Thursday.
Snap Inc. (SNAP - Get Report) will have a lot to prove when it reports second-quarter results after Thursday's closing bell.
Investors will be laser focused on whether the newly public social media company can demonstrate user growth, narrowing losses and momentum in its advertising business. On top of that, Snap also faces pressure to show that it's successfully fending off competition from Facebook Inc. (FB - Get Report) , which has mimicked feature after feature from its younger social media rival.
TheStreet is hosting a live blog analyzing Snap's second-quarter earnings report on Tuesday afternoon. Please go here to check it out.
Wall Street expects Snap to report a loss of 30 cents per share on roughly $186 million in sales. Daily active users are expected to increase modestly to 174 million, compared to the 166 million it had during the previous quarter. That number still pales in comparison to the 250 million daily users on Facebook's Instagram Stories -- its copycat version of Snapchat Stories, which allows users to post videos or images that disappear after 24 hours. Instagram Stories is also growing at a much faster clip than Snapchat Stories, adding 100 million new DAUs since January.
But some have begun to acknowledge that Snap isn't going to grow as fast as Facebook or Instagram. Snap CEO Evan Spiegel's user strategy seems to indicate this. On the company's first-quarter earnings call, Spiegel and other executives said Snap isn't concerned with entering developing markets right now; instead, Snap is focusing on core geographies like North America and Europe, where engagement has proven to be consistently high.
Will the Plant-Based 'Impossible Burger' Get FDA Approval?
If user growth is going to chug along at a relatively slow pace, Snap will have to show investors that it can squeeze as much money as possible out of its existing user base. That's where the average revenue per user metric will come into focus. Analysts are looking for ARPU to jump to $1.07 per user, up from 90 cents during the previous quarter. Monness, Crespi, Hardt analyst James Cakmak contends that Thursday's results will be a "make or break quarter" for Snap, but that it can help save itself by demonstrating significant upside to ARPU.
"We've defended Snap since day one, but now need to see monetization moving in the right direction while delivering outsized gains in the gross margin," Cakmak wrote in a note to investors. "In contrast with Facebook, we are less concerned on the absolute growth in users and focus more on the extracted value (ARPU) given the prioritization of affluent markets."
Cakmak is among a small group of investors who still have a Buy rating on shares of Snap. Among 33 analysts surveyed by FactSet, only nine maintain a Buy rating on Snap, while 16 have Hold ratings and six have given it a Sell or the equivalent of a Sell rating. Wall Street has turned increasingly bearish on Snap in the months since its IPO, as the stock has tumbled 44.5% year to date.
Several analysts noted that they might be more confident in the company if Snap gave some clues about what it's working on and how the next couple of quarters might be shaping up for them. Spiegel continues to remain opaque about Snap's product pipeline, saying on the latest earnings call that the company loves to "surprise our community" and that it should be a "fun rest of the year." Cakmak said he hopes the company will consider giving some guidance when it reports on Thursday.
FBN Securities analyst Shebly Seyrafi said he wants greater visibility into Snap's product pipeline, especially as some near term headwinds remain, including Snap's 180-day lockup period expiration and the possibility that it may be excluded from a third major index provider.
"We need to see that they have enough stuff in their product pipeline that they can further support the company," Seyrafi said. "Those kinds of product launches [like Snap Maps], if they're substantial enough, then they could drive user growth."
What it comes down to, ultimately, is that Snap needs to restore some confidence among investors that it's not going to fade into irrelevancy like Twitter Inc. (TWTR - Get Report) or end up an acquisition target -- something that Seyrafi said he's not ruling out just yet, lest Snap show some positive momentum from its gloomy post-IPO performance.
"I think they're a highly innovative company, I like the company, but I just can't make sense of the current stock price," Seyrafi added.
At the time of publication, Action Alerts PLUS, which Jim Cramer co-manages as a charitable trust, was long FB. |
Towards a New Definition of Social Innovation This chapter focuses on social innovation, a topic that the literature has been increasingly discussing in the last decade. The authors revise the many available (and, to some extent, too general) definitions as well as identify the main features that have been claimed as relevant for social innovation (e.g. Mumford, 2002), which concur in providing its definition. By doing so, they pursue the assessment of a less fuzzy definition of social innovation and make a first attempt to focus on the role that companies play in developing as well as scaling social innovations. The adopted approach exploits the literature review and is based on an in-depth analysis of the definitions of social innovation: the authors collected and catalogued them, so identifying the main dimensions of analysis. Clarifying what social innovation is and the role that companies play in social innovation initiatives can increase companies awareness of what they (can) do with respect to social innovation, possibly taking advantage of this in terms of business objectives. |
Let the gun debate play out over the long term. In the meantime let's act on what we agree on: hardening school security to keep our children safe.
The responsibility to protect our children in schools across America is something that requires the voice of every citizen. We can't do it alone, and we can't accomplish this task with political warfare occurring between us.
We can't let disagreement in the halls of our state legislatures, Congress, school boards, sidewalks or local communities divide us and prevent us from getting done the reforms we know we can agree on. We can fix the weaknesses in our schools' security with practical changes in the short term, while the more contentious issues surrounding firearm policy play out over the long term. There are basic, important and life-protecting policies we can enact right now to fix the problem of violence in our schools.
Americans for Children's Lives and School Safety has produced an eight-point plan to protect our children and our schools, and it revolves around basic security principles. If enacted, our recommendations would elevate our school safety to the same level as sports arenas, government buildings, courthouses and military bases. We currently protect our adults, protect our politicians and protect our public buildings, and it is imperative we protect our children using comparable security protocols.
The leading co-author of this piece suffered the loss of his wonderful daughter, Meadow Pollack, in the shooting at Marjory Stoneman Douglas High School in Parkland, Florida, on Feb. 14. This tragedy has inspired a national movement to fix school safety — a mission that is critical and will not end until real reform is enacted to ensure that the next threat to our children is neutralized.
The Americans for CLASS' eight-point plan focuses on perimeter security, controlling human building entry frequency, protecting the interior, developing a school safety volunteer network, including parent input, appointing clear leadership, increasing support for mental health, and launching a safety hotline. These are steps we can take today, and we need to get them done.
Perimeter security includes cameras and monitoring technologies, coupled with single or limited points of entry, to manage the human flow of entrance, reducing potential risks to our kids. Further, we must place armed guards inside our schools and harden the target. School resource officers who are well trained and medically fit would be instrumental in defending our children in the event of an attack.
We simply must not accept the argument that federal legislation and good wishes will stop those who wish to do us harm, regardless of the type of weapon that might be used in an attack. We must protect our kids. Armed guards are perhaps the most critical component, and we cannot back down on this part of the plan. Without these guards, it doesn't work.
We should look to our seasoned military veterans to fill these positions. They have unique experience with weapons safety and deserve consideration for jobs that will be needed under this initiative.
The final components involve a sound and coherent parental communication network led by a school safety officer who can manage any emergency response efforts, and concurrently, keep parents informed of security efforts. Developing a school safety hotline and increasing funding for mental health will be critical as well.
It will take dedication, hard work and consistent community effort to come together and agree on basic safety measures, notwithstanding the ongoing (and often distracting) debate about guns, extraneous factors or political messaging that come with that debate.
These policy proposals deserve local, state and federal policy consideration and warrant immediate national action. At the same time, ongoing dialogue rightfully will continue regarding the correct and fair steps our states and federal government should take to carry out laws and the extent to which gun regulations should be amended.
We must take the precautions we can agree on and increase school security now. School safety is broken, and our eight-point plan will fix it. |
Grab that calculator, put on your favorite superhero tee, and order some Chinese food, because the new season of The Big Bang Theory is almost here!
We're already counting down the days until we are reunited with our favorite geeky gang for their highly anticipated eight season, and now we've got something to help curb our comedic appetite. ETonline chatted with the always-amazing Mayim Bialik about what's coming up next for her delightfully off-beat character, Amy Farrah Fowler, and the rest of our brilliant Big Bang characters.
Plus, could this be the season that Sheldon (Jim Parsons) and Amy finally speed up their romantic relationship? Read on for all the exclusive details!
PICS: Exclusive Spoilers on 30 of Your Favorite TV Shows!
Big Bang Theory creator Chuck Lorre already spilled to us in our Fall TV Spoiler Spectacular that Penny (Kaley Cuoco-Sweeting) is finally throwing in the acting towel and becoming a pharmaceutical rep at Bernadette's (Melissa Rauch) company. So how is this life change going to shake-up the social hierarchy of the group?
"I think it's going to be a great opportunity to have some of that playfulness, and shifting roles in our dynamic," Bialik revealed. "I'm told that there is an opportunity for us to poke fun at her for being too studious when she's preparing for the new job in a couple of episodes and that will be really funny."
NEWS: 'The Big Bang Theory' Cast Gets Big Raises!
"It's really funny," Bialik agreed of Amy's transformation from science-loving loner to BFF's with Penny and Bernadette. "Now she's manipulating both of them." Not to worry, BBT fans! Amy will still continue to be the pop-culture-challenged gal that we all know and love.
"The episode with Penny and Bernadette is just really funny because it's Amy trying to use the hip lingo of the young people. She's calling Penny on the phone and she goes, 'Can I get a what what?'" Bialik spilled with a laugh. "It's just the nerdiest thing ever and she clearly has no idea what she's doing. It's just very cute."
And speaking of cute, it's time to get our Shamy update! Over the past four years, Sheldon and Amy have progressed slowly but surely as a couple, and despite their snails' pace, their relationship has become a fan favorite pairing. So will this be the year of full speed ahead romance? Mayim says: Not so fast!
"I think taking it slow is something that is really really sweet, and I think the Amy and Sheldon relationship really proves that there is someone for everyone," she said. "There are really no rules for how quickly or reasonably a relationship should progress and I'd like to see more of that."
With The Big Bang Theory finally in the full swing of production, (there was a brief delay due to some salary negotiations that ended up in a big payoff) Bialik now has many different hats that she must switch between. In addition to dazzling fans with her impeccable comedic timing on the smash CBS series, Bialik is also the host of new Candid Camera reboot and the brand ambassador for Texas Instruments calculators.
The real-life neuroscientist explained that she is currently on a mission, along with her favorite TI calculator, to get students excited about science, technology, engineering and math. "This year our back to school campaign is really trying to tap into the vernacular that kids and teenagers are already speaking which is apparently in the form of selfies," Bialik said of the pop-culture craze.
"So I posted mine and that's the contest, to win a video chat and technology for your classroom by submitting your most creative and best selfie." Fans can continue to post their own Texas Instruments calculator pics in the "Express Your Selfie" contest until Sept. 21 for a chance to win the top prize.
Season 8 of The Big Bang Theory premieres Monday Sept. 22 at 8 p.m. on CBS. |
Tax Practice and Procedure Changes in the Tax Cuts and Jobs Act The Tax Cuts and Jobs Act enacted far-reaching changes to taxation of corporations, individuals, and U.S. companies operating in foreign countries. Perhaps because of extensive revisions to tax procedure rules in the Protecting Americans From Tax Hikes (PATH) Act in 2015, the TCJA contains only minor revisions in this area. The TCJAs reductions in tax rates for individuals and corporations, on the other hand, have a significant impact, not only to the computation of tax on taxable income but also to other provisions in the Internal Revenue Code. And despite claiming tax simplification as one purpose of the TCJA, Congress slipped in some additional reporting requirements. This article discusses the TCJAs major revisions to tax practice and procedure rules. |
Education Minister Chris Hipkins says he's disappointed the primary teachers' union has decided to go ahead with strikes next week without taking the Government's latest offer to its members.
Primary teachers and principals will go ahead with rolling regional strikes next week after the NZ Educational Institute (NZEI) rejected the offer worth close to $700 million over three years.
Members would consider the offer at meetings during the strikes.
Hipkins said the latest offer would give the majority of teachers a pay rise of close to $10,000 over three years.
"The new offer is worth $698 million, an increase of $129 million from the previous offer. The new offer would mean significant pay increases for their members and an offer to provide for paid meetings to discuss the offer," Hipkins said.
"NZEI let their members down by not allowing them to consider the new offer before going on strike. They should stop the strike and allow a vote," he said.
NZEI president Lynda Stuart said the offers did not address union claims for lower class sizes and more professional time.
"The question is, will this address the crisis in education and the teacher shortage. What we asked for had children at the heart; for example more time to teach and smaller class sizes. This is something that our members now need to decide," she said.
"The strike action still stands as the offer is not substantially different enough to give us the mandate to revoke the strike notice. We will give members the opportunity to consider the offer, any recommendations from the ERA, and next steps."
Strikes will take place in Auckland on Monday, the rest of the North Island (except Wellington) on Tuesday, Christchurch on Wednesday, the rest of the South Island on Thursday, and Wellington on Friday.
Hipkins said the Government had been working "incredibly hard" to address teachers' concerns and would far rather be talking to them than seeing strike action.
"We think that the strike action should certainly be called off while they consider the new offer that's been put forward."
Hipkins said the proposed pay rise exceeded that of many other professions.
"I think that a $9500 pay rise is a pay rise that many other New Zealanders would certainly appreciate." |
<gh_stars>0
package com.bookstore.service;
import com.bookstore.domain.ShoppingCart;
import org.springframework.stereotype.Service;
@Service
public interface ShoppingCartService {
ShoppingCart updateShoppingCart(ShoppingCart shoppingCart);
void clearShoppingCart(ShoppingCart shoppingCart);
} |
//From https://github.com/VMormoris/GreenTea/blob/master/GreenTea/src/GreenTea/Core/uuid.cpp
#include "uuid.h"
#include <stdio.h>
//From https://stackoverflow.com/questions/36262070/what-does-htons-do-on-a-big-endian-system
#define FLIP_BYTES_S(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))
static constexpr GUID null = { 0 };
static constexpr char nullstr[] = "00000000-0000-0000-0000-000000000000";
//namespace gte {
//From https://stackoverflow.com/questions/18555306/convert-guid-structure-to-lpcstr
[[nodiscard]] std::string uuid::str(void) const noexcept
{
if (mUUID == null)
return std::string(nullstr);
char cstr[37] = { 0 };
sprintf_s
(
cstr,//Buffer
"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",//Format
mUUID.Data1,//4 first bytes
mUUID.Data2,//2 bytes
mUUID.Data3,//2 bytes
mUUID.Data4[0],//2 bytes
mUUID.Data4[1], mUUID.Data4[2], mUUID.Data4[3], mUUID.Data4[4], mUUID.Data4[5], mUUID.Data4[6], mUUID.Data4[7]//Last 6 bytes
);
return std::string(cstr);
}
uuid::uuid(const std::string& str) noexcept
{
if (str.compare(nullstr) != 0)
{
sscanf_s(str.c_str(), "%08x", &mUUID.Data1);
sscanf_s(str.c_str() + 9, "%04hx", &mUUID.Data2);
sscanf_s(str.c_str() + 14, "%04hx", &mUUID.Data3);
unsigned short* ptr = (unsigned short*)&mUUID.Data4;
sscanf_s(str.c_str() + 19, "%04hx", ptr++);
sscanf_s(str.c_str() + 24, "%04hx", ptr++);
sscanf_s(str.c_str() + 28, "%04hx", ptr++);
sscanf_s(str.c_str() + 32, "%04hx", ptr);
ptr -= 3;
for (size_t i = 0; i < 4; i++)
{
*ptr = FLIP_BYTES_S(*ptr);
ptr++;
}
}
}
//TODO(Vasilis): Add assertion
[[nodiscard]] uuid uuid::Create(void) noexcept
{
uuid newone;
HRESULT hr = CoCreateGuid(&newone.mUUID);
return newone;
}
uuid::uuid(void) noexcept { memset(&mUUID, 0, sizeof(GUID)); }
[[nodiscard]] bool uuid::operator==(const uuid& rhs) const noexcept { return memcmp(&mUUID, &rhs.mUUID, sizeof(GUID)) == 0; }
[[nodiscard]] bool uuid::operator!=(const uuid& rhs) const noexcept { return memcmp(&mUUID, &rhs.mUUID, sizeof(GUID)) != 0; }
[[nodiscard]] bool uuid::IsValid(void) const noexcept { return memcmp(&mUUID, &null, sizeof(GUID)) == 0; }
//}
[[nodiscard]] std::ostream& operator<<(std::ostream& lhs, const uuid& rhs)
{
lhs << rhs.str();
return lhs;
} |
// WithSecret configures the service with a secret value
// for signing functions.
func WithSecret(secret string) ConfigOption {
return func(s *service) {
s.secret = []byte(secret)
}
} |
Inflammatory Bowel Disease Reoperation Rate Has Decreased Over Time If Corrected by Prevalence INTRODUCTION: Despite the recent emergence of expensive biologic therapies, hospitalization and surgery remain important contributors for the overall costs of inflammatory bowel disease (IBD). In this study, we aimed to describe the burden of reoperations in patients with IBD by evaluating reoperation rates, charges, and risk factors over 16 years. METHODS: We performed a retrospective analysis of all hospital discharges, with focus on reoperations and with a primary diagnosis of IBD, in public hospitals between 2000 and 2015 in mainland Portugal from the Central Administration of the Health System's national registry. We collected data on patient, clinical, and healthcare charges. We used multivariate regressions to estimate the risk factors of IBD-related reoperations. RESULTS: We found that 5% of IBD-related hospitalizations were related to reoperations. The number of reoperations per year increased by approximately 200%. However, when corrected by the prevalence of the disease, IBD reoperation rates decreased. Mean IBD-related charges per hospitalization were 7,780 € in 2000 and 10,592 € in 2015, with total charges reaching 6.7 million euros by the end of the study. Risk factors for reoperation include urgent hospitalization, in patients with ulcerative colitis (odds ratio 1.94, 95% confidence interval 1.193.17, P = 0.008), and colic disease, in patients with Crohn's disease (odds ratio 1.57, 95% confidence interval 1.062.34, P = 0.025). DISCUSSION: To obtain an accurate scenario of reoperations among patients with IBD, it is mandatory to adjust the number of reoperations to the prevalence of the disease. Reoperation and its risk factors should be closely monitored to decrease the burden of IBD to the healthcare system. The incidence and prevalence of IBD have been increasing since the middle of the twentieth century in all geographic regions. A recent essay on the global burden of IBD anticipates that more than 1 million residents in the United States and 2.5 million in Europe have IBD. In Portugal, it is estimated that 0.2%-0.3% of the population live with IBD and recent predictions indicate that in 2030, this number will reach 0.3%-0.5%. In this context of increasing prevalence and given its chronic nature and unpredictable disease course, the impact of IBD in healthcare systems is increasing exponentially so that it became a considerable economic and social burden, with costs reaching $6.3 billion and V5 billion, in the United States and Europe, respectively. Direct healthcare costs, disability (physical and psychological), work absenteeism, and decreased productivity are among the main burdens of IBD in Western countries. This impact may be reduced by assessing and improving the quality of health care-for example, by identifying and analyzing potential sources of costly clinical outcomes. Despite the recent emergence of expensive biologic therapies, hospitalization and surgery remain important contributors for the overall costs of IBD. The numbers and impact of recurrent surgery in patients with IBD are now being explored by several authors, and the reoperations rates vary between 17% and 38%. In these studies, laparoscopy, side-to-side anastomosis, wide anastomotic stoma, and anti-tumour necrosis factor therapy were associated with a decrease of reoperations, whereas latter introduction of pharmacological therapeutic, duration of the disease, age at diagnosis younger than 17 years, penetrating behavior (B3), no azathioprine use, preoperative smoking, and ileocolic disease were pointed out as risk factors for reoperation. Despite its importance for the improvement of the quality of health care, there is only one report on the impact of IBD in Portugal and a lack of data on the reoperation trends in Portuguese patients with IBD. In this context, we have previously determined the national hospitalization rates of patients with IBD, between 2000 and 2015, resorting to an administrative database of all patients subjected to hospital discharge in that period. In this present study, we aim to describe the burden of recurrent surgeries to the healthcare system-by exploring the same database for the assessment of reoperation rates and healthcare charges-and to identify the risk factors for reoperation in patients with IBD in mainland Portugal. Data design and data source Data were retrieved and collected from the national registry of the Central Administration of the Health System (ACSS), which contains administrative data concerning all patients subjected to hospital discharge from hospitals, governed by the National Health Service (NHS) in Portugal. We included all hospital discharges of patients, of all ages, and a primary diagnosis of IBD identified by the International Classification of Diseases, Ninth Revision, Clinical Modification (ICD-9-CM) codes of 555.x (for CD) and 556.x (for UC) between January 1, 2000, and December 27, 2015. The first hospital discharge with a primary diagnosis of IBD and coded for surgery during this study period was considered the index hospital discharge. The unit of observation was the hospital discharge. Data collection For each hospital discharge, the following data were collected: year (of the hospital discharge date), hospital name, hospital admission date, hospital discharge date, admission type, age (at the time of hospital discharge), sex, area of residence, primary and secondary diagnoses, and IBD-related medical procedures. Data on disease location/extension, IBD-related surgery, anemia, malnutrition, anxiety, weight loss, wound complications, depression, and previous steroid/immunomodulators use were identified by the ICD-9-CM codes listed in Supplementary Table 1 (see Supplementary Digital Content 2, http://links.lww.com/ CTG/A393). The collected data also included the severity of illness and risk of mortality, based on the ACSS's terms of reference, for the contracting of health services in the Portuguese NHS and ranked according to the 3M All Patient Refined-Diagnosis Related Group methodology (APR-DRG, version 21). Outcomes Surgical recurrence or reoperation was defined as the necessity of subsequent operation(s) during the observational period. Other outcome measures included IBD-related number of reoperations, reoperation rate per 100,000 inhabitants, reoperation rate per 100,000 hospitalizations, and reoperation rate per 100,000 patients with IBD. The reoperation rate was calculated by dividing the number of reoperations, during the study period (numerator), by the total number of inhabitants, the total number of hospitalizations, or the total number of patients with IBD (denominators) and multiplying by a factor of 100,000. The total number of inhabitants in mainland Portugal in the analyzed years considered for the computation of the rates was obtained from the National Institute of Statistics. The prevalence of IBD in Portugal was estimated based on our previous publication, where prevalence values were forecasted from 2009 to 2030. Statistical analysis Continuous variables were summarized by mean and SD, mean and minimum and maximum (min-max), or median and interquartile range (IQR) as applicable. Categorical variables were summarized by absolute (n) and relative (%) frequencies and compared using the x 2 test. Length of stay (LOS) was defined as the number of days between the hospital admission date and the discharge date for each hospitalization record. Hospital IBD discharge volume was defined as the number of IBD-related hospitalizations per year and categorized according to percentiles: low (#7 discharges/year), below the 50th percentile; moderate (8-25 discharges/year), between the 50th and 75th percentiles; high (26-71 discharges/ year), between the 75th and 95th percentiles; very high (72-139 discharges/year), between the 95th and 99th percentiles; and highest (.139 discharges/year), above the 99th percentile. We analyzed trends in the total reoperation rates per 100,000 inhabitants or hospitalizations or patients with IBD over the study period. The total reoperation rates per 100,000 inhabitants or hospitalizations were analyzed by year and broken down by the patient's characteristics (sex and age) and disease (IBD, CD, and UC). We estimated the mean (min-max) of the reoperation rates per 100,000 inhabitants or hospitalizations between 2000 and 2015. In addition, we used joinpoint regression to identify possible inflexion points (up to 2) at which there is a significant change in trends (P value of less than 0.05) using a Monte Carlo permutation method. We analyzed joinpoints using Joinpoint trend analysis software from the Surveillance Research Program of the National Cancer Institute Version 4.2.0.2 (Statistical Research and Applications Branch, National Cancer Institute). Because of the particular study design, no control group was established to assess the risk factors for reoperation. Therefore, comparisons were performed between the groups "patients with only 1 surgery" and "patients with more than 1 surgery," being the former defined as a one-time surgery, with the absence of any subsequent surgeries attributed to the same individual and the latter as multiple surgeries attributed to the same individual. Reoperation and Risk Factors in IBD To identify the risk factors associated with reoperation, a logistic regression model was used for univariate and multivariate analyses of the outcome of interest and other covariates. Variables in which a P # 0.25 was identified, in the univariate analysis, were included in the final multivariate regression modeling (backward method). The odds ratio (OR) and 95% confidence intervals (CI) were estimated. The computed OR were adjusted for age, sex, LOS, risk of severity, risk of mortality, large intestine resection, anal/rectum surgery, ileostomy, partial/total colectomy, total proctocolectomy, colectomy/proctocolectomy, anemia, wound complications, extraintestinal manifestations, penetrating disease, bowel obstruction, gastrointestinal complications, hospital volume, and fragmented care for the outcomes related with rehospitalizations. The cumulative probabilities of being reoperated in 5 and 10 years were calculated using the Kaplan-Meier method. Statistical significance was considered for P, 0.05. Statistical analysis was performed using Statistical Package for the Social Sciences software (version 25.0). Overall During the study period, the database registered a total of 48,027 IBD-related hospitalizations in mainland Portugal public hospitals. In our study, we included only 5% of these total hospitalizations, corresponding to 2,214 IBD-related reoperations. The Ulcerative colitis Over the 16-year study period, we found 483 reoperations related to a primary diagnosis of UC in 123 patients ( Table 1). The UC extension was found as pancolitis in 22 reoperations (18%), proctosigmoiditis in 12 (10%), proctitis in 4 (3%), and left side in 2 (2%). Most of the UC-related reoperations older than or equal to 20 years old (88%) and male patients (61%), with a median LOS of 14 days (IQR: 15) ( Table 2). Total healthcare charges corresponded to approximately 2 MV and mean charge per patient was 4,891 V ( Table 2). The mean charges per hospitalization increased from 4,000 V to 5,390 V, between 2000 and 2015. In the same period of time, the total charges per hospitalization increased from 96,010 V to 123,965 V (Table 3). We noticed an increase in the absolute number of UC-related reoperations from the year 2000-2015. Accordingly, as shown in Figure 1, the UC-related reoperations rates per 100,000 inhabitants increased significantly from 0.1 to 0.4 (Figure 1a Table 4). Crohn's disease Over the 16-year study period, we registered 1,731 reoperations related to a primary diagnosis of CD from 189 unique patients ( Table 1). The CD location was ileocolic in 64 reoperations (34%), ileal in 53 (28%), and colic in 33 (17.5%). Most of the CD-related reoperations comprised young adults (20-39 years, 56%) and male patients (57%), with a median LOS of 11 days (IQR: 14) ( Table 2). Total healthcare charges corresponded to approximately 4.5 MV, and the mean charge per patient was 5,135 V ( Table 2). The mean charges per hospitalization increased from 3,780 V to 5,202 V, between 2000 and 2015. In the same period of time, the total charges per hospitalization increased from 154,994 V to 208,075 V (Table 3). The absolute number of CD-related reoperations increased from 43 in 2000 to 131 in 2015 (Table 2). Accordingly, as shown in Figure 1, between 2000 and 2015, the CD-related reoperation rate per 100,000 inhabitants increased from 0.4 to 1.3 ( Figure 1a) and per 100,000 hospitalizations increased from 3.7 to 11.3 (Figure 1b). Similar increases were also observed when the reoperation rates per 100,000 inhabitants were analyzed by sex and age (see Supplementary Table 2 Regarding the risk factors associated with reoperation in patients with CD, the univariate analysis revealed crude OR for reoperation (data not shown, see Supplementary American College of Gastroenterology In multivariate regression, the only factor significantly associated with increased odds of reoperation was colic disease (OR: 1.57; 95% CI: 1.06-2.34) ( Table 5). The factors significantly associated with decreased odds of reoperation were colectomy or proctocolectomy performed in the first surgery (OR: 0.55; 95% CI: 0.39-0.78) ( Table 5). DISCUSSION This study aims to evaluate the reoperation rates-and respective costs and risk factors-in patients with IBD, based on a retrospective analysis of a nationwide database of all hospitalizations, from public hospitals in mainland Portugal. Although, several authors have already explored the trends in reoperation rates in patients with IBD worldwide (7,9,, this is, to our best knowledge, the first project exploring the reoperation rates and the associated risk factors and costs in patients with IBD in Portugal. We found that 5% of the IBD-related hospitalizations corresponded to IBD-related reoperations (CD: 78%; UC: 22%) that increased by 200% from 2000 to 2015 (Table 1), resulting in an increase of the rates per 100,000 inhabitants and per 100,000 hospitalizations in both patients with UC and CD (see Supplementary Table 2, Supplementary Digital Content 2, http://links. lww.com/CTG/A393). This is probably related with the increasing prevalence of IBD in Portugal that, ultimately, conducts to an increase in the absolute numbers of surgeries and recurrent surgeries. In addition, we found inflexion points in the years 2005 and 2012 in IBD and CD reoperation rates per 100,000 inhabitants, respectively (see Supplementary Figures 1a and 1d, Supplementary Digital Content 1, http://links.lww.com/CTG/ A392). These results may be explained by the approval of novel biologic therapeutic approaches since the year 2000 in Portugal that allegedly reduced the risk of hospitalization, surgery, and recurrent surgery among patients with IBD. However, we observed a 1.7-fold decrease in the reoperation rate by adjusting the reoperation numbers for the forecasted population of patients with IBD (Figure 1c and Supplementary Figure 1b, Supplementary Digital Content 1, http://links.lww. com/CTG/A392). This decrease of adjusted reoperation rates among patients with IBD that has also been evidenced recently by other authors in distinct geographic zones might be explained by a combination of 2 factors: (i) the increasing prevalence of IBD in Portugal (and globally) and (ii) the approval of novel biologic treatments. These results evidence that the analysis of reoperation rates can only be conclusive and realistic when performed in a broad perspective considering total population, hospitalizations, and disease prevalence. Furthermore, we found that the cumulative 5-and 10-year reoperation rates were 29.4% and 43.9%, respectively. These results are in line with those found in the literature for CD 18,21). We did not analyze the cumulative reoperation rate for patients with UC because we were not able to consider multistage procedures and thus overestimating the cumulative reoperation rate. Regarding health expenditure of reoperated patients, our study evidenced that the mean charges per hospitalization and the total charges per year increased about 35% and 31%, respectively, between 2000 and 2015. The total charges per year reached 332,040 V in 2015, with CD being responsible for 63% of the expenses (Table 3). However, this increasing tendency was not constant and showed several fluctuations, between 2000 and 2015, hindering the establishment of a direct causal association between the number of reoperations (registered each year) and costs. This can be related to the wide range of costs of the reoperations-registered in the database-that, depending on the technical complexity, can vary significantly resulting in total charges that are not proportional to the total number of reoperations in each year. Although it is undeniable that the cost profile of patients with IBD is changing because of the recent advances in biologic therapies, several studies evidence that hospitalization and surgery remain important contributors to direct costs in IBD. Our study also aimed to identify the risk factors for reoperation, for both patients with CD and UC. Regarding UC, our data revealed that, among the evaluated factors, urgent hospitalization is the only risk factor for reoperation (Table 4). This is possibly because of emergency surgeries, such as colectomies, performed as consequence of emergency hospitalizations. In fact, there is a described tendency for the decrease of colectomy at first instance, among patients with IBD, probably because of the use of biologics but that possibility cannot be excluded in cases of severe complications. Distinctly, old age ($60 years) and anal/rectum surgery (performed in the first surgery) were identified as factors decreasing the odds of reoperation in good agreement with clinical and literature data (Table 4). Age is generally considered an important risk factor for postoperative morbidity and mortality that leads to a decrease in the number of emergency surgeries in elderly patients. Regarding previous anal/rectum surgery, our results can be related to the fact that, in this kind of procedure, there is no rectum remaining and only rarely the patients need additional surgery. What concerns to CD is that colic disease was the only risk factor for reoperation (Table 5), as also evidenced in previous studies that identified disease location and extension as risk factors for surgical recurrence in patients with CD. Colectomy or proctocolectomy performed in the first surgery was found to be protective against reoperation in patients with CD which is in accordance with the prognosis of the patients submitted to this kind of procedure. The key strengths of this study are the utilization of an administrative database with national coverage, ensuring the representativeness of the data to a nationwide scale and the novelty of this study in mainland Portugal. The study had, however, some limitations. First, as already stated, we were not able to take into account multistage procedures. Second, the retrospective and registry-based design might have led to data misclassification by inaccurate coding and validation and to eventual underreporting. For example, disease extent is not mandatory, thus frequencies in the columns may not sum up to 100% because of missing data. Third, our data set lacks patients with CD with a classification of upper disease because ICD-9-CM does not use this classification. Nevertheless, several studies have already validated the suitability of the ICD-9-CM coding system in the IBD context. Fourth, unfortunately and unlike the ICD-10-CM classification, ICD-9-CM does not allow the codification of biological treatment, and therefore, we could not possibly consider this factor in our analysis. Furthermore, only public hospitals were included in this study, therefore private hospitalizations were not considered. Finally, we only used the 2009 expenditure tables with the 3M APR-DRGversion 21 that may underappreciate any price fluctuations regarding IBD-related charges that occurred subsequently. Any DRG changes were also not considered. In conclusion, reoperation should be closely monitored and an effort on reducing or controlling the identified risk factors should be performed to improve not only the quality of life of patients but also the quality of care, with consequent reduction of the burden of IBD to the healthcare system. CONFLICTS OF INTEREST Guarantor of the article: Fernando Magro, MD, PhD. Specific author contributions: M.S. was involved in data analysis, interpretation of data, and writing the manuscript. C.C.D. was involved in conception and design of the study, data analysis, interpretation of data, and revising the manuscript. F.M. was involved in the conception and design of the study, interpretation of data, and revising the manuscript. All authors reviewed and approved the final manuscript. Study Highlights WHAT IS KNOWN 3 In the context of increasing prevalence and given its chronic nature and unpredictable disease course, the impact of IBD in healthcare systems is increasing exponentially so that it became a considerable economic and social burden. 3 The numbers and impact of recurrent surgery, in IBD patients, are now being explored by several authors and the reoperations rates vary between 17% and 38%. WHAT IS NEW HERE 3 This is the first study of its kind conducted in a Southern-European country. 3 IBD patients seem to be submitted to less reoperations since we observed a 1.7-fold decrease in the reoperation rate, by adjusting the reoperation numbers for the forecasted population of IBD patients. 3 IBD-related reoperation charges reached 6.7 MV during the study period. 3 Risk factors for reoperation include urgent hospitalization, in patients with UC, and colic disease in patients with Crohn's disease. TRANSLATIONAL IMPACT 3 To obtain an accurate scenario of reoperations among IBD patients, it is mandatory to adjust the number of reoperations to the prevalence of the disease. Reoperation and its risk factors should be closely monitored in order to decrease the burden of IBD to the healthcare system. |
#ifndef BAD_TEST_F32X4_CALC_H
#define BAD_TEST_F32X4_CALC_H
#include <bad/bad.h>
BAD_NAMESPACE_START
// =========== Arithmetic ===========
void test_f32x4_hadd3();
void test_f32x4_hadd4();
void test_f32x4_sum3();
void test_f32x4_sum4();
// ====== Advanced arithmetic =======
void test_f32x4_abs();
void test_f32x4_sign();
void test_f32x4_neg();
void test_f32x4_frac();
void test_f32x4_mod();
void test_f32x4_trunc();
void test_f32x4_round();
void test_f32x4_floor();
void test_f32x4_ceil();
void test_f32x4_clamp();
void test_f32x4_lerp();
void test_f32x4_mul_add();
void test_f32x4_mul_sub();
void test_f32x4_nmul_add();
void test_f32x4_nmul_sub();
// =========== Trigonometry ===========
void test_f32x4_sin();
// ============ Comparison ============
void test_f32x4_neq();
void test_f32x4_eq();
void test_f32x4_ge();
void test_f32x4_gt();
void test_f32x4_le();
void test_f32x4_lt();
// ======= Tests ========
void test_f32x4_is_nan();
void test_f32x4_is_infinite();
void test_f32x4_is_finite();
BAD_NAMESPACE_END
#endif |
Q:
Does entropy decrease if time is reversed?
Entropy increases if we let newton's equation work its magic.
Since newton's equation is time reversible, I would assume that in a closed isolated system, solving the differential equation and running time backwards would increase (and NOT decrease) the entropy of the system.
Is that true?
A:
Simple answer: in our universe, definitely no.
You're hitting here on an idea known as Loschmidt's Paradox[1]: given that microscopic laws are time reversible, entropy should have the same tendency to increase whether we run a system forwards or backwards in time, exactly as you understand.
The fact that this understanding is manifestly against experimental observation can be explained if we observe that the universe began (i.e. found itself at the time of the big bang) in an exquisitely low entropy state, so that almost any random walk in the universe's state space tends to increase entropy. Likewise, in the everyday world, things "happen" when a systems are not in its maximum entropy state: they spontaneously wander towards these maximum entropy states, thus changing their states and undergoing observable changes. Sir Roger Penrose calls this notion the "Thermodynamic Legacy" of the big bang and you could read the chapter entitled "The Big Bang and its Thermodynamic Legacy" in his "Road to Reality". In summary, we have a second law of thermodynamics simply by dint of the exquisitely low entropy state of the early universe.
[1] Loschmidt's own name for it is "reversal objection" (umkehreinwand), not "paradox". Paradoxes, i.e. genuine logical contradictions cannot arise in physics, otherwise they could not be experimentally observed. |
<filename>TelemetryServer/app/src/main/java/org/mavlink/messages/ardupilotmega/msg_fence_status.java
/**
* Generated class : msg_fence_status
* DO NOT MODIFY!
**/
package org.mavlink.messages.ardupilotmega;
import org.mavlink.messages.MAVLinkMessage;
import org.mavlink.IMAVLinkCRC;
import org.mavlink.MAVLinkCRC;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* Class msg_fence_status
* Status of geo-fencing. Sent in extended
status stream when fencing enabled
**/
public class msg_fence_status extends MAVLinkMessage {
public static final int MAVLINK_MSG_ID_FENCE_STATUS = 162;
private static final long serialVersionUID = MAVLINK_MSG_ID_FENCE_STATUS;
public msg_fence_status(int sysId, int componentId) {
messageType = MAVLINK_MSG_ID_FENCE_STATUS;
this.sysId = sysId;
this.componentId = componentId;
length = 8;
}
/**
* time of last breach in milliseconds since boot
*/
public long breach_time;
/**
* number of fence breaches
*/
public int breach_count;
/**
* 0 if currently inside fence, 1 if outside
*/
public int breach_status;
/**
* last breach type (see FENCE_BREACH_* enum)
*/
public int breach_type;
/**
* Decode message with raw data
*/
public void decode(ByteBuffer dis) throws IOException {
breach_time = (int)dis.getInt()&0x00FFFFFFFF;
breach_count = (int)dis.getShort()&0x00FFFF;
breach_status = (int)dis.get()&0x00FF;
breach_type = (int)dis.get()&0x00FF;
}
/**
* Encode message with raw data and other informations
*/
public byte[] encode() throws IOException {
byte[] buffer = new byte[8+8];
ByteBuffer dos = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN);
dos.put((byte)0xFE);
dos.put((byte)(length & 0x00FF));
dos.put((byte)(sequence & 0x00FF));
dos.put((byte)(sysId & 0x00FF));
dos.put((byte)(componentId & 0x00FF));
dos.put((byte)(messageType & 0x00FF));
dos.putInt((int)(breach_time&0x00FFFFFFFF));
dos.putShort((short)(breach_count&0x00FFFF));
dos.put((byte)(breach_status&0x00FF));
dos.put((byte)(breach_type&0x00FF));
int crc = MAVLinkCRC.crc_calculate_encode(buffer, 8);
crc = MAVLinkCRC.crc_accumulate((byte) IMAVLinkCRC.MAVLINK_MESSAGE_CRCS[messageType], crc);
byte crcl = (byte) (crc & 0x00FF);
byte crch = (byte) ((crc >> 8) & 0x00FF);
buffer[14] = crcl;
buffer[15] = crch;
return buffer;
}
public String toString() {
return "MAVLINK_MSG_ID_FENCE_STATUS : " + " breach_time="+breach_time+ " breach_count="+breach_count+ " breach_status="+breach_status+ " breach_type="+breach_type;}
}
|
<reponame>inepex/ineform
package com.inepex.ineForm.client.resources;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.client.ui.Image;
public class ResourceHelper {
private static IneFormResources ifResources = null;
private static CellTableResources cellTableResources = null;
// image helper
public static String getImageAsString(ImageResource resource) {
Image img = new Image();
img.setResource(resource);
return img.getElement().getString();
}
// ineform resources
public static IneFormResources ineformRes() {
if (ifResources == null) {
ifResources = GWT.create(IneFormResources.class);
ifResources.style().ensureInjected();
}
return ifResources;
}
public static void setIfResources(IneFormResources ifResources) {
ResourceHelper.ifResources = ifResources;
}
// celltable resources
public static CellTableResources cellTableResources() {
if (cellTableResources == null)
cellTableResources = GWT.create(IneCellTableResources.class);
return cellTableResources;
}
public static void setCellTableResources(CellTableResources cellTableResources) {
ResourceHelper.cellTableResources = cellTableResources;
}
public interface IneCellTableResources extends CellTableResources {
/**
* The styles used in this widget.
*/
@Source("com/inepex/ineForm/client/STYLES/IneCellTable.gss")
@Override
CellTable.Style
cellTableStyle();
}
}
|
package main
import (
"math"
"testing"
)
const tolerance = 0.01
func TestReaction1Enthalpy(t *testing.T) {
res, expected := reaction1Enthalpy(298.15), 206.20
if math.Abs(res-expected) >= tolerance {
t.Errorf("incorrect reaction enthalpy: expected %f; got %f", expected, res)
}
}
func TestReaction2Enthalpy(t *testing.T) {
res, expected := reaction2Enthalpy(298.15), -41.20
if math.Abs(res-expected) >= tolerance {
t.Errorf("incorrect reaction enthalpy: expected %f; got %f", expected, res)
}
}
func TestReaction3Enthalpy(t *testing.T) {
res, expected := reaction3Enthalpy(298.15), 165.00
if math.Abs(res-expected) >= tolerance {
t.Errorf("incorrect reaction enthalpy: expected %f; got %f", expected, res)
}
}
|
/// ceil UIEdgeInset for pixel-aligned
static inline UIEdgeInsets YYUIEdgeInsetPixelCeil(UIEdgeInsets insets) {
insets.top = YYCGFloatPixelCeil(insets.top);
insets.left = YYCGFloatPixelCeil(insets.left);
insets.bottom = YYCGFloatPixelCeil(insets.bottom);
insets.right = YYCGFloatPixelCeil(insets.right);
return insets;
} |
// addTransaction adds the passed transaction to the fake tx source.
func (p *fakeTxSource) addTransaction(tx *dcrutil.Tx, txType stake.TxType, height int64, fee int64, totalSigOps int) {
txDesc := TxDesc{
Tx: tx,
Type: txType,
Added: time.Now(),
Height: height,
Fee: fee,
TotalSigOps: totalSigOps,
TxSize: int64(tx.MsgTx().SerializeSize()),
}
p.pool[*tx.Hash()] = &txDesc
p.miningView.AddTransaction(&txDesc, p.findTx)
msgTx := tx.MsgTx()
for _, txIn := range msgTx.TxIn {
p.outpoints[txIn.PreviousOutPoint] = tx
}
atomic.StoreInt64(&p.lastUpdated, time.Now().Unix())
} |
Formally recognised small RNA viruses include members of Picornaviradae, the Nodaviradae and the Tetraviradae. However, there are many unrecognised insect viruses that also fall into this category. The Tetraviradae are a family of small isometric insect viruses with unenveloped, icosahedral capsids 35-41 nm in diameter and single-stranded positive-sense RNA (ss+RNA) genomes. They have not received wide attention from virologists. Their known host range is confirmed to only a few families of moths in a single insect order, the Lepidoptera (moths, butterflies), making them the only small RNA virus family restricted to insect hosts. While they appear to be effective at controlling several of their hosts that are important insect pests, they have been little used in this regard. The lack of a cell culture system or, until recently, a reliable means to obtain the virus from laboratory reared insects made it necessary to rely on sporadically available field-collected material of uncertain quality. Such was the difficulty that only recently did it emerge that there are actually two groups of tetraviruses, Nudaurelia .beta.-like viruses having a mono-partite genome of ca. 6 kb and Nudaurelia .omega.-like viruses having a bi-partite genome comprising ss RNAs of 5.3 and 2.5 kb. There are only two known Nudaurelia .omega.-like viruses. The complete genome of one member (Helicoverpa armigera stunt virus--HaSV) has been previously sequenced by the present inventors. The other member is Nudaurelia .omega. virus (N.omega.V) which has been partially sequenced.
One of the most intriguing aspects of infections by tetraviruses is that they appear only to infect a single tissue type, which in the case of HaSV is the midgut. In a definitive experiment that highlights the specificity of HaSV, the present inventors showed that its midgut specificity prevailed even when virus was injected into the haemocoel of larvae, thereby exposing host non-midgut cell types not normally exposed to HaSV. The presence of virus was examined by using cloned cDNA probes on Northern blots of RNA extracted from midguts and from the rest of the carcasses from three groups of larvae, one injected with HaSV, one fed HaSV and uninfected controls. They observed a positive signal only in the midgut RNA of both groups of larvae treated with HaSV.
Further evidence for specific binding of HaSV particles to a particular cell type comes from a rigorous examination of larvae of H. armigera infected with HaSV. The sensitive immuno-histochemistry technique of immuno-gold staining with silver enhancement was employed on a series of cross- and sagittal-sections of infected larvae. Sections in this series were also examined with electron microscopy. Staining appeared only in midgut cells despite close attention to tissues from the foregut, fat, body, salivary gland, and brain. Both types of differentiated cells of the midgut, the columnar and goblet cells, were found to be infected, as were the much smaller undifferentiated regenerative cells at the basal membrane. Although all these midgut cell types were found to be infected, analysis of virus binding to cells in sections of wax-embedded midgut showed that only goblet cells, and not columnar cells, were the primary target of HaSV binding.
The two known .omega.-like viruses show a high degree of sequence identity. That is, the amino acid sequences of the coat proteins of the two .omega.-like viruses show an overall 67% identity (76% similarity). This comparison defined four domains in the coat (capsid) protein, with two regions of high homology (ca. 80% identity and containing extensive stretches of sequence reaching over 95% identity) (Hanzlik et al., 1995). A 49 residue amino-terminal domain shows lower homology, as does a 165 residue sequence located towards the middle of the sequence and showing 33% identity. Surprisingly, the high overall sequence identity is not reflected in a detectable serological relationship suggesting that the central domain of low sequence homology is exposed on the capsid surface as the sole immunogenic portion of the intact virion. As first suggested by Hanzlik et al. (1995), this region is responsible for the differing host specificities of the two viruses.
The present inventors have now surprisingly realised that the central domain (corresponding to residues 287 to 416) of HaSV forms a structure belonging to the Immunoglobulin (Ig) superfamily. Other protein domains whose structures show an Ig-like fold include the variable (V) and constant (C) domains found on antibodies (e.g. the Fab fragment of IgGs), the HLA surface antigens of the MHC complex and cell adhesion proteins and receptors (e.g. the CD4 receptor recognised by HIV gp 120). Mediation of cell adhesion to other cells or the extracellular matrix by these proteins is central to development, differentiation, the immune response and tissue structure and healing. Many of these proteins are also used as receptors by viruses (Lentz (1990).
Recent studies based on cell adhesion assays and analysis of artificial lipid bilayers attached to plates have elucidated the basis of cell adhesion promoted by binding of surface proteins. These studies are exemplified by work on the binding between the MHC class II and CD4 proteins, which mediate adhesion of antigen presenting cells (APCs) and CD4.sup.+ T cells in the immune response. Soluble (monomeric) CD4 (sCD4) fails to inhibit the MHC class II-specific proliferative response of T-cell clones (Hussey et al., 1988) or the binding of MHC class II.sup.+ B cells to CD4-transfected COS-7 cells in cell adhesion assays, even at a concentration of 100 .mu.M (Sakihama et al., 1995a). This implies that the affinity of the monomeric sCD4 for the MHC class II proteins is >10.sup.-4 M. It has now been shown that oligomerization of CD4 molecules on the surface of CD4.sup.+ cells is required for stable binding to MHC class II proteins, by increasing the avidity of the interaction between these cell adhesion protein molecules (Sakihama et al., 1995 a,b). This oligomerization follows an initial interaction between 1 or 2 CD4 molecules and MHC class II dimers. Characterization of chimaeric CD4 molecules has shown that the membrane proximal domains 3 and/or 4 appear to be involved in oligomerization.
The present inventors have now recognised that the lack of sequence similarity between the Ig-like domain of HaSV and the corresponding domain of N.omega.V may allow tetravirus particles to be used as icosahedral platforms capable of carrying altered Ig-like domains or substituted tertiary structures and thereby show modified host cell binding specificities.
The Ig-like domain forms a prominent protrusion which interacts with either quasi 3-fold or icosahedral 3-fold related subunits on the surface of the tetravirus capsid. The icosahedral particles therefore present a defined oligomeric form of the Ig-like domain which is likely to allow stable binding of the complete capsid to the cell-surface receptor, analogous to the binding between CD4 and MHC class II oligomers. Support for this notion comes from the findings of Weber and Karjalainen (1993), who reported that a soluble, pentameric immunofusion construct of mouse CD4 and human C.mu. could inhibit the interaction between polymer-bound mouse sCD4 and B cells, whereas a soluble monomeric immunofusion construct of mouse CD4 and mouse C.kappa. could not. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.