content
stringlengths 7
2.61M
|
---|
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
#from test import apidf
# Imports from this application
from app import create_app, track_id
#returns a random song from the kmeans model
ssuggest = suggestion
# 2 column layout. 1st column width = 4/12
# https://dash-bootstrap-components.opensource.faculty.ai/l/components/layout
column1 = dbc.Col(
[
dcc.Markdown(
"""
##### Find the song ID of a song you enjoy listening to and paste it into the prediction generator to disvover new music.
In order to find the song ID, open spotify and search for the song you would like to use. Click on "..." next to the song and navigate to the share tab. Copy the song link and paste it into a notes page.
The result should look something like,
https://open.spotify.com/track/5ervA7lbl13K2ekOUFmgKe
The numbers and letters following /track/ are the song ID. Input this into the prediction generator to discover new music.
"""
),
],
md=6,
)
column2 = dbc.Col(
[
html.Label('Song ID: '),
dcc.Input(id = 'Track ID',
type = 'text',
placeholder='Track ID'),
html.Br(), html.Br(),
html.Button('Submit', id='btn-submit'),
html.Label('Input your track ID: '),
html.Div(id='output-submit'),
html.Br(), html.Hr(),
html.Div(f'Here is a song you may enjoy! {ssuggest}', style={'whiteSpace': 'pre-line'})
]
)
layout = dbc.Row([column1, column2])
html.Div(id='intermediate-value', style={'display': 'none'})
#Stuff I'm working on
# for store in ('session'):
# @app.callback(Output(store, 'data'),
# Input('{}-button'.format(store), 'n_clicks'),
# State(store, 'data'))
# def on_click(n_clicks, data):
# if n_clicks is None:
# raise PreventUpdate
# data = data or {'clicks': 0}
# data['clicks'] = data['clicks'] + 1
# return data
# @app.callback(Output('{}-clicks'.format(store), 'children'),
# Input(store, 'modified_timestamp'),
# State(store, 'data'))
# def on_data(ts, data):
# if ts is None:
# raise PreventUpdate
# data = data or {}
# return data.get('clicks', 0)
# def handle_upload(track_id):
# if track_id == None:
# return pd.DataFrame({}).to_json()
# e = pd.read_csv(io.StringIO(track_id))
# return e.to_json() |
Host-Pathogen Interactions : XIX. THE ENDOGENOUS ELICITOR, A FRAGMENT OF A PLANT CELL WALL POLYSACCHARIDE THAT ELICITS PHYTOALEXIN ACCUMULATION IN SOYBEANS. An elicitor of phytoalexin accumulation (endogenous elicitor) is solubilized from purified cell walls of soybean (Glycine max Merr., cv. Wayne) by extracting the walls with hot water or by subjecting the walls to partial acid hydrolysis. The endogenous elicitor obtained from soybean cell walls binds to an anion exchange resin. The elicitor-active material released from the resin contains oligosaccharides rich in galacturonic acid; small amounts of rhamnose and xylose are also present. The preponderance of galacturonic acid in the elicitor-active fragments suggests that the elicitor is, in fact, a fragment of a pectic polysaccharide. This possibility is supported by the observation that treatment of the wall fragments with a highly purified endopolygalacturonase destroys their ability to elicit phytoalexin accumulation. This observation, together with other evidence presented in this paper, suggests that galacturonic acid is an essential constituent of the elicitor-active wall fragments. Endogenous elicitors were also solubilized by partial hydrolysis from cell walls of suspension-cultured tobacco, sycamore, and wheat cells. |
High-income countries remain overrepresented in highly ranked public health journals: a descriptive analysis of research settings and authorship affiliations ABSTRACT Scientific contribution in high-impact journals is largely from authors affiliated with institutions in high-income countries (HICs). Publication of papers by contribution of individual countries to leading journals can provide a picture of the most influential countries in a particular discipline. The aim of the study was to identify changes in the patterns in authorship and origin of original research articles in relation to countries income level in the field of public health in 2016 in comparison to previous studies. A descriptive analysis was conducted based on articles published in highly ranked public health journals in 2016. Based on the inclusion criteria, 368 research articles were identified. Over 80% of these studies were conducted in HICs. Authors were mainly based in HICs (84%), especially in the USA. The majority of first, last, and corresponding authors were affiliated with HICs (over 90%). Our study might serve as a prompt for editorial and advisory boards of the leading international journals to provide more opportunities for researchers based in low and middle-income countries. |
/**
* @author aquarius
* @date 17-4-11
*/
public class LotteryViewTwo extends View {
private int mScreenWidth; // 屏幕宽度
private int mScreenHeight; // 屏幕高度
private int mSelfTotalWidth; // 自身最大的宽度
private static float DEFAULT_SIZE_FACTOR = 0.85f; // 自身占用屏幕宽度的比例
private int mOuterCircleWidth; // 最外边圆环
private Paint mOuterCirclePaint;
private int mOuterCircleBackgroundColor;
private Paint mInnerPaint;
private int mInnerCircleBackgroundColor;
private Paint mSmallCirclePaint;
private int mSmallCircleBlueColor;
private int mSmallCircleYellowColor;
private int mInnerCardTextColor;
private int mCenterCardBackgroundColor;
private int mInnerCardDefaultColor;
private int mSmallCircleRadius; // 小圆圈半径
private int mInnerCardWidth; // 卡片宽度
private int mInnerCardSpace; // 卡片间隔
private boolean mHadInitial = false;
private ArrayList<Pair<Pair<Integer, Integer>,Pair<Integer, Integer>>> mCardPositionInfoList;
private Context mContext;
private AlertDialog mAlertDialog;
private int[] mPicResId;
private String[] mInfoResArray;
private Rect mBounds = new Rect();
private float mSmallInfoTextSize;
private float mBigInfoTextSize;
private boolean mNeedRandomTimes = false;
private int mInvalidateCircleCount;
private int mInvalidateInnerCardCount;
private int mLotteryInvalidateTimes;
private boolean mStartAnimation = false; // not real animation
private boolean mLastEndSelected = false;
public LotteryViewTwo(Context context) {
this(context, null);
}
public LotteryViewTwo(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public LotteryViewTwo(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
Log.i("lottery","init");
mContext = context;
acquireCustomAttValues(context, attrs);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
mScreenWidth = dm.widthPixels;
mScreenHeight = dm.heightPixels;
mSelfTotalWidth = mScreenWidth < mScreenHeight ?
(int)(mScreenWidth * DEFAULT_SIZE_FACTOR) : (int)(mScreenHeight * DEFAULT_SIZE_FACTOR);
mSmallInfoTextSize = context.getResources().getDimension(R.dimen.lotteryview_inner_card_text_size);
mBigInfoTextSize = context.getResources().getDimension(R.dimen.lotteryview_inner_card_big_text_size);
mOuterCircleWidth = (int) context.getResources().getDimension(R.dimen.lotteryview_outer_circle_width);
mInnerCardSpace = (int) context.getResources().getDimension(R.dimen.lotteryview_inner_card_blank);
mInnerCardWidth = (mSelfTotalWidth- getPaddingLeft() -getPaddingRight() - mOuterCircleWidth * 2 - mInnerCardSpace * 4) / 3;
mSmallCircleRadius = (int) context.getResources().getDimension(R.dimen.lotteryview_outer_small_circle_radius);
mInnerCardTextColor = context.getResources().getColor(R.color.inner_card_text_color);
mCenterCardBackgroundColor = context.getResources().getColor(R.color.center_card_bg_color);
mOuterCircleBackgroundColor = context.getResources().getColor(R.color.outer_circle_bg_color);
mOuterCirclePaint = new Paint();
mOuterCirclePaint.setColor(mOuterCircleBackgroundColor);
mOuterCirclePaint.setAntiAlias(true);
mOuterCirclePaint.setStrokeWidth(mOuterCircleWidth);
mOuterCirclePaint.setStyle(Paint.Style.FILL);
mSmallCircleBlueColor = mSmallCircleBlueColor != 0 ? mSmallCircleBlueColor : context.getResources().getColor(R.color.small_circle_color_blue);
mSmallCircleYellowColor = mSmallCircleYellowColor != 0 ? mSmallCircleYellowColor : context.getResources().getColor(R.color.small_circle_color_yellow);
mSmallCirclePaint = new Paint();
mSmallCirclePaint.setColor(mSmallCircleBlueColor);
mSmallCirclePaint.setAntiAlias(true);
mOuterCirclePaint.setStyle(Paint.Style.FILL);
mInnerCircleBackgroundColor = context.getResources().getColor(R.color.inner_circle_bg_color);
mInnerPaint = new Paint();
mInnerPaint.setAntiAlias(true);
mInnerPaint.setColor(mInnerCircleBackgroundColor);
mInnerPaint.setStyle(Paint.Style.FILL);
mCardPositionInfoList = new ArrayList<>();
initResId();
}
private void acquireCustomAttValues(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.LotteryViewTwo);
mSmallCircleBlueColor = ta.getColor(R.styleable.LotteryViewTwo_outer_small_circle_color_default, 0);
mSmallCircleYellowColor = ta.getColor(R.styleable.LotteryViewTwo_outer_small_circle_color_active, 0);
mLotteryInvalidateTimes = ta.getInt(R.styleable.LotteryViewTwo_lottery_invalidate_times, 0);
DEFAULT_SIZE_FACTOR = ta.getFloat(R.styleable.LotteryViewTwo_self_width_size_factor, DEFAULT_SIZE_FACTOR);
mInnerCardDefaultColor = ta.getColor(R.styleable.LotteryViewTwo_inner_round_card_color_default, Color.parseColor("#ffffff"));
ta.recycle();
}
private void initResId() {
L.d("initResId");
mPicResId = new int[]{
R.mipmap.lottery_two_icon_huawei_mobile,
R.mipmap.lottery_one_danfan,
R.mipmap.lottery_one_f015,
R.mipmap.lottery_one_f040,
0,
R.mipmap.lottery_one_ipad,
R.mipmap.lottery_one_iphone,
R.mipmap.lottery_one_meizi,
0
};
mInfoResArray = mContext.getResources().getStringArray(R.array.jifeng_array_info);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.i("lottery","onMeasure");
setMeasuredDimension(mSelfTotalWidth, mSelfTotalWidth);
}
@Override
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
Log.i("lottery","onDraw");
drawOuterRoundCircle(canvas); //画大框
drawOuterDecorateSmallCircle(canvas);
drawInnerBackground(canvas);
drawInnerCards(canvas);
loopSmallCircleAnimation();
loopInnerRoundCardAnimation();
}
/** 外层带圆角矩形圆环 */
private void drawOuterRoundCircle(Canvas canvas) {
Log.i("lottery","drawOuterRoundCircle");
canvas.save();
canvas.clipRect(
mOuterCircleWidth + getPaddingLeft(),
mOuterCircleWidth + getPaddingTop(),
mSelfTotalWidth - mOuterCircleWidth - getPaddingRight(),
mSelfTotalWidth - mOuterCircleWidth - getPaddingBottom(),
Region.Op.DIFFERENCE);
canvas.drawRoundRect(
getPaddingLeft(),
getPaddingTop(),
mSelfTotalWidth - getPaddingRight(),
mSelfTotalWidth - getPaddingBottom(),
18, 18, mOuterCirclePaint);
canvas.restore();
}
private void drawOuterDecorateSmallCircle(Canvas canvas) {
Log.i("lottery","drawOuterDecorateSmallCircle");
int result = mInvalidateCircleCount % 2;
// top
int x = 0, y = 0;
int sideSize = mSelfTotalWidth - mOuterCircleWidth * 2 - getPaddingLeft() - getPaddingRight(); // 除去最外边圆环后的边长
for (int i = 0; i < 10; i++) {
mSmallCirclePaint.setColor(i % 2 == result ? mSmallCircleYellowColor : mSmallCircleBlueColor);
x = mOuterCircleWidth + (sideSize - mSmallCircleRadius * 2 * 9) / 9 * i + mSmallCircleRadius * 2 * i + getPaddingLeft();
y = (mOuterCircleWidth - mSmallCircleRadius * 2) / 2 + mSmallCircleRadius + getPaddingTop();
canvas.drawCircle(x, y, mSmallCircleRadius, mSmallCirclePaint);
}
// bottom
for (int i = 0; i < 10; i++) {
mSmallCirclePaint.setColor(i % 2 == result ? mSmallCircleYellowColor : mSmallCircleBlueColor);
x = mOuterCircleWidth + (sideSize - mSmallCircleRadius * 2 * 9) / 9 * i + mSmallCircleRadius * 2 * i + getPaddingLeft();
y = mSelfTotalWidth - mOuterCircleWidth + (mOuterCircleWidth - mSmallCircleRadius * 2) / 2 + mSmallCircleRadius - getPaddingBottom();
canvas.drawCircle(x, y, mSmallCircleRadius, mSmallCirclePaint);
}
// left
for(int i = 0; i < 9; i++) {
mSmallCirclePaint.setColor(i % 2 == (result == 0 ? 1 : 0) ? mSmallCircleYellowColor : mSmallCircleBlueColor);
x = mOuterCircleWidth / 2 + getPaddingLeft();
y = mOuterCircleWidth*2 + (sideSize - mSmallCircleRadius * 2 * 9) / 9 * i + mSmallCircleRadius * 2 * i + getPaddingTop();
canvas.drawCircle(x, y, mSmallCircleRadius, mSmallCirclePaint);
}
// right
for(int i = 0; i < 9; i++) {
mSmallCirclePaint.setColor(i % 2 == result ? mSmallCircleYellowColor : mSmallCircleBlueColor);
x = mSelfTotalWidth - mOuterCircleWidth / 2 - getPaddingRight();
y = mOuterCircleWidth*2 + (sideSize - mSmallCircleRadius * 2 * 9) / 9 * i + mSmallCircleRadius * 2 * i + getPaddingTop();
canvas.drawCircle(x, y, mSmallCircleRadius, mSmallCirclePaint);
}
}
private void drawInnerBackground(Canvas canvas) {
Log.i("lottery","drawInnerBackground");
canvas.drawRect(mOuterCircleWidth + getPaddingLeft(), mOuterCircleWidth + getPaddingTop(),
mSelfTotalWidth - mOuterCircleWidth - getPaddingRight(),
mSelfTotalWidth - mOuterCircleWidth - getPaddingBottom(), mInnerPaint);
}
private void drawInnerCards(Canvas canvas) {
Log.i("lottery","drawInnerCards");
int left = 0, top = 0, right = 0, bottom = 0;
int spaceNum = 0;
for(int i = 0 ; i < 9 ; i++) {
spaceNum = i % 3 + 1;
left = mOuterCircleWidth + mInnerCardWidth * (i%3) + mInnerCardSpace * spaceNum + getPaddingLeft();
top = mOuterCircleWidth + mInnerCardWidth * (i/3) +mInnerCardSpace * (i/3 + 1) + getPaddingTop();
right = left + mInnerCardWidth;
bottom = top + mInnerCardWidth;
if(!mHadInitial) {
mCardPositionInfoList.add(new Pair(new Pair(left, right), new Pair(top, bottom)));
}
drawInnerRoundCard(canvas, left, top, right, bottom, i);
}
mHadInitial = true;
}
private void drawInnerRoundCard(Canvas canvas, int left, int top, int right, int bottom, int index) {
Log.i("lottery","drawInnerRoundCard");
boolean need = switchCardColorIfNeed(index);
mInnerPaint.setColor(mInnerCardDefaultColor);
if(mStartAnimation && need) {
mInnerPaint.setColor(mOuterCircleBackgroundColor);
}
// 绘制内部小卡片
if(index == 4) {
mInnerPaint.setColor(Color.parseColor("#73D7F8"));
}
canvas.drawRoundRect(left, top, right, bottom, 12, 12, mInnerPaint);
if(index ==4) {
mInnerPaint.setColor(mCenterCardBackgroundColor);
int space = mInnerCardWidth / 9;
canvas.drawRoundRect(left + space, top + space, right - space, bottom - space, 12, 12, mInnerPaint);
}
// 绘制卡片中的图片
int picHeight = 0;
if (mPicResId != null && mPicResId[index] != 0) {
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(),mPicResId[index]);
picHeight = bitmap.getHeight();
int picLeft = left + (mInnerCardWidth - bitmap.getWidth()) / 2;
int picTop = top + mInnerCardWidth / 7;
canvas.drawBitmap(BitmapFactory.decodeResource(mContext.getResources(),mPicResId[index]), picLeft, picTop, mInnerPaint);
}
// 绘制卡片说明文字
if (mInfoResArray != null && !TextUtils.isEmpty(mInfoResArray[index])) {
if(index == 4 || index == 8) { // center text
mInnerPaint.setColor(index == 4 ? Color.parseColor("#ffffff") : mInnerCardTextColor);
mInnerPaint.setTextSize(mBigInfoTextSize);
int textX = left + (mInnerCardWidth - getTextWidth(mInfoResArray[index].substring(0, 2), mInnerPaint))/2;
int textY_1 = top + (mInnerCardWidth/4 + getTextHeight(mInfoResArray[index].substring(0, 2), mInnerPaint)) - 8;
int textY_2 = top + (mInnerCardWidth/4 + getTextHeight(mInfoResArray[index].substring(0, 2), mInnerPaint)*2 + mInnerCardWidth/10) -8;
canvas.drawText(mInfoResArray[index], 0, 2, textX, textY_1, mInnerPaint);
canvas.drawText(mInfoResArray[index], 2, 4, textX, textY_2, mInnerPaint);
return;
}
mInnerPaint.setColor(mInnerCardTextColor);
mInnerPaint.setTextSize(mSmallInfoTextSize);
int textX = left + (mInnerCardWidth - getTextWidth(mInfoResArray[index], mInnerPaint))/2;
int textY = top + picHeight + mInnerCardWidth / 4 + getTextHeight(mInfoResArray[index], mInnerPaint) -10;
canvas.drawText(mInfoResArray[index],textX, textY, mInnerPaint);
}
}
private boolean switchCardColorIfNeed(int index) {
int result = mInvalidateInnerCardCount % 9;
if((result == 0 && index == 0) || (result == 1 && index == 1) || (result == 2 && index == 2)
|| (result == 6 && index == 6)) {
return true;
}
if((result == 3 && index == 5) || (result == 4 && index == 8) || (result == 5 && index == 7)
|| (result == 7 && index == 3)) {
return true;
}
return false;
}
private void loopSmallCircleAnimation() {
// not real animation, just like it.
if(mStartAnimation){
if(mInvalidateInnerCardCount % 8 == 0) {
mInvalidateCircleCount++;
//postInvalidate();
}
}else {
mInvalidateCircleCount++;
postInvalidateDelayed(800);
}
}
private void loopInnerRoundCardAnimation() {
if(!mStartAnimation || mLastEndSelected) {return;}
if(mInvalidateInnerCardCount == mLotteryInvalidateTimes){
//mStartAnimation = false;
mLastEndSelected = true;
postInvalidate();
postDelayed(new ResultTask(mLotteryInvalidateTimes), 300);
return;
}
mInvalidateInnerCardCount++;
postInvalidateDelayed(50);
}
private class ResultTask implements Runnable {
int times;
public ResultTask(int times) {
this.times = times;
}
@Override
public void run() {
mInvalidateInnerCardCount = 0;
mLastEndSelected = false;
String info = "";
int i = times % 9;
info = mInfoResArray[i];
if(i == 3) {info = mInfoResArray[5];}
if(i == 4) {info = mInfoResArray[8];}
if(i == 5) {info = mInfoResArray[7];}
if(i == 7) {info = mInfoResArray[3];}
showResultDialog(mContext, info);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
int index = getTouchPositionInCardList(x, y);
if(index == 5) {
if(mNeedRandomTimes || mLotteryInvalidateTimes == 0) {
mLotteryInvalidateTimes = (new Random().nextInt(9) + 1) * 9 + new Random().nextInt(9);
mNeedRandomTimes = true;
}
// showReminderDialog(mContext);
start();
}
break;
}
return true;
}
public void start() {
mStartAnimation = true; //开始抽奖
invalidate();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mStartAnimation = false;
mInvalidateCircleCount = 0;
mInvalidateInnerCardCount = 0;
mNeedRandomTimes = false;
}
private void showResultDialog(Context context, String result) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.result_title)
.setMessage(context.getString(R.string.result_message, result))
.setCancelable(true)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
// private void showReminderDialog(Context context) {
// AlertDialog.Builder bubeanilder = new AlertDialog.Builder(context);
// builder.setTitle(R.string.choujiang)
// .setMessage(R.string.choujiang_desc)
// .setCancelable(false)
// .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// if(mAlertDialog != null) mAlertDialog.dismiss();
// }
// })
// .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// mStartAnimation = true;
// invalidate();
// }
// });
// mAlertDialog = builder.create();
// mAlertDialog.show();
// }
private int getTouchPositionInCardList(int x, int y) {
if(mCardPositionInfoList != null) {
int index = 1;
for (Pair<Pair<Integer, Integer>,Pair<Integer, Integer>> pair : mCardPositionInfoList) {
if(x > pair.first.first && x < pair.first.second && y > pair.second.first && y < pair.second.second) {
return index;
}
index++;
}
}
return 0;
}
private int getTextWidth(String str, Paint paint) {
paint.getTextBounds(str, 0, str.length(), mBounds);
return mBounds.width();
}
private int getTextHeight(String text, Paint paint){
paint.getTextBounds(text,0,text.length(), mBounds);
return mBounds.height();
}
} |
package de.vegetweb.vbrowserscroll;
import org.vaadin.addonhelpers.AbstractTest;
import org.vaadin.stickyvaadin.Sticky;
import com.vaadin.annotations.Theme;
import com.vaadin.data.*;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.ui.*;
import com.vaadin.ui.Button.ClickEvent;
import de.svenjacobs.loremipsum.LoremIpsum;
@SuppressWarnings("serial")
@Theme("stickyvaadin")
public class StickyDemoUI extends AbstractTest {
@Override
public Component getTestComponent() {
VerticalLayout mainLayout = new VerticalLayout();
mainLayout.setMargin(true);
mainLayout.setSpacing(true);
mainLayout.setWidth("100%");
// mainLayout.setHeight("2200px");
final GridLayout layout = new GridLayout(2, 1);
layout.setSizeFull();
layout.setMargin(true);
layout.setSpacing(true);
Panel buttonPanel = new Panel();
HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.setMargin(true);
buttonLayout.setSpacing(true);
buttonPanel.setContent(buttonLayout);
mainLayout.addComponent(buttonPanel);
mainLayout.addComponent(layout);
Button button1 = new Button("Make this button sticky/unsticky");
button1.setId("test_id_asdsad");
final Sticky sticky = new Sticky(button1);
Button button2 = new Button("Make this Panel sticky/unsticky");
buttonPanel.setId("test_id2_asdsad");
final Sticky sticky2 = new Sticky(buttonPanel);
button1.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
if (!sticky.isSticky()) {
sticky.makeSticky();
} else {
sticky.makeUnSticky();
}
}
});
button2.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
if (!sticky2.isSticky()) {
sticky2.makeSticky();
} else {
sticky2.makeUnSticky();
}
}
});
final NativeSelect spacingSelect = new NativeSelect(
"Select top spacing for sticky panel", getSpacingContainer());
spacingSelect.select("top 0px");
spacingSelect.setImmediate(true);
spacingSelect.setNullSelectionAllowed(false);
spacingSelect
.addValueChangeListener(new Property.ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Integer pxs = (Integer) spacingSelect
.getContainerProperty(spacingSelect.getValue(),
"px")
.getValue();
sticky2.setTopSpacingInPx(pxs);
}
});
buttonLayout.addComponents(button1, button2, spacingSelect);
buttonLayout.setComponentAlignment(button1, Alignment.BOTTOM_LEFT);
buttonLayout.setComponentAlignment(button2, Alignment.BOTTOM_LEFT);
for (int i = 0; i < 90; i++) {
layout.addComponent(new Label(new LoremIpsum().getWords(50)));
}
return mainLayout;
}
private Container getSpacingContainer() {
IndexedContainer container = new IndexedContainer();
container.addContainerProperty("px", Integer.class, 0);
container.addItem("top 40px").getItemProperty("px").setValue(40);
container.addItem("top 15px").getItemProperty("px").setValue(15);
container.addItem("top 10px").getItemProperty("px").setValue(10);
container.addItem("top 0px").getItemProperty("px").setValue(0);
return container;
}
} |
import { validateFn } from "./validateFn.ts";
import { validHostnames } from "./validHostnames.ts";
import { assertEquals } from "../../deps.ts";
Deno.test({
name: "invalid url",
fn: async () => {
try {
validateFn(new URL(""), []);
} catch (e) {
assertEquals(e.message, "Invalid URL");
}
},
});
Deno.test({
name: "not a ta url",
fn: async () => {
try {
validateFn(new URL("https://christianhaller.com"), validHostnames);
} catch (e) {
assertEquals(
e.message,
"christianhaller.com is not a valid tripadvisor url",
);
}
},
});
Deno.test({
name: "ta url",
fn: async () => {
validateFn(new URL("https://tripadvisor.de"), validHostnames);
},
});
Deno.test({
name: "tripadvisor.de",
fn: async () => {
validateFn(new URL("https://www.tripadvisor.de"), validHostnames);
},
});
Deno.test({
name: "profile",
fn: async () => {
validateFn(
new URL("https://www.tripadvisor.com/members/GermanR"),
validHostnames,
);
},
});
|
<gh_stars>0
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
@class ALSdk, NSString;
@interface ALUserTokenManager : NSObject
{
NSString *_userIdentifier;
NSString *_compassRandomToken;
NSString *_applovinRandomToken;
ALSdk *_sdk;
}
@property(nonatomic) __weak ALSdk *sdk; // @synthesize sdk=_sdk;
@property(copy, nonatomic) NSString *applovinRandomToken; // @synthesize applovinRandomToken=_applovinRandomToken;
@property(copy, nonatomic) NSString *compassRandomToken; // @synthesize compassRandomToken=_compassRandomToken;
@property(copy, nonatomic) NSString *userIdentifier; // @synthesize userIdentifier=_userIdentifier;
- (void).cxx_destruct;
- (id)retrieveTokenWithUserDefaultsKey:(id)arg1 oldToken:(id)arg2;
- (id)retrieveUserIdentifier;
- (id)initWithSdk:(id)arg1;
@end
|
#include <bits/stdc++.h>
using namespace std;
// *****
class Solution {
inline int hour(const string &s) const {
return 10 * (s[0] - '0') + (s[1] - '0');
}
inline int mins(const string &s) const {
return 10 * (s[3] - '0') + (s[4] - '0');
}
public:
int findMinDifference(const vector<string> &time) {
vector<int> minutes(time.size());
int T = time.size();
for (int i = 0; i < T; ++i) {
minutes[i] = hour(time[i]) * 60 + mins(time[i]);
}
sort(minutes.begin(), minutes.end());
int best = 1440;
for (int i = 1; i < T; ++i) {
best = std::min(best, minutes[i] - minutes[i - 1]);
}
best = std::min(best, 1440 - (minutes.back() - minutes.front()));
return best;
}
};
// *****
int main() {
return 0;
}
|
Theory of International Politics. By Waltz Kenneth N.. (Reading, Mass.: Addison-Wesley Publishing Co., 1979. Pp. iv + 251. $7.95, paper.) student of nationalism and Smith's theses deserve the attention of the field. Most social scientists would no doubt agree that "nationalism" is one of the most important determinants of contemporary political behavior. But the failure to address the question of what kind of behavior it induces is often a product of a previous failure of conceptual construction. There is no self-evident definition of nationalism and different authorities choose to embrace quite different elements in their definitions. A failure to advance and, more important, to remain true to an operational definition of the concept is likely to lead to inconsistency and a tendency to reify. Smith is seriously guilty on both counts. Nationalism lives and breathes in this book. Most frequently the organism is liberal. "It aims to build a nation, to construct a world of nations, each free and self governing, each unique and cohesive, each able to contribute something special to plural humanity" (p. 29). Mazzini's dream has come to life! Smith tells us nationalism is an ideology but its components are never consistently spelled out. We learn that nationalism is able to grasp "the importance and profundity of mass religious sentiments" (p. 31); that it has "aimed to give concrete political form to the aspirations of both rationalism and romanticism" (p. 82). But these insights are in the form of undeveloped assertions. |
Extracorporeal methods of vascular control for difficult IVC procedures. Surgical procedures in the juxtaheptic and intrapericardial inferior vena cava (IVC) are difficult because of the complexity of achieving vascular control in the area. We describe 10 patients with a variety of pathologies in this region who underwent venovenous bypass (VVB) or cardiopulmonary bypass with hypothermic circulatory arrest (CBCA). Renal cell carcinoma with IVC extension was present in three patients (with tumor extension into the right atrium in two), adrenal adenocarcinoma in one, septic IVC thrombus in one, and blunt IVC/hepatic trauma in five. Those patients without atrial involvement underwent VVB with a mean bypass time of 40 minutes (range 12-144). Those patients with tumor extension into the right atrium underwent CBCA with systemic hypothermia to 18C, total body exsanguination for a bloodless field, and removal of the tumor by cavotomy and right atriotomy. The mean bypass, aortic cross-clamp, and circulatory arrest times were 152, 92, and 36 minutes, respectively. Eight of the 10 patients did well and went home within 4 weeks of surgery. Two patients died, one from metabolic sequelae of exsanguinating IVC injury (VVB) and one from sepsis 2 weeks postoperatively (CBCA). |
Insertion-and-deletion-derived tumour-specific neoantigens and the immunogenic phenotype : a pan-cancer analysis Background The focus of tumour-specific antigen analyses has been on single nucleotide variants (SNVs), with the contribution of small insertions and deletions (indels) less well characterised. We investigated whether the frameshift nature of indel mutations, which create novel open reading frames and a large quantity of mutagenic peptides highly distinct from self, might contribute to the immunogenic phenotype. Introduction Tumour mutations are a key substrate for the generation of anticancer immunity. 1 Large-scale sequencing studies 2 have led to the systematic annotation of mutational processes and somatic alterations across a broad range of human cancer types. The cumulative insight from these studies has advanced our understanding of oncogenesis at both a basic and translational level. The data have also been scrutinised for mutations that might play a role in the recognition of cancer cells by the immune system. The focus of these analyses to a large extent is on the single nucleotide variants (SNVs), on account of the relative simplicity and reliability of calling sequence changes of one base pair (bp) fixed length. As a consequence, the effect of small scale insertion and deletion mutations (indels) on antitumour immunity has been poorly characterised despite the clear link of such mutations to oncogenesis 3 and their potential to generate highly immunogenic peptides. The success of checkpoint inhibitor therapies underlines the notion that tumour-specific T-cell responses pre-exist in some patients and are kept under tight control via immune modulatory mechanisms. To date, checkpoint inhibitors have been approved for the treatment of six solid tumour types: melanoma (anti-PD-1/CTLA-4), merkel cell carcinoma (anti-PDL-1), renal clear cell carcinoma (anti-PD-1), non-small cell lung cancer (lung adenocarcinoma and lung squamous cell carcinoma; anti-PD-1), carcinoma of the bladder (anti-PD-L1), and head and neck squamous cell carcinoma (anti-PD-1), as well as microsatellite instability high (MSI-H) tumours of any tissue subtype. T cells reactive to tumour-specific mutant antigens (neoantigens) have been detected across the common epithelial malignancies 4 and neoantigens are increasingly shown to be the target of checkpoint inhibitor-induced T-cell responses 5,6 and adoptively transferred T cells. 7-9 Many investigators are leveraging whole-exome sequencing and RNA sequencing, focusing on non-synonymous SNVs (nsSNVs), to predict expressed mutated peptides that bind MHC class I molecules (SNV-neoantigens). Neoantigen burden is closely related to the nsSNV burden, which varies significantly across cancer types, from one nsSNV in paediatric tumours to more than 1500 nsSNVs in tumours associated with microsatellite instability. 10 However, less than 1% of the nsSNVs in expressed genes lead to detectable CD4-positive 11 or CD8-positive T-cell 7 reactivities in tumour-infiltrating lymphocytes. Accordingly, efficacy of checkpoint inhibitors is most marked in tumour types with a high nsSNV burden, including melanoma, lung adenocarcinoma, lung squamous cell carcinoma, head and neck squamous cell carcinoma, and carcinoma of the bladder, 10 which reflects a higher probability of creating a neoantigen that will be presented to and recognised by T cells. Furthermore, within these tumour types, nsSNV and neoantigen burdens correlate with response to checkpoint inhibitors. 12-16 A notable outlier is renal clear cell carcinoma, which has a relatively low nsSNV burden (around ten times lower than melanoma). Renal clear cell carcinoma is characterised by a high level of tumour-infiltrating immune cells 17 and has been shown to respond to interferon-, high-dose interleukin 2, 18,19 and, more recently, checkpoint inhibitors, 20,21 but the mutational and antigenic determinants of these responses are unknown. Indel mutations that cause a frameshift (frameshift indels) create a novel open reading frame and could produce a large quantity of neoantigenic peptides highly distinct from self (appendix p 5). It has been hypothesised 22 that novel open reading frames might be an ideal source of tumour-derived neoantigens and so induce multiple neoantigen reactive T cells, because of both an increased number of mutant peptides and reduced susceptibility to self-tolerance mechanisms. On this basis, we aimed to characterise the pattern of indel mutations with pan-cancer analysis and investigate their association with antitumour immune response and outcome following checkpoint blockade. Study design and participants Pan-cancer somatic mutational data were obtained from The Cancer Genome Atlas (TCGA) for whole-exome sequencing data of 5777 solid tumours, across 19 Research in context Evidence before this study We searched for available evidence in PubMed, which revealed multiple publications documenting overall mutation rates and signatures by cancer type. The predominant focus of existing literature was on single nucleotide variation (SNV) mutations, with no previous study done of insertion and deletion (indel) mutations on a pan-cancer basis. Regarding the association between somatic mutations and upregulation of antitumour immunity via checkpoint inhibition, several previous studies reported a link between high SNV load and improved response to checkpoint inhibition. Prevailing evidence suggests the mechanism of this association is linked to tumour-specific neoantigen reactive T cells. No previous pan-cancer study has investigated the difference between SNV and indel-derived neoantigens, despite the propensity of indels to generate highly mutagenic peptides via creation of a shifted novel open reading frame. Added value of this study We did a pan-cancer assessment of indel load across 5777 tumour samples spanning 19 cancer types. Kidney tumours were observed to have the highest proportion and absolute count of indel mutations on a pan-cancer basis, a result which was replicated in two further independent datasets. Compared with SNV mutations, indel mutations were observed to generate three times more high-bindingaffinity neoantigens, and nine times more mutant-specific binders. Finally, we assessed the association between indel load and checkpoint inhibitor response in three melanoma cohorts, which showed indel load to be more strongly associated with response than non-synonymous (ns) SNV load. Implications of all the available evidence Our data highlight the importance of frameshift neoantigens alongside nsSNV neoantigens as determinants of immunotherapy efficacy and potentially crucial targets for vaccine and cell therapy interventions. Our observations in kidney cancer might reconcile the observed immunogenicity of this tumour type despite its low overall mutational burden. 23 and a whole-exome sequencing study of ten patients with renal clear cell carcinomas reported by Gerlinger and colleagues. 24 We obtained final post-quality control patient-level mutation annotation files for each study. To further test for an association between nsSNVs or indel loads and patient response to checkpoint inhibitor therapy we used four patient cohorts. The first dataset consisted of 38 patients with melanoma treated with anti-PD-1 therapy, as reported by Hugo and colleagues. 25 We obtained final post-quality control mutation annotation files and clinical outcome data, and 34 patients were retained for analysis after exclusion of cases in which DNA had been extracted from patientderived cell lines and patients in whom tissue tumor purity was below 20%. Four samples from Hugo and colleagues 25 were taken after a short period on treatment, which raises the possibility that checkpoint inhibitor therapy itself might have affected mutational frequencies through possible elimination of immunogenic tumour clones. To be consistent with the original study, these samples were not excluded; however, we note the frameshift indel association presented becomes more significant with these cases removed. The second checkpoint inhibitor cohort comprised of 62 patients with melanoma treated with anti-CTLA-4 therapy, as reported by Snyder and colleagues. 13 All patients' samples were taken from fresh snap frozen tumour tissue with tumour purity of more than 20% so, accordingly, all 62 cases were retained for analysis. The Snyder and colleagues' cohort also contained a number of samples taken on treatment; these samples have been retained for consistency; however, we note again the significance of results strengthens if they are removed. The third checkpoint inhibitor cohort comprised of 100 patients with melanoma treated with anti-CTLA-4 therapy, as reported by Van Allen and colleagues; 12 one patient (Pat21) was excluded because of a tumour purity of less than 20%. The final checkpoint inhibitor cohort comprised of 31 patients with non-small-cell lung cancer treated with anti-PD-1 therapy, as reported by Rizvi and colleagues; 14 all patients were eligible for inclusion. For these four cohorts, 12-14 final mutation annotation files, including indel mutations, were not available, so we obtained raw BAM files and undertook variant calling using a standardised bioinformatics pipeline. To assess for a general association between nsSNVs or indel loads and patient overall survival we used a final cohort of 100 patients with non-small-cell lung cancer, as reported by Jamal-Hanjani and colleagues. 26 We obtained final post-quality control mutation annotation files and clinical outcome data, and 88 patients were retained for analysis after exclusion of non-smokers. Non-smokers were excluded on account of differing cause of disease and dramatic differences in mutation counts, which were likely to confound analyses. We additionally considered clonal versus subclonal analysis of indel counts in this cohort; however, because of small indel numbers it was not possible to reliably subset the data in this manner. Procedures For whole-exome sequencing variant calling, we obtained BAM files representing both the germline and tumour samples from the cohorts of Snyder and colleagues, 13 Van Allen and colleagues, 12 and Rizvi and colleagues 14 and converted these to FASTQ format using Picard tools (version 1.107) SamToFastq. Raw paired-end reads (100 bp) in FastQ format were aligned to the full hg19 genomic assembly (including unknown contigs) obtained from GATK bundle (version 2.8), 27 using bwa mem (bwa-0.7.7). 28 We used Picard tools to clean, sort, and merge files from the same patient sample and to remove duplicate reads. We used Picard tools, GATK (version 2.8.1), and FastQC (version 0.10.1) to produce quality control metrics. SAMtools mpileup (version 0.1.19) 29 was used to locate non-reference positions in tumour and germline samples. Bases with a Phred score of less than 20 or reads with a mapping quality less than 20 were omitted. Base-alignment quality computation was disabled and the coefficient for downgrading mapping quality was set to 50. VarScan2 somatic (version 2.3.6) 30 used output from SAMtools mpileup to identify somatic variants between tumour and matched germline samples. Default parameters were used with the exception of minimum coverage for the germline sample, which was set to 10, and minimum variant frequency was changed to 001. VarScan2 processSomatic was used to extract the somatic variants. The resulting SNV calls were filtered for false positives with the associated fpfilter.pl script in Varscan2, initially with default settings then repeated with min-var-frac=002, having first run the data through bamreadcount (version 0.5.1). Only indel calls classed as high confidence by VarScan2 processSomatic were kept for further analysis, with somatic_p_value scores less than 5 10 -. MuTect (version 1.1.4) 31 was also used to detect SNVs, with annotation files contained in GATK bundle. Following completion, variants called by MuTect were filtered according to the filter parameter PASS. In the pan-cancer cohort, SNV and indel mutation counts were computed per case, considering all variant types. Across all 5777 samples, we observed a total of We estimated non-sense-mediated decay (NMD) efficiency with RNAseq expression data (as measured in transcripts per kilobase million), obtained from the TCGA GDAC Firehose repository. We estimated the extent of NMD for all indel and SNV mutations (with SNV mutations used as a benchmark comparator) by comparing mRNA expression in samples with a mutation to the median mRNA expression of the same transcript across all other tumour samples in which the mutation was absent. Specifically, mRNA expression of every mutation-bearing transcript was divided by the median mRNA expression of that transcript in non-mutated samples, to give an NMD index. The overall NMD index values observed were 093 (indels) and 100 (SNVs), suggesting an overall 7% reduction in expression in indel mutated transcripts. Tumour purity in the renal clear cell carcinoma cohort was 054, 32 quantified by histological assessment, and assuming constant expression in the remaining 046 normal cellular content, that would yield an adjusted 14% drop in expression in indel-mutationbearing cancer cells. If we assume that tumour mutations are clonal, of heterozygote genotype, in a diploid genomic region, and wild-type allele expression in mutated cancer cells remains constant, a purity-adjusted reduction of 05 would be expected under a model of fully effective NMD. Hence these data suggest NMD operates with reduced efficiency in the renal clear cell carcinoma cohort; however, we acknowledge that these assumptions will have some effect. These data are presented as a global approximation of NMD efficiency, using methods in line with previous publications. 33 NMD index values were −log₂ transformed, with 0 indicating no mRNA degradation and plotted for indel or SNV mutations. We used PyClone 34 and ASCAT 35 to determine the clonal status of variants in the cohorts by Snyder and colleagues 13 and Van Allen and colleagues. 12 For each case variant calls were integrated with local allele-specific copy number (obtained from ASCAT), tumour purity (also obtained from ASCAT), and variant allele frequency. All mutations were then clustered using the PyClone Dirichlet process clustering. We ran PyClone with 10 000 iterations and a burn-in of 1000, and default parameters. For a number of tumours the reliable copy number, mutation, and purity estimations could not be extracted, rendering clonal architecture analysis intractable and these tumours were omitted from the analysis. The following sample was excluded because of an absence of accurate copy number or clonality estimation in Snyder and colleagues' cohort 13 : V_MSK052. For Van Allen and colleagues' cohort, 12 reliable analysis of indel mutation clonality was not possible because of a lack of accurate copy number or clonality estimation in a number of cases: Pat02, Pat06, Pat100, Pat101, Pat103, Pat106, Pat110, Pat113, Pat131, Pat132, Pat135, Pat138, Pat139, Pat140, Pat148, Pat159, Pat160, Pat163, Pat165, Pat166, Pat170, Pat171, Pat174, Pat175, Pat24, Pat36, Pat38, Pat73, Pat77, Pat78, Pat79, and Pat92. For a subset of patients (n=4592) from the TCGA cohort, tumour-specific neoantigen binding affinity prediction data were also available and obtained from Rooney and colleagues. 36 Briefly, the four digit HLA type for each sample, along with mutations in class I HLA genes, were determined using POLYSOLVER (POLYmorphic loci reSOLVER). 37 We determined somatic mutations using Mutect 31 and Strelka 38 tools. All possible 9-mer and 10-mer mutant peptides were computed, on the basis of the detected somatic SNV and indel mutation across the cohort. Binding affinities of mutant and corresponding wild-type peptides, relevant to the corresponding POLYSOLVER-inferred HLA alleles, were predicted using NetMHCpan (version 2.4). 39 Highaffinity binders were defined as IC 50 less than 50 nM. Wild-type allele non-strong binding was defined as IC 50 greater than 50 nM. Accordingly a mutant-specific binder was used to refer to a neoantigen with mutant IC 50 less than 50 nM and wild-type IC 50 more than 50 nM. A strong binding threshold was used for wild-type alleles to ensure fair comparison between SNV-derived and indel-derived neoantigens, in view of the high incidence of wild-type non-binders for indels. We excluded (from the pancancer neoantigen analyses) cancers that were associated with a high level of viral genome integration, including cervical (>80% rate of human papillomavirus integration) and hepatocellular carcinoma (>50% rate of hepatitis B integration), but not head and neck squamous cell carcinoma (<15% rate of human papillomavirus integration). No TCGA dataset was available for Merkel cell carcinoma. Immune gene signature data were obtained from Rooney and colleagues, 40 with gene sets defined as stated in the appendix (p 3). We did analysis for TCGA patients with renal clear cell carcinoma (n=392), for whom both RNAseq and neoantigen data were available. A high burden of frameshift indel high-affinity neoantigens was defined as more than 10 per case (n=32), and the percentage difference in expression was compared between the high indel neoantigen group and all other patients across each immune signature. We excluded immune signatures with minimal ssGSEA enrichment scores (<05) in all groups. The same analysis was repeated for a high burden of SNV-derived high-affinity (number of indels + number of SNVs) indel proportion = number of indels neoantigens, with a threshold of more than 17 SNV neoantigens selected to size match the high burden groups (equal number of patients; n=32 across all highload groups) across mutational types. We plotted the percentage differences in expression in heatmap format. We did correlation analysis within the high-frameshift indel neoantigen group (n=32 patients with renal clear cell carcinoma). Outcomes Across the four cohorts of patients treated with checkpoint inhibitors, we tested nsSNV, all-coding indel, and frameshift indel variant counts for an association with patient response to therapy. For each of these measures, high groups were defined as the top quartile and low groups were defined as the bottom-three quartiles. We used the same criteria across all four datasets and compared the proportion of patients responding to therapy in high and low groups. Measures of patient response were based on definitions consistent with how they were evaluated in the said trials, as follows. For Snyder and colleagues' cohort, 13 long-term clinical benefit was defined as radiographic evidence of freedom from disease, evidence of a stable disease, or decreased volume of disease for more than 6 months. No long-term clinical benefit was defined as tumour growth on every CT scan after the initiation of treatment (no benefit) or a clinical benefit lasting 6 months or less (minimal benefit). For Hugo and colleagues' cohort, 25 responding tumours were complete response, partial response, and stable disease, and non-responding tumours were defined as disease progression. For Van Allen and colleagues' cohort, 12 clinical benefit was defined as complete response, partial response, or stable disease, and no clinical benefit was progressive disease or stable disease with overall survival less than 1 year. For Rizvi and colleagues' cohort, 14 durable clinical benefit was defined as partial response or stable disease lasting longer than 6 months, and no durable benefit was progressive disease less than 6 months from beginning of therapy. Statistical analysis Survival analysis was done using the Kaplan-Meier method, with p value determined by a log-rank test. Relapse-free survival was defined as the time to recurrence or relapse, or if a patient had died without recurrence, the time to death. Hazard ratio (HR) was determined through a Cox proportional hazards model. Multivariate Cox regression was done with relapse-free survival versus indel load with stage, adjuvant therapy (yes or no), age, and histology included in the model. We compared indel burden and proportion measures between renal cell carcinomas and all other non-kidney cancers with a two-sided Mann-Whitney U test. In the checkpoint inhibitor response analysis, nsSNV, exonic indel, and frameshift indel counts were each compared to patient response outcome using a two-sided Mann-Whitney U test. We did a meta-analysis of results across the four checkpoint inhibitor datasets using the Fisher's method of combining p values from independent tests. We undertook immune signature correlation analysis using a Spearman's rank correlation coefficient. We carried out statistical analyses using R (version 3.0.2) and considered a p value of 005 or less (two-sided) as being statistically significant. Role of the funding source The funders of the study had no role in study design, data collection, data analysis, data interpretation, or writing of the report. The corresponding author had full access to all the data in the study and had final responsibility for the decision to submit for publication. Results We observed a median indel proportion value of 005 and a median indel count of 4, cohort-wide. Across all tumour types, renal clear cell carcinoma was found to have the highest proportion of coding indels, 012 (p<22 10 -; figure 1), a 24 times increase when compared with the pan-cancer average. This result was replicated in two further independent cohorts, with median observed indel proportions of 010 in Sato and colleagues' study 23 and 012 in Gerlinger and colleagues' study 24 (figure 1). Renal papillary cell carcinoma and chromophobe renal cell carcinoma had the second and third highest indel proportion, suggesting a possible tissue-specific mutational process contributing to the acquisition of indels in renal cancers. Renal papillary cell carcinoma (median indel number of 10 ) and chromophobe renal cell carcinoma (8 ) had the highest absolute indel count across all tumour types, closely followed by renal clear cell carcinoma (7 ). Renal clear cell carcinoma is characterised by loss-offunction mutations in one or more tumour-suppressor genes: VHL, PBRM1, SETD2, BAP1, and KDM5C, 32 which can be inactivated by nsSNV or indel mutations. To exclude the possibility that these hallmark mutations were distorting the results, we recalculated renal clear cell carcinoma indel proportion excluding these genes; the revised indel proportion remained at 012. When we used previously published multiregion whole-exome sequencing data 24 from ten cases of renal clear cell carcinoma to assess the clonal nature of indel mutations, 53 (48%) of 110 frameshifting indels were clonal in nature (present in all tumour regions). The overall effect of NMD on the expression of indelmutated genes was estimated to be 14% (7% drop divided by 054 tumour purity), suggesting it operates on a subset of transcripts (appendix p 6). Next we sought to investigate the potential immunogenicity of nsSNV and indel mutations through analysis of MHC class I-associated tumour-specific neoantigen binding predictions in the pan-cancer TCGA cohort. Across all samples, HLA-specific neoantigen predictions were done on 335 594 nsSNV mutations, resulting in a total of 214 882 high-affinity binders (defined as epitopes with predicted IC 50 <50 nM; the concentration necessary to reduce the binding affinity by half), equating to a rate of 064 neoantigens per nsSNV mutation (SNVneoantigens; table). In a similar manner, predictions were made on 19 849 frameshift indel mutations, resulting in 39 768 high-affinity binders with a rate of 200 neoantigens per frameshift mutation (frameshift neoantigens; table). Thus on a per mutation basis, frameshift indels could generate around three times more high-affinity neoantigen binders than nsSNVs (table), consistent with the prediction in a recent analysis of a colorectal cancer cohort. 41 When both wild-type and mutant peptides are predicted to bind, central immune tolerance mechanisms might delete cells with the reactive T-cell receptor. 42 Therefore, we repeated a pancancer analysis restricting the neoantigens to mutantspecific binders (ie, where the wild-type peptide is not predicted to be a strong binder), and showed that frameshift indels were nine times enriched for mutantallele-only binders (table). Of particular interest were genes that are frequently altered via frameshift mutations and with high propensity for MHC binding. In a pan-cancer analysis, these genes were enriched for classic tumour-suppressor genes, including TP53, ARID1A, PTEN, KMT2D, KMT2C, APC, and VHL (figure 2). Collectively, the top 15 genes with the highest number of frameshift mutations were mutated in more than 500 samples (approximately 10% of the cohort with 5777 samples) with more than 2400 highaffinity neoantigens predicted. Tumour-suppressor genes have been a previously intractable mutational target, but they might be targetable as potent neoantigens. Furthermore, by virtue of being founder events, many alterations in tumour-suppressor genes are clonal, present in all cancer cells, rendering them compelling targets for immunotherapy. 43 We next considered the clinical effect of indel mutations by assessing the association between neoantigen enrichment and therapeutic benefit. Consistent with a potential role of frameshifts in the generation of neoantigens, those tumour types approved for the use of checkpoint inhibitors were all found to harbour an above average number of frameshift neoantigens, despite substantial differences in the total SNV or indel mutational burden-eg, renal cell carcinoma ( figure 3). Overall, the number of frameshift neoantigens were significantly higher in the checkpoint inhibitor-approved tumour types versus those that have not been approved to date (p<22 10 -). However, the potential presence of frameshift neoantigens alone does not imply that they induce T-cell responses, and hence we tested their effect on checkpoint inhibitor efficacy. We used the exome sequencing results from an anti-PD-1 study 25 in melanoma (n=38 patients). We tested three classes of mutation, nsSNVs, in-frame indels, and frameshift indels, for an association with response to treatment. Although nsSNVs (p=027) and in-frame (3n) indels (p=019) had no association with response to treatment, frameshift indel mutations were significantly associated with anti-PD-1 response (p=0023; figure 4A). The upper quartile of patients with the highest burden of frameshift indels had an 88% (seven of eight cases) response to anti-PD-1 therapy, compared with 43% (11 of 26 cases) for the lower three quartiles (odds ratio 95 ; figure 4B). To confirm the reproducibility of this association, further checkpoint inhibitor response data were obtained from two additional melanoma cohorts: Snyder and colleagues' cohort 13 (n=62, anti-CTLA-4 treated) and Van Allen and colleagues' cohort 12 (n=100, anti-CTLA-4 treated). We did the same analysis in each cohort and frameshift indel burden was significantly associated with checkpoint inhibitor response in both datasets (HR 34 ; p=00074 for Snyder and colleagues' cohort and 29 ; p=0032 for Van Allen and colleagues' cohort; figure 4A). An overall meta-analysis across the three cohorts confirmed frameshift indel count to be associated with checkpoint inhibitor response (p=47 10 -), and with a more significant association than nsSNV count (p=48 10 -). The effect of clonality was additionally assessed, and clonal frameshift indels were found to have a further significantly predictive advantage beyond all frameshift indels (clonal and subclonal; appendix p 7), supporting previous work reported by our group. 43 Overall survival analysis was not different between high and low frameshift indel groups, possibly because of the effect of subsequent therapies on the overall survival (OR 243 ; p=0228 for Hugo and colleagues' cohort 25 ; appendix p 8). We assessed the association between frameshift indel load and checkpoint inhibitor response in another tumour type by using data obtained from Rizvi and colleagues' small cohort 14 of 31 patients with non-small-cell lung cancer treated with anti-PD-1 therapy; no difference was observed (p=023). Neoantigens per mutation To further investigate the importance of frameshift indels in non-small-cell lung cancer, we did additional analysis using data from Jamal-Hanjani and colleagues' cohort 26 of 100 cases, none of whom received treatment with checkpoint inhibitors. Consistent with our previous findings, 43 we observed that patients with lung adenocarcinoma whose tumour's harboured a high clonal neoantigen burden (higher than upper quartile of cohort) exhibited improved relapse-free survival compared with the bottom three quartiles (p=0026). However, across all histological subtypes of non-smallcell lung cancer, survival was found to be significantly improved for patients with a high load of frameshift indels (vs low load: HR 025 ; p=0045); by contrast, nsSNV load was not formally associated (036 ; p=0084; appendix p 9). Of note, the strongest prognostic predictor was for patients in the patients with a high load of both nsSNVs and frameshift indels, with elevated levels of both frameshift indels and nsSNVs, with no events in this group (p=0025). Multivariate analysis showed some evidence of correlation between variables (appendix p 2), so further investigation of nsSNVs and frameshift indels as predictors in larger patient cohort will be required to draw definitive conclusions. Analyses of the indel load and proportion of response achieved from phase 2 studies for the tumour types not approved for checkpoint inhibition were limited by the small sample size and variable patient inclusion criteria such as PDL-1 immunohistochemistry (appendix p 4). Nevertheless, the proportion of patients achieving a response was higher in triple-negative breast cancer 44 compared with other invasive breast carcinoma molecular subtypes, and triple-negative invasive breast carcinoma has a higher burden of frameshift and mutant-specific neoantigens ( figure 3). Furthermore, mutational burden has been reported as higher in BRCA1-mutated triplenegative breast cancer compared with BRCA-wild-type triple-negative breast cancer, 45 and we specifically observed a higher indel load in these cases (appendix p 10). However, this outcome did not correlate with tumourinfiltrating lymphocyte density (appendix p 10), possibly because of the small sample size, absence of indel immunogenicity in this tissue type, or additional factors that modulate tumour-infiltrating lymphocyte density. Finally, although genomic data are not available to correlate with checkpoint inhibitor response in renal clear cell carcinoma, we analysed the association between frameshift neoantigen load and immune responses within the tumour using RNAseq gene expression data. Patients were split into groups on the basis of the burden of frameshift neoantigens (high defined as >10 frameshifts per case, with this threshold set to capture the top 10% of cases) versus SNV-neoantigens (high defined as >17 nsSNVs per case, with this threshold set to ensure matched patient sample sizes). A high load of frameshift neoantigens was associated with upregulation of immune signatures classically linked to immune activation, including MHC class I antigen presen tation, CD8-positive T-cell activation, and increased cytolytic activity, a pattern not observed in the high SNV-neoantigen group ( figure 5). Furthermore, correlation analysis within the high frameshift neoantigen group showed that CD8-positive T-cell signature was correlated with both MHC class I antigen presentation genes (r=078) and cytolytic activity (r=083; figure 5). Discussion In this study, we analysed the pattern of indel mutations across 19 solid tumour types and found that renal clear cell carcinoma, renal papillary cell carcinoma, and chromophobe renal cell carcinoma have the highest indel rate as a proportion of their total mutational burden and the highest overall indel count and are enriched for mutant-specific neoantigens. We also observed that indel number is significantly associated with checkpoint inhibitor response in melanoma. Indels are thought to occur as a result of DNA strand slippage during DNA synthesis 46 and their frequency is higher in repetitive sequences, especially those that are AT-rich. Indels are also generated through mutagen exposure, with a higher number observed in smoking than in non-smoking non-small-cell lung cancer (lung adenocarcinoma) 40 and higher in UV-exposed (cutaneous) versus UV-protected (mucosal) melanomas. 47 Less is known about the repair of indels than SNVs; however, the role of the mismatch repair mechanism is illustrated by the microsatellite instability-high phenotype, characterised by excess indels in repetitive sequences as seen in patients with Lynch syndrome. Although renal clear cell carcinoma has been reported in patients with Lynch syndrome, 48 this cannot account for the overall pattern of indel rates across renal clear cell carcinoma nor the comparatively low SNV burden. Most renal clear cell carcinomas have loss of chromosome 3p, which encodes the mismatch repair gene MLH1, but the remaining allele is rarely mutated in sporadic renal clear cell carcinoma. Another relevant gene encoded on 3p is FHIT, and its deficiency has been linked with indel accumulation in knockout mouse models, but the consequences of the heterozygous knockout (whether haploinsufficient) are unknown. 49 However, as loss of 3p is an infrequent event in renal papillary cell carcinoma and chromophobe renal cell carcinoma and indels are also elevated in both these tumour types, other tissuespecific phenomena are likely to contribute to the increased indel burden across all renal carcinoma subtypes. 50 Renal clear cell carcinoma and renal papillary cell carcinoma arise in the proximal tubule and chromophobe renal cell carcinoma in the distal tubule of the nephron, and this shared tissue context might be important, even if the three subtypes are molecularly distinct. 32,50,51 The nephron, and the proximal tubule in particular, play a crucial role in the reabsorption of vast volumes of renal filtrate and elimination of waste products of metabolism and toxins, with the effects of toxin elimination evident in the increased incidence of renal clear cell carcinoma in those individuals exposed to aristolochic acid. 52 Ochratoxin A, a mycotoxin, induces renal tumours in rodents by causing double-strand breaks. 53 Poly morphisms in genes involved in the repair of double-strand breaks are associated with an increased risk of renal clear cell carcinoma. 54 Double-strand breaks are mostly repaired by non-homologous end-joining, which is error-prone and can increase the rate of small indels (1-10 bp). Therefore, it is possible that an environmental toxin causes an excess of double-strand breaks in the nephron and that non-homologous endjoining's mutagenic potential is exacerbated by functional polymorphisms. In support of this notion we observed a higher rate of indels in triple-negative breast cancer, which is enriched for BRCA deficiency. BRCA1 has been shown to inhibit error prone non-homologous endjoining. 55 However, we did not observe a correlation between indel load and tumour-infiltrating leucocytes density in BRCA1 triple-negative invasive breast carcinoma. We observed that indels, which alter the reading frame, generate three times as many predicted neoantigens as nsSNVs and nine times as many strong mutant-binding neoantigens where the wild-type sequence is not predicted to strongly bind the HLA molecule (IC 50 >50 nM). Thus, frameshift mutations potentially result in a neoantigen landscape, which is both quantitatively and qualitatively more potent than that provided by an equivalent number of nsSNVs. In keeping with this notion, microsatellite instability-high colorectal cancer CD8-positive tumour-infiltrating leucocytes density correlates positively with the total number of frameshift mutations. 56 With the exception of polyomavirus-positive Merkel cell carcinoma and Hodgkin's lymphoma, renal clear cell carcinoma is the only tumour type with a relatively low nsSNV burden among the tumour types for which checkpoint inhibitors have been approved for clinical use. However, owing to a comparable frameshift burden its level of mutant-specific high-affinity neoantigens is similar to that observed in non-small-cell lung cancer and melanoma, and the same is true of renal papillary cell carcinoma and chromophobe renal cell carcinoma. Although the evidence for the immunogenicity of renal papillary cell carcinoma is sparse, complete responses have been noted with the use of both high-dose interleukin 2 57 and anti-PD-1 therapy. 58,59 Therapeutic data in chromophobe renal cell carcinoma are limited. Given the differential benefit across patients, the spectrum of immune-related adverse events, and the cost of checkpoint inhibitor drugs, efforts to identify biomarkers of response are ongoing. PDL-1 expression and MSI-H status are the only biomarkers that have been linked to drug approval. Mutational and neoantigen burdens have been shown to correlate with clinical outcomes from checkpoint inhibitor therapy in patients with advanced melanoma, colorectal cancer, and nonsmall-cell lung cancer. 13,14,16 However, some patients with cutaneous melanoma with a low nsSNV burden still derive benefit from checkpoint inhibitors, as do some patients with UV-protected mucosal melanomas, 60 which have a characteristically low nsSNV burden. 61 We analysed three melanoma datasets for which both response and mutational data were available. In two of the three studies, 13,14 comprising a total of 96 patients treated with either anti-PD-1 or anti-CTLA-4 therapy, frameshift indel burden was a better predictor of response than nsSNV burden. In the third study 12 of 100 patients treated with anti-CTLA-4 therapy, the nsSNV burden and frameshift burden were both significantly associated with checkpoint inhibitor response. We note that most of the patients in Van Allen and colleagues' cohort 12 were pretreated and therefore any mutational biomarker assessment in this group might be less reliable. Although nsSNVs contribute greatly towards tumour immunogenicity in heavily mutated tumours, our analyses suggest that frameshift mutations also make a significant contribution relative to their overall low number. The contribution of frameshift indels in low nsSNV burden tumours might be of greater importance still, as illustrated by the fact that frameshift mutations contribute over a third of the neoantigen load in renal clear cell carcinoma. Mutational and checkpoint inhibitor response data were not available for renal clear cell carcinoma, hence we could not establish a direct association between frameshift indels and positive checkpoint inhibitor response. In terms of indirect evidence in renal clear cell carcinoma, we observed an association between the frameshift neoantigens and upregulation of machinery necessary for antigen presentation by the MHC complex and T-cell activation. Furthermore, the CD8-positive T-cell signature in the frameshift neoantigen-high group was closely related to cytolytic activity, suggesting the presence of antitumour effectors that could confer sensitivity to immunotherapy. However, no definitive conclusions can be drawn until checkpoint inhibitor response and indel load is directly investigated in a sufficiently powered series of renal clear cell carcinoma cases. For frameshift neoantigens to contribute to antitumour immunity the mutant peptides must be expressed. Frameshifts cause premature termination codons and the resultant mRNAs can be targeted for NMD. Published analyses 62 of germline samples show that premature termination codons frequently lead to the loss of expression of the variant allele, but that some mutant transcripts escape NMD on the basis of the exact location of the frameshift within a gene. Combined analyses of mutational and expression data from more than 10 000 cancer samples showed that NMD is triggered with variable efficacy, and even when effective might not alter expression because of factors such as short mRNA halflife. 33 RNAseq analysis in renal clear cell carcinoma cases showed a minimal change in mRNA transcript levels for frameshift indel-mutated tumours, suggesting NMD is operating on a subset of transcripts, as expected. In this context, the strongly hypoxic microenvironment that characterises renal clear cell carcinomas might be a contributing factor, with evidence showing NMD inhibition in cells subject to hypoxia and other perturbed microenvironmental conditions. 63 Clonal frameshift mutations could be an important source of tumour-specific antigens for personalised immunotherapy strategies, including peptide vaccines and adoptive cell therapy. Tumour-reactive T cells recognising a frameshifted product of the CDKN2A tumour-suppressor gene were reported to mediate a potent in-vivo response in melanoma. 64 In microsatellite instability-high colorectal cancer, frameshift neopeptidespecific cytotoxic T-cell responses were observed in patients harbouring those mutations. 65 Cytotoxic T-lymphocyte responses to frameshifted proteins have been detected in healthy hereditary non-polyposis colorectal cancer-mutation carriers, raising the possibility of protective immunosurveillance in this population. 66 Frameshift neoantigens are particularly pertinent in the context of mismatch repair-deficiency, which is a pancancer event, and crucially, frameshifts commonly occurring in microsatellite instability-high colorectal carcinomas have been shown to generate NMD-resistant transcripts. 67 In support of this, in a study 68 of PD-1 blockade in patients with microsatellite instability-high tumours from various cancer subtypes, functional analyses in a responding patient showed in-vivo expansion of frameshift neoantigen-specific T-cell clones. Frameshift neoantigens provide a unique opportunity to target common tumour-suppressor genes, such as such as TP53 and BAP1, 69 and their founder status also enriches for clonal neoantigens. Acknowledging the qualitative difference in the neoantigen burden of renal clear cell carcinoma might be integral for optimising responses to checkpoint inhibitors. Neoantigens derived from driver mutations elicit profound T-cell exhaustion via chronic antigen stimulation, generating T-cell pools refractory to immune therapy. 70 Thus, early administration of checkpoint blockade might further improve clinical benefit in cancers with particularly antigenic mutations such as renal clear cell carcinoma. It is also noteworthy that a high differential affinity between wild-type and mutant peptides is indicative of enhanced tumour protection in vivo. 71 The enrichment of mutant-only binders by nine times in neoantigens derived from frameshift mutations relative to nsSNVs might therefore partly explain the predictive power of frameshift neoantigens in checkpoint inhibitor responses. A widely recognised challenge in bioinformatics is indel variant calling, due to the inherent nature of shortread sequencing technology; however, accurate indel calling can be achieved within both a research and clinical context with strict quality control procedures. 72 While strict quality control procedures can ensure a low false-positive rate, as a consequence the true rate of indel mutations might be underestimated. In conclusion, we report that kidney cancers carry the highest pan-cancer burden of indel mutations. Futhermore, our data suggest that frameshift indels are a highly immunogenic mutational class; triggering an increased quantity of neoantigens and greater mutant binding specificity. Collectively, these data might reconcile the outlier nature of immunotherapy responses in renal clear cell carcinoma, highlighting frameshift indels as a potential biomarker of checkpoint inhibitor response and supporting the targeting of clonal frameshift indels by both vaccine and cell therapy approaches. |
Aleksandra Kasuba
Aleksandra Kasuba (1923 – March 5, 2019) was a Lithuanian-American environmental artist.
Kasuba studied sculpture in her native country before emigrating to the United States with her husband Vytautas Kašuba in 1947, having spent the previous two years in Germany as a refugee. Much of her work, in materials such as marble and brick, is abstract and architectural in nature, and is fully integrated into nearby buildings. Examples may be seen at the Rochester Institute of Technology; Lincoln Hospital in the Bronx; the Bank of California Building in Portland, Oregon; the headquarters of the Container Corporation of America in Chicago; and the plaza in front of the Old Post Office Pavilion, today the Trump International Hotel Washington, D.C. She also produced a design for the Amherst Street station of Buffalo Metro Rail. In addition to her sculptural work, she has received architectural awards for designs made of stretched fabric. Kasuba has lived in New York and New Mexico during her career. A collection of her papers is currently held by the Archives of American Art of the Smithsonian Institution. She was the subject of a retrospective at the National Art Gallery in Vilnius in 2015. |
Con: Preoperative autologous donation has no role in cardiac surgery. THE TRAGEDY OF the 1980s and 1990s caused by viral transmission in blood products has been responsible for efforts to reduce the amount of allogeneic blood products used in both surgical and medical patients. In his final report on the Blood System in Canada, Krever1 recommended appropriate use of, and alternatives to, blood components and blood products. Over the last 2 decades, there have been institutional, regional, and national attempts to prevent allogeneic transfusions. Cardiac surgery is responsible for approximately 20% of allogeneic transfusions; in the last 20 years, the transfusion rate in cardiac surgery has dropped from nearly 100% to 27% to 92% depending on the institution.2 Contributing factors to this decrease include shorter bypass times, improved surgical techniques, bone marrow stimulation, antifibrinolytics, lowering of the transfusion trigger, and the use of autologous blood products. Autologous practices include recovery of shed blood, acute normovolemic hemodilution (ANH), and preoperative autologous donation (PAD). Although some of these techniques have been effective, many, including PAD, remain controversial. |
<reponame>zdrapela/kie-tools<filename>packages/dashbuilder/dashbuilder-runtime-parent/dashbuilder-runtime-client/src/main/java/org/dashbuilder/client/external/SupportedMimeType.java
/*
* Copyright 2022 Red Hat, Inc. and/or its affiliates.
*
* 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.dashbuilder.client.external;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
enum SupportedMimeType {
// JSON is a no-op transformer
JSON("application/json", "json", v -> v),
CSV("text/csv", "csv", new CSVParser()),
// metrics is only matched by URL, otherwise it takes precedence on CSV when it is text/plain
METRIC("", "metrics", new MetricsParser());
String mimeType;
String extension;
Function<String, String> tranformer;
private SupportedMimeType(String type, String extension, Function<String, String> tranformer) {
this.mimeType = type;
this.extension = extension;
this.tranformer = tranformer;
}
public String getMimeType() {
return mimeType;
}
public String getExtension() {
return extension;
}
public static Optional<SupportedMimeType> byMimeTypeOrUrl(String mimeType, String url) {
// not working with GWT...
//return byMimeType(mimeType).or(() -> byUrl(url));
var op = byMimeType(mimeType);
if (!op.isPresent()) {
op = byUrl(url);
}
return op;
}
public static Optional<SupportedMimeType> byMimeType(String mimeType) {
if (mimeType == null || mimeType.trim().isEmpty()) {
return Optional.empty();
}
return Arrays.stream(values())
.filter(t -> !t.getMimeType().isEmpty() && mimeType.toLowerCase().startsWith(t.getMimeType()))
.findFirst();
}
public static Optional<SupportedMimeType> byUrl(String url) {
if (url == null || url.trim().isEmpty()) {
return Optional.empty();
}
return Arrays.stream(values())
.filter(t -> url.toLowerCase().endsWith(t.getExtension()))
.findFirst();
}
}
|
/*
* Copyright (c) 2019 by <NAME>.
*
* The author 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 com.simiacryptus.mindseye.art.models;
import com.simiacryptus.mindseye.art.VisionPipeline;
import com.simiacryptus.mindseye.art.VisionPipelineLayer;
import com.simiacryptus.mindseye.art.util.ImageArtUtil;
import com.simiacryptus.mindseye.lang.Layer;
import com.simiacryptus.mindseye.network.PipelineNetwork;
import com.simiacryptus.ref.wrappers.RefMap;
import com.simiacryptus.tensorflow.ImageNetworkPipeline;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* The enum Inception 5 h.
*/
public enum Inception5H implements VisionPipelineLayer {
/**
* Inc 5 h 1 a inception 5 h.
*/
Inc5H_1a("conv2d0"),
/**
* Inc 5 h 2 a inception 5 h.
*/
Inc5H_2a("localresponsenorm1"),
/**
* Inc 5 h 3 a inception 5 h.
*/
Inc5H_3a("mixed3a"),
/**
* Inc 5 h 3 b inception 5 h.
*/
Inc5H_3b("mixed3b"),
/**
* Inc 5 h 4 a inception 5 h.
*/
Inc5H_4a("mixed4a"),
/**
* Inc 5 h 4 b inception 5 h.
*/
Inc5H_4b("mixed4b"),
/**
* Inc 5 h 4 c inception 5 h.
*/
Inc5H_4c("mixed4c"),
/**
* Inc 5 h 4 d inception 5 h.
*/
Inc5H_4d("mixed4d"),
/**
* Inc 5 h 4 e inception 5 h.
*/
Inc5H_4e("mixed4e"),
/**
* Inc 5 h 5 a inception 5 h.
*/
Inc5H_5a("mixed5a"),
/**
* Inc 5 h 5 b inception 5 h.
*/
Inc5H_5b("mixed5b");
@Nullable
private static transient RefMap<String, PipelineNetwork> inception5h = null;
@Nullable
private static volatile VisionPipeline visionPipeline = null;
private final String layerId;
Inception5H(String layerId) {
this.layerId = layerId;
}
@Nonnull
@Override
public PipelineNetwork getLayer() {
RefMap<String, PipelineNetwork> layerMap = layerMap();
PipelineNetwork network = layerMap.get(this.layerId);
layerMap.freeRef();
Layer layer = network.copyPipeline();
network.freeRef();
layer.setName(name());
return (PipelineNetwork) layer;
}
@Nonnull
@Override
public VisionPipeline getPipeline() {
return getVisionPipeline();
}
@Nonnull
@Override
public String getPipelineName() {
VisionPipeline visionPipeline = getVisionPipeline();
String name = visionPipeline.name;
visionPipeline.freeRef();
return name;
}
/**
* Gets vision pipeline.
*
* @return the vision pipeline
*/
@Nullable
public static VisionPipeline getVisionPipeline() {
if (null == visionPipeline) {
synchronized (Inception5H.class) {
if (null == visionPipeline) {
visionPipeline = new VisionPipeline(Inception5H.class.getSimpleName(), Inception5H.values());
}
}
}
return visionPipeline.addRef();
}
/**
* Layer map ref map.
*
* @return the ref map
*/
@Nonnull
public static RefMap<String, PipelineNetwork> layerMap() {
if (null == inception5h) {
synchronized (Inception5H.class) {
if (null == inception5h) {
inception5h = ImageArtUtil.convertPipeline(
ImageNetworkPipeline.loadGraphZip(
"https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip",
"tensorflow_inception_graph.pb"),
"conv2d0", "localresponsenorm1", "mixed3a", "mixed3b", "mixed4a", "mixed4b", "mixed4c", "mixed4d",
"mixed4e", "mixed5a", "mixed5b");
}
}
}
return inception5h.addRef();
}
}
|
from collections import deque
n=int(input())
s=input()
ans=deque(s)
cnt=0
for i in range(n):
if (cnt==0)and(s[i]==')'):
ans.appendleft('(')
elif (cnt!=0)and(s[i]==')'):
cnt-=1
pass
elif s[i]=='(':
cnt+=1
if cnt>0:
ans.append(')'*cnt)
print(''.join(ans)) |
import * as React from "react"
import { render } from "react-dom"
import { v4 as uuid } from "uuid"
import Cookies from "js-cookie"
import { App } from "./components/App"
import { Op } from "./lib/messages"
const getUserId = (): string => {
let userId = Cookies.get("user_id")
if (!userId) {
userId = uuid()
Cookies.set("user_id", userId)
}
return userId
}
const userId = getUserId()
const worker = new Worker("./workers/game.ts")
const sendMessage = (op: Op, data?: object) =>
worker.postMessage({ userId, op, data })
window.addEventListener("beforeunload", () => {
sendMessage(Op.BECOME_INACTIVE)
})
render(
<App worker={worker} sendMessage={sendMessage} userId={userId} />,
document.getElementById("root")
)
|
Thioester-Containing Benzoate Derivatives with -Glucosidase Inhibitory Activity from the Deep-Sea-Derived Fungus Talaromyces indigoticus FS688 Eurothiocins CH (16), six unusual thioester-containing benzoate derivatives, were isolated from the deep-sea-derived fungus Talaromyces indigoticus FS688 together with a known analogue eurothiocin A. Their structures were elucidated through spectroscopic analysis and the absolute configurations were determined by X-ray diffraction and ECD calculations. In addition, compound 1 exhibited significant inhibitory activity against -glucosidase with an IC50 value of 5.4 M, while compounds 4 and 5 showed moderate effects with IC50 values of 33.6 and 72.1 M, respectively. A preliminary structureactivity relationship is discussed and a docking analysis was performed. Introduction Organosulfur compounds, referring to sulfur-containing low-molecular-weight compounds including thiols, thioesters, and sulfoxides, continue to be a research hotspot in the field of organic chemistry due to their unique chemical properties and reactive functions. On the one hand, sulfur is an essential element in primary metabolism from bacteria and fungi to plants and animals; for example, the cysteine is the most important amino acid in protein structures and in protein-folding pathways. On the other hand, sulfur-containing secondary metabolites produced by plant, animals or microorganisms always exhibit significant biological activities such as anti-inflammatory, anticancer and plant defense. Several clinical drugs developed from natural products (NPs) are organosulfur compounds such as penicillin, cephalosporine and trabectedin (ET-743). However, sulfur-containing NPs are still relatively rare when compared to other types of NPs, and the biological significance and biosynthetic mechanisms of sulfur-containing NPs have been investigated with limited progress. Since sulfur is the second most common non-metallic element, after chlorine in sea water, sulfur-containing metabolites are widely produced by different marine organisms. Marine microorganisms are potential and reproducible sources of new bioactive sulfurcontaining NPs, and have attracted research interest worldwide in recent years. Since the first sulfur-containing metabolite, gliovictin, was discovered from marine deuteromycete Asteromyces cruciatus, 484 non-sulfated organosulfur NPs have been isolated from marine microorganisms as of the end of 2020 and fungi contributed the most significant number of the new compounds (43%), which were reviewed by Shao C.-L. et al.. Mar. Drugs 2022, 20, 33 2 of 10 Thus, it could be concluded that marine fungi have become the most productive marine microorganisms of sulfur-containing NPs. Deep-sea-derived fungi are a special group of microorganisms collected from sediment or water at a depth of over 1000 m. Due to their potential ability to produce novel and bioactive natural products promoted by the extreme environment, deep-sea-derived fungi have attracted considerable attention from both natural product and medicinal chemists. In the course of searching for bioactive metabolites from deep-sea-derived fungi, Talaromyces indigoticus FS688-isolated from the South China Sea-was investigated and seven unusual thioester-containing benzoate derivatives were isolated ( Figure 1). Herein, the details of the isolation, the structure identification and the biological evaluation of compounds 1-7 are discussed. Mar. Drugs 2022, 20, x 2 of 11 the first sulfur-containing metabolite, gliovictin, was discovered from marine deuteromycete Asteromyces cruciatus, 484 non-sulfated organosulfur NPs have been isolated from marine microorganisms as of the end of 2020 and fungi contributed the most significant number of the new compounds (43%), which were reviewed by Shao C.-L. et al.. Thus, it could be concluded that marine fungi have become the most productive marine microorganisms of sulfur-containing NPs. Deep-sea-derived fungi are a special group of microorganisms collected from sediment or water at a depth of over 1000 m. Due to their potential ability to produce novel and bioactive natural products promoted by the extreme environment, deep-sea-derived fungi have attracted considerable attention from both natural product and medicinal chemists. In the course of searching for bioactive metabolites from deep-sea-derived fungi, Talaromyces indigoticus FS688-isolated from the South China Sea-was investigated and seven unusual thioester-containing benzoate derivatives were isolated ( Figure 1). Herein, the details of the isolation, the structure identification and the biological evaluation of compounds 1-7 are discussed. Structure Identification The fermented substrate of the fungus Talaromyces indigoticus FS688 was extracted with ethyl acetate three times and then concentrated under reduced pressure to give a brown oil, which was further subjected to repeated silica gel with gradient elution followed by Sephdex-20 and semi-preparative HPLC purification to afford compounds 1−7 ( Figure 1). Eurothiocin C was obtained as a colorless oil. The molecular formula was deduced to be C15H19O5S on the basis of the deprotonated quasi molecular ion peak at m/z 311.0964 -and the characteristic 34 S-containing isotope ion peak at m/z 313.0938 in a 20:1 ratio with the 32 S-containing ion peak from the HRESIMS spectrum. The 1 H NMR spectrum (Table 1) showed the signals of a chelating proton at H 11.14 (7-OH), five singlet methyls including a methoxy group at H 3.78 (Me-18), and intercoupled methylene and methine groups at H 3.17/3.09 (H2-9) and H 4.78 (H-10), respectively. The 13 C NMR data resolved 15 resonances composed of six aromatic carbons, eight aliphatic carbons and a carbonyl carbon (C 197.8), suggesting that a fully substituted benzene ring should be contained in compound 1. By comparing the 1D NMR data to that of the known compound eurothiocin A, indicated that compound 1 was a methoxy additive product of eurothiocin A. Structure Identification The fermented substrate of the fungus Talaromyces indigoticus FS688 was extracted with ethyl acetate three times and then concentrated under reduced pressure to give a brown oil, which was further subjected to repeated silica gel with gradient elution followed by Sephdex-20 and semi-preparative HPLC purification to afford compounds 1−7 ( Figure 1). Eurothiocin C was obtained as a colorless oil. The molecular formula was deduced to be C 15 H 19 O 5 S on the basis of the deprotonated quasi molecular ion peak at m/z 311.0964 − and the characteristic 34 S-containing isotope ion peak at m/z 313.0938 − in a 20:1 ratio with the 32 S-containing ion peak from the HRESIMS spectrum. The 1 H NMR spectrum (Table 1) showed the signals of a chelating proton at H 11.14 (7-OH), five singlet methyls including a methoxy group at H 3.78 (Me-18), and intercoupled methylene and methine groups at H 3.17/3.09 (H 2 -9) and H 4.78 (H-10), respectively. The 13 C NMR data resolved 15 resonances composed of six aromatic carbons, eight aliphatic carbons and a carbonyl carbon ( C 197.8), suggesting that a fully substituted benzene ring should be contained in compound 1. By comparing the 1D NMR data to that of the known compound eurothiocin A, indicated that compound 1 was a methoxy additive product of eurothiocin A. The complete structure was elucidated by analysis of 2D NMR data ( Figure 2). The COSY correlations of H 2 -9/H-10 and the HMBC correlations from H 3 -12/H 3 -13 to C-10/C-11 indicated the presence of an oxygenated isopentenyl unit (C-9 to C-13), which was further connected to C-6 of the benzene ring based on the correlations from H 2 -9 to C-5, C-6 and C-7. A benzofuran core was constructed by the key HMBC correlations from H-10 to C-5. The chelating proton at 7-OH displayed HMBC correlations to C-2, C-6 and C-7, which suggested that the carbonyl group should be linked to C-2 of the benzene ring to form an intramolecular hydrogen bond. Finally, the methyl thioester moiety was deduced by the correlations from H 3 -14 to C-1 and the characteristic chemical shifts of C-1 ( C 197.8), while the locations of Me-8 and 4-OMe were evaluated by the cross-peaks from H 3 -8 to C-2/C-3/C-4 and from 4-OMe to C-4. Hence, the planar structure of compound 1 was elucidated to be a sulfur-containing benzofuran derivative as shown. The complete structure was elucidated by analysis of 2D NMR data ( Figure 2). The COSY correlations of H2-9/H-10 and the HMBC correlations from H3-12/H3-13 to C-10/C-11 indicated the presence of an oxygenated isopentenyl unit (C-9 to C-13), which was further connected to C-6 of the benzene ring based on the correlations from H2-9 to C-5, C-6 and C-7. A benzofuran core was constructed by the key HMBC correlations from H-10 to C-5. The chelating proton at 7-OH displayed HMBC correlations to C-2, C-6 and C-7, which suggested that the carbonyl group should be linked to C-2 of the benzene ring to form an intramolecular hydrogen bond. Finally, the methyl thioester moiety was deduced by the correlations from H3-14 to C-1 and the characteristic chemical shifts of C-1 (C 197.8), while the locations of Me-8 and 4-OMe were evaluated by the cross-peaks from H3-8 to C-2/C-3/C-4 and from 4-OMe to C-4. Hence, the planar structure of compound 1 was elucidated to be a sulfur-containing benzofuran derivative as shown. Because only one chiral center was detected in 1, the absolute configuration could be directly determined by comparing the theoretical ECD spectrum with the experimental Because only one chiral center was detected in 1, the absolute configuration could be directly determined by comparing the theoretical ECD spectrum with the experimental plot. The calculated ECD spectrum of 10R-1 at the PBE1PBE/tzvp level exhibited an excellent fit to the experimental plot ( Figure 3), assigning the 10R configuration. Eurothiocin D, obtained as a colorless oil, showed a similar 1D NMR spectrum ( Table 2) to that of eurothiocin A. The main differences observed were a series of additional proton signals from H 3.30 to 5.20 including an anomeric oxymethine at H 5.20 and six additional carbon resonances from C 61 to 94, suggesting that a glucoside moiety should be constructed in compound 2. The COSY correlations of H-1 /H-2 /H-3 /H-4 /H-5 /H 2 -6 confirmed the existence of the glucoside; meanwhile, the HMBC correlations ( Figure 2) from H-1 to C-11 further revealed the location of the glucoside at C-11. plot. The calculated ECD spectrum of 10R-1 at the PBE1PBE/tzvp level exhibited an excellent fit to the experimental plot ( Figure 3), assigning the 10R configuration. Eurothiocin D, obtained as a colorless oil, showed a similar 1D NMR spectrum ( Table 2) The deshielded anomeric proton observed at H 5.20 combined with the small 3 J1',2' (3.8 Hz) indicated an -glucopyranosyl linkage. Finally, the crystal of compound 2 was obtained and the X-ray diffraction analysis confirmed a -d-glucopyranosyl unit at C-11 ( Figure 4). The deshielded anomeric proton observed at H 5.20 combined with the small 3 J 1,2 (3.8 Hz) indicated an -glucopyranosyl linkage. Finally, the crystal of compound 2 was obtained and the X-ray diffraction analysis confirmed a -d-glucopyranosyl unit at C-11 ( Figure 4). Eurothiocin E was isolated as a colorless oil and gave the molecular formula C 14 H 17 O 3 S deduced by the quasi molecular ion peak at m/z 265.0900 − as well as the 34 S-containing characteristic isotope ion peak at m/z 267.0879 − in a 20:1 ratio with the 32 S-containing ion peak from the HRESIMS spectrum. The 1 H NMR spectrum (Table 1) The COSY correlation (Figure 2) of H2-9/H-10 combined with the HMBC cross-peaks from H3-12/H3-13 to C-10/C-11 constructed an isopentenyl unit (C-9 to C-13), which was connected to C-6 of the benzene ring based on the correlations from H2-9 to C-5/C-6/C-7. The locations of the carbonyl at C-1 and the chelating hydroxyl groups were evaluated by the HMBC correlations from 7-OH to C-2, C-6 and C-7. A similar methyl thioester moiety to that of eurothiocin C/D was deduced by the correlations from H3-14 to C-1 and the characteristic chemical shifts of C-1 (C 198.2). All of the above evidence indicated that compound 3 was a ring-opening precursor of eurothiocin A. Finally, the HMBC correlation ( Figure 2) from H3-8 to C-2/C-3/C-4 and the deshielded chemical shift of C-5 (C 158.9) revealed a methyl and a hydroxy group at C-8 and C-5, respectively. Thus, the gross structure of compound 3 was established to be an isopentenyl-substituted benzoate thioester derivative. Both eurothiocins F and G exhibited similar 1D NMR spectra (Tables 2 and 3) to that of compound 3, which suggested that they are analogues containing a similar isopentenyl-substituted benzoate thioester core. Their HRESIMS spectra exhibited 34 S: 32 S (20:1) isotope ion peaks. On the one hand, the main differences in compound 4 were that the methyl group (H 1.74) was absent and an additional hydroxymethyl group at H 3.98/C 67.7 was detected, which indicated that Me-12 was oxygenated. On the other hand, in the 1D NMR spectrum of compound 5, the signals of the tri-substituted double bond ( 10 ) were absent and the olefin proton was transferred to a methylene (H 3.98/C 67.7), suggesting that the 10 was hydrolyzed. Further analysis of 2D NMR spectra (Figure 2) constructed the structures of both compound 4 and 5. The geometry of the 10 in compound 4 was deduced by the NOESY correlation ( Figure S38) between H-10 and H2-12; meanwhile, the structure of compound 5 was confirmed by X-ray diffraction analysis (Figure 4). Eurothiocin H was obtained as a colorless powder, the molecular formula of which was deduced to be C10H11O3S based on the HRESIMS data exhibiting a quasi mo- The COSY correlation (Figure 2) of H 2 -9/H-10 combined with the HMBC cross-peaks from H 3 -12/H 3 -13 to C-10/C-11 constructed an isopentenyl unit (C-9 to C-13), which was connected to C-6 of the benzene ring based on the correlations from H 2 -9 to C-5/C-6/C-7. The locations of the carbonyl at C-1 and the chelating hydroxyl groups were evaluated by the HMBC correlations from 7-OH to C-2, C-6 and C-7. A similar methyl thioester moiety to that of eurothiocin C/D was deduced by the correlations from H 3 -14 to C-1 and the characteristic chemical shifts of C-1 ( C 198.2). All of the above evidence indicated that compound 3 was a ring-opening precursor of eurothiocin A. Finally, the HMBC correlation ( Figure 2) from H 3 -8 to C-2/C-3/C-4 and the deshielded chemical shift of C-5 ( C 158.9) revealed a methyl and a hydroxy group at C-8 and C-5, respectively. Thus, the gross structure of compound 3 was established to be an isopentenyl-substituted benzoate thioester derivative. Both eurothiocins F and G exhibited similar 1D NMR spectra (Tables 2 and 3) to that of compound 3, which suggested that they are analogues containing a similar isopentenyl-substituted benzoate thioester core. Their HRESIMS spectra exhibited 34 S: 32 S (20:1) isotope ion peaks. On the one hand, the main differences in compound 4 were that the methyl group ( H 1.74) was absent and an additional hydroxymethyl group at H 3.98/ C 67.7 was detected, which indicated that Me-12 was oxygenated. On the other hand, in the 1D NMR spectrum of compound 5, the signals of the tri-substituted double bond (∆ 10 ) were absent and the olefin proton was transferred to a methylene ( H 3.98/ C 67.7), suggesting that the ∆ 10 was hydrolyzed. Further analysis of 2D NMR spectra ( Figure 2) constructed the structures of both compound 4 and 5. The geometry of the ∆ 10 in compound 4 was deduced by the NOESY correlation ( Figure S38) between H-10 and H 2 -12; meanwhile, the structure of compound 5 was confirmed by X-ray diffraction analysis ( Figure 4). Eurothiocin H was obtained as a colorless powder, the molecular formula of which was deduced to be C 10 H 11 O 3 S based on the HRESIMS data exhibiting a quasi molecular ion peak at m/z 211.0435 − and the 34 S-containing isotope ion peak at m/z 213.0412 −. The methyl thioester moiety was evaluated by the characteristic methyl signals at H 2.46/ C 12.6 and the carbonyl carbon at C 195.2. A set of meta-coupled aromatic protons at H 6.24/ H 6.27 detected in the 1 H NMR spectrum and six aromatic carbon signals in 13 C NMR revealed a benzoate thioester core in 6. The HMBC correlations from H 3 -8 to C-2/C-3/C-4, from H 3 -9 to C-1, from H 3 -10 to C-7 and from H-4/H-6 to C-2/C-5 confirmed the complete structure. To the best of our knowledge, thioester moieties are the rarest in marine microorganisms and only 12 compounds have been discovered to date, of which seven are produced by bacteria (suncheonosides A-D ; nitrosporeusines A-B ; thiocoraline ), two are produced by cyanobacteria (largazole and thiopalmyrone ) and the others were isolated from marine mollusk-derived fungi (Eurothiocins A-B and N-((3R,4S)-4methyl-2-oxotetrahydrothiophen-3-yl)acetamide ). This is the first report of thioestercontaining NPs isolated from the deep-sea-derived fungus. In general, it is recognized that glutathione is a direct donor of the sulfur atom in sulfur-containing NPs from plants or bacteria. However, how the sulfur is introduced in the biosynthesis of metabolites from fungi is still unknown. A further biosynthetic investigation will be carried out in the future to understand the biosynthesis of the thioester moieties in eurothiocins. Bioassays and Molecular Docking The previously reported bioactivity screening results indicated that eurothiocin A is a potential -glucosidase inhibitor. Thus, the in vitro -glucosidase inhibitory activities of eurothiocins C-H were evaluated (Table 4). Compound 2 exhibited the most significant inhibitory effect with an IC 50 value of 5.4 M, while compounds 4 and 5 showed moderate activities with IC 50 values of 33.6 and 72.1 M, respectively. Further, compounds 1, 3 and 6 only displayed weak inhibitory effects at a concentration of 100 M. The strong inhibitory effect of compound 2 might be contributed to by -d-glucopyranosyl unit substitution at C-11, which could make it easy to interact with the enzyme. By comparing the compound with the structures and bioactivities of compounds 3-5, it could be concluded that a hydrophilic terminal of the isopentenyl group at C-6 played an important role in inhibiting -glucosidase. In order to predict the binding mechanism, a docking analysis of the reaction between -glucosidase and the active compounds was performed through Autodock 4.2 ( Figure 5). The protein crystallized structure of -glucosidase from Saccharomyces cerevisiae was downloaded from the RSCB Protein Data Bank (pdb: 3A4A). The docking results indicated that compounds 2, 4 and 5 bound at the same bioactive site, mainly containing the active residues Asp215, Val216, Gly217 or Ser218, which was reported by Yamamoto et al. previously. Moreover, the hydrogen bonds between the 2'-OH of 2/12-OH of 4/11-OH of compound 5 and the residues in the site further demonstrated that the glucopyranosyl at C-11 or the hydrophilic terminal of the isopentenyl group might be the key bioactive function groups. General Experimental Procedures An Anton Paar MCP-500 (Anton Paar, Graz, Austria) and a Jasco 820 spectropolarimeter were used to measure the circular dichroism (ECD) and the UV spectra, respectively. ECD and UV spectra were recorded at the range of 200-400 nm under N2 gas production. IR spectra were recorded on a Shimadzu IR Affinity-1 spectrophotometer. All the NMR spectra were measured on a 600 MHz Bruker Avance-III HD spectrometer and the tetramethylsilane was used as an internal standard. HR-ESI-MS was measured on a Bruker maXis high-resolution mass spectrometer. A Shimadzu LC-20 AT (equipped with an SPD-M20A PDA detector) was used for the preparative separations. The ACE 5 PFP-C18 column (250 10.0 mm, 5 m, 12 nm) was used for semi-preparative HPLC separation and the CHIRAL-MD -RH column (250 10.0 mm, 5 m) was used for chiral separation General Experimental Procedures An Anton Paar MCP-500 (Anton Paar, Graz, Austria) and a Jasco 820 spectropolarimeter were used to measure the circular dichroism (ECD) and the UV spectra, respectively. ECD and UV spectra were recorded at the range of 200-400 nm under N 2 gas production. IR spectra were recorded on a Shimadzu IR Affinity-1 spectrophotometer. All the NMR spectra were measured on a 600 MHz Bruker Avance-III HD spectrometer and the tetramethylsilane was used as an internal standard. HR-ESI-MS was measured on a Bruker maXis high-resolution mass spectrometer. A Shimadzu LC-20 AT (equipped with an SPD-M20A PDA detector) was used for the preparative separations. The ACE 5 PFP-C 18 column (250 10.0 mm, 5 m, 12 nm) was used for semi-preparative HPLC separation and the CHIRAL-MD -RH column (250 10.0 mm, 5 m) was used for chiral separation (Guangzhou FLM Scientific Instrument Co., Ltd, Guangzhou, China). The commercial silica gel (SiO 2 ; 200-300 mesh; Qingdao Marine Chemical Plant, Qingdao, China) and Sephadex LH-20 gel (GE Healthcare Bio-Sciences ABSE-751, Uppsala, Sweden) were used for column chromatography. All solvents were of analytical grade (Guangzhou Chemical Regents Company, Ltd., Guangzhou, China). The natural sea salt was purchased from Guangdong Yueyan saltern. The -glucosidase from Saccharomyces cerevisiae and p-nitrophenyl--dglucopyranoside (p-NPG) used in bioassays were purchased from Sigma-Aldrich (St. Louis, MO, USA). Fungal Material The fungal strain FS688 was identified to be Talaromyces indigoticus, which was collected from deep-sea sediment in the South China Sea (118 Eurothiocin C Crystal diffraction data of compound 2: Data were collected on an Agilent Xcalibur Nova single-crystal diffractometer using Cu K radiation. The crystal structure was refined by full-matrix least-squares calculation with the SHELXT. Crystallographic data have been Details of Quantum Chemical Calculations Spartan'14 software (Wavefunction Inc.) and the Gaussian 09 program were used for the Merck molecular force field (MMFF) and DFT/TD-DFT calculations, respectively. Conformers with an energy window lower the 10 kcal mol −1 from MMFF calculations were generated and re-optimized at the b3lyp/6-31+g(d,p) level, and the frequency calculations were carried out at the same level to estimate their relative thermal free energy (∆G) at 298.15 K. Finally, conformers with the Boltzmann distribution over 5% were chosen for energy calculations at the b3lyp/6-311+g(d,p) level (rotatory strengths for a total of 20 excited states were calculated). The solvent effects were considered based on the selfconsistent reaction field (SCRF) method with the polarizable continuum model (PCM). The final spectra were generated by the SpecDis program using a Gaussian band shape with a 0.30 eV exponential half-width from dipole-length dipolar and rotational strengths. -Glucosidase Inhibition Assay The method used for the -glucosidase inhibitory activity assay was based on previously reported literature with slight modification. The pre-reaction mixture consisted of 130 L of PBS (100 mM, pH 7.0), 30 L of enzyme (1 U/mL) and 0.5 L of the test compounds at different concentrations. After incubation at 37 C for 10 min, 40 L of pNPG was added and the mixture was further incubated at 37 C for 15 min. Finally, the absorbance was measured at 405 nm on an automatic microplate reader. Acarbose was used as the positive control (IC 50 = 317.2 M). All experiments were carried out in triplicate. Docking Analysis The minimized structure of compound 2 was obtained from X-ray diffraction, while the preferred structures of compounds 4 and 5 were optimized by Spartan'14 software based on the MMFF. The energy grid maps for each atom type in the ligands as well as the electrostatic and de-solvation maps were calculated using the AutoGrid 4.2.6 program. The docking analysis was carried out in Autodock Tools package v1.5.4 (ADT, http:// mgltools.scripps.edu/, 17 December 2021) based on a previously reported method. The docking pose was placed in a grid box of 90 90 90 3 (0.375 of grid spacing) with the protein at the center of the box. The results were analyzed by ADT and the figures were prepared with PyMOL visualization tool (v1.7.4, Schrdinger, New York, NY, USA). |
The North or the South? Early medieval ceramics decorated with a zoned ornament the result of local changes or interregional contacts? The article underlines the need to re-discuss the prevailing views in archaeological literature on the provenance and transformation stages of completely wheel-turned ceramics decorated with zoned ornament. This class of ceramics was used in the Early Middle Ages (for about 100 years) by communities living in the area of southern Greater Poland and the north-eastern part of Lower Silesia. The previous ideas suggesting a close relationship between zoned ceramics and vessels produced in northern Bohemia are reconsidered, with the internal diversity of zoned ceramics being pointed out. We argue that inspiration in ceramics manufacturing came not only from the south (Bohemia), but also from the north (Pomerania) and the west (the middle Elbe region), and that there were also changes that appeared independently of these impulses in the ceramics production of small, native communities. |
<filename>demo/tree_demo6.c
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
typedef struct {
int x[3];
} triple_t;
int comp(triple_t *a, triple_t *b) {
for (int i = 0; i < 3; i++) {
if (a->x[i] < b->x[i]) {
return -1;
}
if (a->x[i] > b->x[i]) {
return 1;
}
}
return 0;
}
#define data_t triple_t
#define prefix trip
#include <tree.h>
#undef prefix
#undef data_t
int main(void) {
srand(time(NULL));
tree_trip_t *t = tree_trip_init();
tree_trip_set_comp(t, comp);
tree_trip_set_value_free(t, free);
int n = 10;
for (int i = 0; i < n; i++) {
triple_t key = {.x[0] = rand(), .x[1] = rand(), .x[2] = rand()};
double *value = malloc(sizeof(double));
*value = (double) rand() / (1 << 15);
tree_trip_insert(t, key, value);
}
void *state;
tree_trip_walk_init(t, &state);
while (state != NULL) {
key_trip_value_t q = tree_trip_walk_next(&state);
printf("%12d %12d %12d %12.4f \n", q.key.x[0], q.key.x[1], q.key.x[2], *(double*)q.value);
}
tree_trip_destroy(&t);
return 0;
}
|
MINNEAPOLIS -- The Minnesota Vikings announced their full training camp schedule on Tuesday afternoon, and fans who travel to Mankato, Minnesota, for the team's 49th camp there will have more opportunities to watch the Vikings practice under the lights.
The team will have three evening practices in Blakeslee Stadium, at 7:30 p.m. CT on July 25, Aug. 2 and Aug. 11. The Vikings had held an evening practice on the first Saturday of August in recent years -- and will still make that their featured event in Mankato -- but they'll add some more work under the lights as they get ready for their first preseason game at TCF Bank Stadium on Aug. 8.
Here is the Vikings' full camp schedule:
Friday, July 25
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Saturday, July 26
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Sunday, July 27
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Monday, July 28
Walk-through: 10:30 - 11:30 a.m.
Practice: 7:30 - 9:30 p.m. (Blakeslee Stadium)
Tuesday, July 29
Players day off
Wednesday, July 30
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Thursday, July 31
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Friday, Aug. 1
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Saturday, Aug. 2
Walk-through: 10:30 - 11:30 a.m.
Practice: 7:30 - 9:30 p.m. (Blakeslee Stadium)
Sunday, Aug. 3
Players day off
Monday, Aug. 4
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Tuesday, Aug. 5
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Wednesday, Aug. 6
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Thursday, Aug. 7
Travel back to Twin Cities
Friday, Aug. 8
Raiders @ Vikings - 7:00 p.m.
Saturday, Aug. 9
Players Day Off
Sunday, Aug. 10
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Monday, Aug. 11
Walk-through: 10:30 - 11:30 a.m.
Practice: 7:30 - 9:30 p.m. (Blakeslee Stadium)
Tuesday, Aug. 12
Players Day Off
Wednesday, Aug. 13
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Thursday, Aug. 14
Walk-through: 10:30 - 11:30 a.m.
Practice: 3:00 - 5:10 p.m.
Friday, Aug. 15
Travel back to Twin Cities
Saturday, Aug. 16
Cardinals @ Vikings - 7:00 p.m. |
<filename>src/app/core/components/notifications/NotificationsPage.tsx
import React, { useCallback, useEffect, useMemo } from 'react'
import useReactRouter from 'use-react-router'
import { useDispatch, useSelector } from 'react-redux'
import { partition, prop } from 'ramda'
import moment from 'moment'
import { makeStyles } from '@material-ui/styles'
import Tabs from 'core/components/tabs/Tabs'
import Tab from 'core/components/tabs/Tab'
import ListTable from 'core/components/listTable/ListTable'
import Text from 'core/elements/text'
import Button from 'core/elements/button'
import { notificationActions, ErrorNotificationType } from 'core/notifications/notificationReducers'
import { cloudProviderTypes } from 'k8s/components/infrastructure/cloudProviders/selectors'
import { capitalizeString } from 'utils/misc'
import { routes } from 'core/utils/routes'
import { typedNotificationsSelector } from './selectors'
import { INotificationsSelector } from './model'
import { GlobalState } from 'k8s/datakeys.model'
import {
renderConnectionStatus,
renderPlatform9ComponentsStatus,
renderApiServerHealth,
} from 'k8s/components/infrastructure/clusters/ClustersListPage'
import SimpleLink from '../SimpleLink'
import NotificationDetails from './notification-details'
const useStyles = makeStyles((theme) => ({
clearButton: {
marginRight: 16,
},
tableCell: {
maxWidth: 150,
maxHeight: 90,
overflow: 'hidden',
wordBreak: 'break-word',
},
}))
const NotificationTableCell = ({ value, route = undefined }) => {
const classes = useStyles()
const content = (
<Text variant="body2" className={classes.tableCell}>
{value || 'N/A'}
</Text>
)
if (!route) {
return content
}
return <SimpleLink src={route}>{content}</SimpleLink>
}
const renderCell = (value) => <NotificationTableCell value={value} />
const renderLinkCell = (value, { id }, notificationType) => (
<NotificationTableCell
value={value}
route={routes.notifications.detail.path({ id, notificationType })}
/>
)
const renderClusterHealthCell = (value) => {
if (!value) return renderCell(value)
const ConnectionStatus = renderConnectionStatus(undefined, value)
const Platform9ComponentsStatus = renderPlatform9ComponentsStatus(undefined, value)
const ApiServerHealth = renderApiServerHealth(undefined, value)
return [ConnectionStatus, Platform9ComponentsStatus, ApiServerHealth]
}
const getColumns = (columns, notificationType) => [
{
id: 'date',
label: 'Date',
render: (value) => moment(value).format('LLL'),
sortWith: (prevDate, nextDate) => (moment(prevDate).isBefore(nextDate) ? 1 : -1),
},
{ id: 'type', label: 'Type' },
{
id: 'title',
label: 'Title',
render: (value, data) => renderLinkCell(value, data, notificationType),
},
{
id: 'message',
label: 'Message',
render: (value, data) => renderLinkCell(value, data, notificationType),
},
...columns,
{ id: 'cluster.name', label: 'Cluster Name', render: renderCell },
{
id: 'cluster.cloudProviderType',
label: 'Cluster Type',
render: (type) => renderCell(cloudProviderTypes[type] || capitalizeString(type)),
},
{ id: 'cluster', label: 'Cluster Health', render: renderClusterHealthCell },
{ id: 'cluster.version', label: 'K8s Version', render: renderCell },
]
const clusterErrorColumns = getColumns(
[
{ id: 'k8sResource', label: 'K8s Resource', render: renderCell },
{ id: 'namespace', label: 'Namespace', render: renderCell },
],
ErrorNotificationType.ClusterError,
)
const pf9EventColumns = getColumns(
[{ id: 'managementApi', label: 'Management Api', render: renderCell }],
ErrorNotificationType.Platform9Event,
)
const NotificationsListView = ({ data, columns, onClear, notificationType, onDelete }) => {
const classes = useStyles()
return (
<ListTable
multiSelection={false}
selectColumns={false}
onDelete={onDelete}
filters={
<Button
onClick={() => onClear(notificationType)}
color="primary"
className={classes.clearButton}
>
Clear All
</Button>
}
batchActions={[
{
icon: 'info-circle',
label: 'Details',
routeTo: ([row]) => routes.notifications.detail.path({ id: row.id, notificationType }),
},
]}
columns={columns}
data={data}
/>
)
}
const NotificationsPage = () => {
const { match, history } = useReactRouter()
const notifications = useSelector(typedNotificationsSelector)
const dispatch = useDispatch()
const [clusterErrors, pf9Events] = useMemo(
() => partition((notification) => notification.isClusterError, notifications),
[notifications],
)
const selectedNotification = useMemo(
() => notifications.find((notification) => notification.id === match.params.id),
[match.params.id, notifications],
)
useEffect(() => {
dispatch(notificationActions.markAsRead())
}, [])
const clearNotifications = useCallback((notificationType) => {
dispatch(notificationActions.clearNotifications(notificationType))
}, [])
const handleDeleteOne = useCallback(([{ id }]) => {
dispatch(notificationActions.clearNotificationById(id))
}, [])
const handleClose = useCallback(() => {
const notificationType = selectedNotification?.isClusterError
? ErrorNotificationType.ClusterError
: ErrorNotificationType.Platform9Event
history.push(routes.notifications.list.path({ notificationType }))
}, [selectedNotification])
return (
<>
{selectedNotification && (
<NotificationDetails notification={selectedNotification} onClose={handleClose} />
)}
<Tabs>
<Tab value={ErrorNotificationType.ClusterError} label="Cluster Errors">
<NotificationsListView
data={clusterErrors}
columns={clusterErrorColumns}
onClear={clearNotifications}
onDelete={handleDeleteOne}
notificationType={ErrorNotificationType.ClusterError}
/>
</Tab>
<Tab value={ErrorNotificationType.Platform9Event} label="Platform9 Events">
<NotificationsListView
data={pf9Events}
columns={pf9EventColumns}
onClear={clearNotifications}
onDelete={handleDeleteOne}
notificationType={ErrorNotificationType.Platform9Event}
/>
</Tab>
</Tabs>
</>
)
}
export default NotificationsPage
|
1. Field of Invention
This disclosure generally relates to processing of semiconductor substrates with a focused laser beam.
2. Related Art
Focused laser beams have found applications in drilling, scribing, and cutting of semiconductor wafers, such as silicon. Marking and scribing of non-semiconductor materials, such as printed circuit boards and product labels are additional common applications of focused laser beams. Micro-electromechanical systems (MEMS) devices are laser machined to provide channels, pockets, and through features (holes) with laser spot sizes down to 5 μm and positioning resolution of 1 μm. Channels and pockets allow the device to flex. All such processes rely on a significant rise in the temperature of the material in a region highly localized at the laser beam point of focus.
The foregoing applications, however, are all, to some degree, destructive, and relate generally to focused laser beams at power densities intended to ablate material. In silicon and related semiconductor and electronic materials, such applications are generally for mechanical results (e.g., dicing, drilling, marking, etc.). Thus, there is a need to provide and control laser beams to achieve processing effects for electronic and or optical device fabrication on semiconductor wafers. |
<reponame>FelixVi/Bedrock<filename>soc/picorv32/test/spi/spi_test.c
#include "stdint.h"
#include "settings.h"
#include "spi.h"
static void test(void)
{
// Send 'Hello' to model0
SPI_SET_DAT_BLOCK( BASE_SPI0, 'H' );
SPI_SET_DAT_BLOCK( BASE_SPI0, 'e' );
SPI_SET_DAT_BLOCK( BASE_SPI0, 'l' );
SPI_SET_DAT_BLOCK( BASE_SPI0, 'l' );
SPI_SET_DAT_BLOCK( BASE_SPI0, 'o' );
// Send 'Hello' to model1
SPI_SET_DAT_BLOCK( BASE_SPI1, 'H' );
SPI_SET_DAT_BLOCK( BASE_SPI1, 'e' );
SPI_SET_DAT_BLOCK( BASE_SPI1, 'l' );
SPI_SET_DAT_BLOCK( BASE_SPI1, 'l' );
SPI_SET_DAT_BLOCK( BASE_SPI1, 'o' );
// read back memory from model0
SPI_SET_DAT_BLOCK( BASE_SPI0, 0x81040000 );
SPI_GET_DAT( BASE_SPI0 );
// read back memory from model1
SPI_SET_DAT_BLOCK( BASE_SPI1, 0x00840000 );
SPI_GET_DAT( BASE_SPI1 );
}
int main(void)
{
// change spi speed of model0 to 2, CPOL=0, CPHA=1, DW=32
SPI_INIT(BASE_SPI0, 0, 0, 0, 1, 0, 32, 1);
// change spi speed of model1 to 4, CPOL=1, CPHA=1, DW=24
SPI_INIT(BASE_SPI1, 0, 0, 1, 1, 0, 24, 4);
test();
// Now do it again with LSB first
// change spi speed of model0 to 2, CPOL=0, CPHA=1, DW=32
SPI_INIT(BASE_SPI0, 0, 0, 0, 1, 1, 32, 1);
// change spi speed of model1 to 4, CPOL=1, CPHA=1, DW=24
SPI_INIT(BASE_SPI1, 0, 0, 1, 1, 1, 24, 4);
test();
return 0;
}
|
// String implements the fmt.Stringer interface.
func (s Status) String() string {
if str, ok := statusStr[s]; ok {
return str
}
return "invalid"
} |
export { AngularModuleStarterModule } from './angular-module-starter.module';
export { AngularModuleStarterService } from './angular-module-starter.service';
|
def project_corns_from_dims(dims, ry, locat, project_mat):
global_corns = global_corners(dims, ry, locat)
proj_points = project_global_corns(global_corns, project_mat)
return proj_points |
# Copyright 2013, Mirantis Inc
#
# 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.
from django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.dashboards.member import views
urlpatterns = patterns('',
#register port
#by ying.zhou
url(r'checkUser/', views.ajaxCheckUser, name='home'),
url(r'checkproject/', views.ajaxCheckProject, name='home'),
url(r'updateUser/', views.ajaxUpdatePassword, name='home'),
url(r'sendEmail/', views.sendEmail, name='home'),
url(r'updateUser/', views.updateUser, name='home'),
url(r'createCode/', views.createCode, name='home'),
url(r'checkCode/', views.checkCode, name='home'),
url(r'sendMsg/', views.sendMsg, name='home'),
url(r'checkMsg/', views.checkMsg, name='home'),
)
|
use crate::command_prelude::*;
use cargo::ops;
use cargo::ops::FetchOptions;
pub fn cli() -> Command {
subcommand("fetch")
.about("Fetch dependencies of a package from the network")
.arg_quiet()
.arg_manifest_path()
.arg_target_triple("Fetch dependencies for the target triple")
.after_help("Run `cargo help fetch` for more detailed information.\n")
}
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
let ws = args.workspace(config)?;
let opts = FetchOptions {
config,
targets: args.targets(),
};
let _ = ops::fetch(&ws, &opts)?;
Ok(())
}
|
Erratum: Where the Blame Lies: Unpacking Groups Into Their Constituent Subgroups Shifts Judgments of Blame in Intergroup Conflict Whom do individuals blame for intergroup conflict? Do people attribute responsibility for intergroup conflict to the in-group or the out-group? Theoretically integrating the literatures on intergroup relations, moral psychology, and judgment and decision-making, we propose that unpacking a group by explicitly describing it in terms of its constituent subgroups increases perceived support for the view that the unpacked group shoulders more of the blame for intergroup conflict. Five preregistered experiments (N = 3,335 adults) found support for this novel hypothesis across three distinct intergroup conflicts: the Israeli-Palestinian conflict, current racial tensions between White people and Black people in the United States, and the gender gap in wages in the United States. Our findings (a) highlight the independent roles that entrenched social identities and cognitive, presentation-based processes play in shaping blame judgments, (b) demonstrate that the effect of unpacking groups generalizes across partisans and nonpartisans, and (c) illustrate how constructing packed versus unpacked sets of potential perpetrators can critically shape where the blame lies. |
V Srivatsa, Fund Manager and EVP, UTI MF, tells ET Now that private sector banks, utilities and pharma are the three spaces he is betting on.
Even the macros seem to be a bit unfavourable, there has been a crude oil price inflation, there is rupee weakness and a lot of global headwinds as far as trade tariffs goes and several other factors. What should ideally be the strategy for investing in a market like this?
There are challenges on the global side whether it is in terms of trade wars happening or general global weakness or even the US hiking rates. On the Indian side, the macros are not looking that great, especially if you look at the qualitative aspect.
We are now in the last year of the current government. With the election coming in, there is likely to be more nervousness in the Indian markets. For the next two three quarters, I really do not see the markets going up in a significant way. In fact, our view is that it will probably be range-bound with a negative bias. Our focus in terms of the current portfolio is to look out for sectors where the valuations are quite reasonable and where there is earnings growth ahead irrespective of the change in government or some of the macro factors that I talked about.
A corollary of what you are saying with a negative bias perspective could also mean that you are not expecting much from this earnings season?
Yes, the earnings season will probably be a different story. You would have some amount of earnings growth because we have had a very low base, especially on the consumption side of the sector like FMCG or pharma or on automobile which was impacted by GST.
Apart from the fact the global oriented sectors say like resources or energy is also expected to do well this quarter. I do not see any issue as far as the results are concerned, I think we would be having a good amount of growth as far as the earnings is concerned but my worry mostly stems on the sentiment side which is bad both from a global and a local perspective.
Also, one needs to keep into mind that the current valuations which are probably 17-18 times one year forward, already factors in a reasonable amount of growth. In this quarter, if we give a 15-20% growth, that may not see a significant level of rerating happening just because we have grown by 10-15% or upwards of 15% after a long time.
What would be some of the stocks that you think are reasonable or are poised to do better once the volatility cools down a bit?
I am looking primarily at three sectors; one is the private sector corporate banking side where I believe a large part of the pain is behind us and also the valuations are extremely reasonable now on a long-term perspective. These banks have the capital to grow for the next three to five years that is the first point that I am making.
Second is utilities. It is a significant overweight in my portfolio. This is also a sector where I see decent growth ahead because this is a proxy to the overall domestic industrial recovery as well as domestic demand and this is one of the very few domestic oriented sectors which is probably trading at very attractive valuations, ignoring the growth that this sector has to offer over the medium term.
Third is pharmaceuticals which has done well of late. Here also we believe that we are in an inflection point where there is going to be some amount of earnings growth, primarily led by the Indian markets which should start seeing growth from now on. |
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
scanner.close();
int stringLength = s.length();
// 1
String sReverse = reverseString(s);
boolean firstCondition = s.equals(sReverse);
// 2
int partLength = (stringLength - 1) / 2;
String sPart = s.substring(0, partLength);
String sPartReverse = reverseString(sPart);
boolean secondCondition = sPart.equals(sPartReverse);
// 3
int otherPartLength = (stringLength + 3) / 2 - 1;
String sOtherPart = s.substring(otherPartLength, stringLength);
boolean thirdCondition = sOtherPart.equals(reverseString(sOtherPart));
String result;
if (firstCondition && secondCondition && thirdCondition)
{
result = "Yes";
}
else
{
result = "No";
}
System.out.println(result);
}
private static String reverseString(String s)
{
return new StringBuilder(s).reverse().toString();
}
} |
<reponame>cbertinato/crossroads
/* server.h
General TCP socket handling, not instrument specific
*/
#ifndef SERVER_H
#define SERVER_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <resolv.h>
#include <pthread.h>
#include <netdb.h>
#include "parse_config.h"
typedef struct {
int sd;
device_config config;
} handler_args;
int create_tcp_socket(int port);
int wait_for_connection(int, void *);
#endif
|
def load_from_disk(cls, path_with_file_name):
file_handler = open(path_with_file_name,'r')
clustering = pickle.load(file_handler)
file_handler.close()
return clustering |
BEREA, Ohio (AP) — Browns owner Jimmy Haslam finally tried the patient approach with his head coach.
Haslam made his fourth coaching change since 2012 by firing Hue Jackson, who won just three of 40 games over two-plus seasons and then lost his job because of a feud with offensive coordinator Todd Haley that went public and threatened to turn a promising season into another one of those Cleveland catastrophes.
Haslam fired Jackson and Haley within hours of each other on Monday, a day after the Browns (2-5-1) lost their 25th consecutive road game — one shy of the NFL record.
As for his poor track record in finding coaches, Haslam offered no excuses.
Defensive coordinator Gregg Williams is Cleveland’s interim coach, and running backs coach Freddie Kitchens will take over for Haley.
Haslam said Williams, who coached Buffalo from 2001-03, was the only in-house candidate considered to finish the season. While Williams has extensive experience and won a Super Bowl, he also has a checkered past. He was suspended by the league for a full season in 2012 for his role in the “Bountygate” scandal that rocked the New Orleans Saints.
Haslam said it’s premature to consider the next coaching hire for the Browns, who are 22-81-1 since he and his wife, Dee, agreed to buy the franchise in 2012.
The main objective now is to get through the season’s second half, beginning with a matchup on Sunday against the high-scoring, Kansas City Chiefs (7-1).
There are already names floating around as potential candidates to be Cleveland’s next coach, including Oklahoma’s Lincoln Riley, who coached Browns quarterback Baker Mayfield in college.
Just three weeks ago, the Browns, who went 0-16 last season under Jackson, appeared to have turned the corner following an overtime win against Baltimore.
But things unraveled quickly, thrust in the wrong direction by a power struggle between Jackson and Haley, who joined Cleveland’s staff this season after six in Pittsburgh. Following a loss at Tampa Bay last week, Jackson aimed blame at Haley by offering to help the team’s offense.
Haley publicly said he wasn’t offended by the remarks. But Jackson’s comments seemed to widen a divide between the coaches, who had disagreed on players getting days off during training camp and whether wide receiver Josh Gordon deserved to start the opener.
In order to salvage the season, Haslam and general manager John Dorsey felt change was necessary.
Without pointing fingers, Dorsey said there’s only one way to stop the in-fighting.
Jackson’s the sixth straight Cleveland coach to be fired following the team’s second game against Pittsburgh. Romeo Crennel, Eric Mangini, Pat Shurmur, Rob Chudzinski and Mike Pettine all met the same demise, but they were let go following the season’s final game.
Haslam wouldn’t get into any specifics about the “‘discord” between Jackson and Haley.
Jackson was hired in 2016 by the Haslams, who stuck by him despite a 1-15 record in his first season and then last season’s debacle. His failures were always explained away with excuses: not enough talent, injuries, bad luck, a disconnection with the front office.
Haslam thought hiring a high-profile coordinator like Haley would help Jackson.
In the end, it was his undoing. |
<filename>smithy-diff/src/main/java/software/amazon/smithy/diff/evaluators/RemovedEntityBinding.java
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.smithy.diff.evaluators;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import software.amazon.smithy.diff.ChangedShape;
import software.amazon.smithy.diff.Differences;
import software.amazon.smithy.model.shapes.EntityShape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.validation.Severity;
import software.amazon.smithy.model.validation.ValidationEvent;
/**
* A meta-validator that checks for the removal of an operation or
* resource binding from a service or resource.
*
* <p>A "RemovedOperationBinding" eventId is used when an operation is
* removed, and a "RemovedResourceBinding" eventId is used when a
* resource is removed.
*/
public class RemovedEntityBinding extends AbstractDiffEvaluator {
private static final String REMOVED_RESOURCE = "RemovedResourceBinding";
private static final String REMOVED_OPERATION = "RemovedOperationBinding";
@Override
public List<ValidationEvent> evaluate(Differences differences) {
List<ValidationEvent> events = new ArrayList<>();
differences.changedShapes(EntityShape.class).forEach(change -> validateOperation(change, events));
return events;
}
private void validateOperation(ChangedShape<EntityShape> change, List<ValidationEvent> events) {
findRemoved(change.getOldShape().getOperations(), change.getNewShape().getOperations())
.forEach(removed -> events.add(createRemovedEvent(REMOVED_OPERATION, change.getNewShape(), removed)));
findRemoved(change.getOldShape().getResources(), change.getNewShape().getResources())
.forEach(removed -> events.add(createRemovedEvent(REMOVED_RESOURCE, change.getNewShape(), removed)));
}
private Set<ShapeId> findRemoved(Set<ShapeId> oldShapes, Set<ShapeId> newShapes) {
Set<ShapeId> removed = new HashSet<>(oldShapes);
removed.removeAll(newShapes);
return removed;
}
private ValidationEvent createRemovedEvent(String eventId, EntityShape entity, ShapeId removedShape) {
String descriptor = eventId.equals(REMOVED_RESOURCE) ? "Resource" : "Operation";
String message = String.format(
"%s binding of `%s` was removed from %s shape, `%s`",
descriptor, removedShape, entity.getType(), entity.getId());
return ValidationEvent.builder()
.eventId(eventId)
.severity(Severity.ERROR)
.shape(entity)
.message(message)
.build();
}
}
|
package main
import (
"encoding/json"
"errors"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/supertokens/supertokens-golang/recipe/session"
"github.com/supertokens/supertokens-golang/recipe/session/sessmodels"
"github.com/supertokens/supertokens-golang/recipe/thirdparty"
"github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels"
"github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword"
"github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels"
"github.com/supertokens/supertokens-golang/supertokens"
)
func main() {
err := supertokens.Init(supertokens.TypeInput{
Supertokens: &supertokens.ConnectionInfo{
ConnectionURI: "https://try.supertokens.io",
},
AppInfo: supertokens.AppInfo{
AppName: "SuperTokens Demo App",
APIDomain: "http://localhost:3001",
WebsiteDomain: "http://localhost:3000",
},
RecipeList: []supertokens.Recipe{
thirdpartyemailpassword.Init(&tpepmodels.TypeInput{
/*
We use different credentials for different platforms when required. For example the redirect URI for Github
is different for Web and mobile. In such a case we can provide multiple providers with different client Ids.
When the frontend makes a request and wants to use a specific clientId, it needs to send the clientId to use in the
request. In the absence of a clientId in the request the SDK uses the default provider, indicated by `isDefault: true`.
When adding multiple providers for the same type (Google, Github etc), make sure to set `isDefault: true`.
*/
Providers: []tpmodels.TypeProvider{
// We have provided you with development keys which you can use for testsing.
// IMPORTANT: Please replace them with your own OAuth keys for production use.
thirdparty.Google(tpmodels.GoogleConfig{
// We use this for websites
IsDefault: true,
ClientID: "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com",
ClientSecret: "<KEY>",
}),
thirdparty.Google(tpmodels.GoogleConfig{
// we use this for mobile apps
ClientID: "1060725074195-c7mgk8p0h27c4428prfuo3lg7ould5o7.apps.googleusercontent.com",
ClientSecret: "", // this is empty because we follow Authorization code grant flow via PKCE for mobile apps (Google doesn't issue a client secret for mobile apps).
}),
thirdparty.Github(tpmodels.GithubConfig{
// We use this for websites
IsDefault: true,
ClientID: "467101b197249757c71f",
ClientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd",
}),
thirdparty.Github(tpmodels.GithubConfig{
// We use this for mobile apps
ClientID: "8a9152860ce869b64c44",
ClientSecret: "<KEY>",
}),
/*
For Apple signin, iOS apps always use the bundle identifier as the client ID when communicating with Apple. Android, Web and other platforms
need to configure a Service ID on the Apple developer dashboard and use that as client ID.
In the example below 4398792-io.supertokens.example.service is the client ID for Web. Android etc and thus we mark it as default. For iOS
the frontend for the demo app sends the clientId in the request which is then used by the SDK.
*/
thirdparty.Apple(tpmodels.AppleConfig{
// For Android and website apps
IsDefault: true,
ClientID: "4398792-io.supertokens.example.service",
ClientSecret: tpmodels.AppleClientSecret{
KeyId: "7M48Y4RYDL",
PrivateKey: "-----<KEY>",
TeamId: "YWQCXGJRJL",
},
}),
thirdparty.Apple(tpmodels.AppleConfig{
// For iOS Apps
ClientID: "4398792-io.supertokens.example",
ClientSecret: tpmodels.AppleClientSecret{
KeyId: "7M48Y4RYDL",
PrivateKey: "-----<KEY>",
TeamId: "YWQCXGJRJL",
},
}),
},
}),
session.Init(nil),
},
})
if err != nil {
panic(err.Error())
}
e := echo.New()
// CORS middleware
e.Use(func(hf echo.HandlerFunc) echo.HandlerFunc {
return echo.HandlerFunc(func(c echo.Context) error {
c.Response().Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
c.Response().Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request().Method == "OPTIONS" {
c.Response().Header().Set("Access-Control-Allow-Headers", strings.Join(append([]string{"Content-Type"}, supertokens.GetAllCORSHeaders()...), ","))
c.Response().Header().Set("Access-Control-Allow-Methods", "*")
c.Response().Write([]byte(""))
return nil
} else {
return hf(c)
}
})
})
// SuperTokens Middleware
e.Use(func(hf echo.HandlerFunc) echo.HandlerFunc {
return echo.HandlerFunc(func(c echo.Context) error {
supertokens.Middleware(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
hf(c)
})).ServeHTTP(c.Response(), c.Request())
return nil
})
})
e.GET("/sessioninfo", sessioninfo, verifySession(nil))
e.Start(":3001")
}
func verifySession(options *sessmodels.VerifySessionOptions) echo.MiddlewareFunc {
return func(hf echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
session.VerifySession(options, func(rw http.ResponseWriter, r *http.Request) {
c.Set("session", session.GetSessionFromRequestContext(r.Context()))
hf(c)
})(c.Response(), c.Request())
return nil
}
}
}
func sessioninfo(c echo.Context) error {
sessionContainer := c.Get("session").(*sessmodels.SessionContainer)
if sessionContainer == nil {
return errors.New("no session found")
}
sessionData, err := sessionContainer.GetSessionData()
if err != nil {
err = supertokens.ErrorHandler(err, c.Request(), c.Response())
if err != nil {
return err
}
return nil
}
c.Response().WriteHeader(200)
c.Response().Header().Add("content-type", "application/json")
bytes, err := json.Marshal(map[string]interface{}{
"sessionHandle": sessionContainer.GetHandle(),
"userId": sessionContainer.GetUserID(),
"accessTokenPayload": sessionContainer.GetAccessTokenPayload(),
"sessionData": sessionData,
})
if err != nil {
c.Response().WriteHeader(500)
c.Response().Write([]byte("error in converting to json"))
} else {
c.Response().Write(bytes)
}
return nil
}
|
Dugan said that the newest video, which was taken at an angle, is believed to be the same man seen in the first because of his general build, clothes, mannerisms and gait. Dugan says the footage was recorded just moments before the latest shooting of 60-year-old Ronald Felton on Tuesday morning.
An FBI SWAT Team joined Tampa police and the Hillsborough County Sheriff’s Office in conducting door-to-door searches in a manhunt for a suspect in a string of homicides.
Police also said they received several more videos and are still going through them. Dugan said he would release more footage as investigators study the videos.
While Dugan refrained from saying that all four killings were committed by the same person, he said that detectives are “very comfortable” in saying that all the incidents are linked.
Detectives still believe the killer lives in the Seminole Heights area.
“Someone has to know who this individual is. We need to know who this person is … we need names,” Dugan urged.
Police continue to try to calm nervous residents and area business owners who are frightened to leave their homes since the shootings began. Dugan reminded the community to stick together when traveling around the area, as all four victims targeted were alone when they died.
Police are asking residents who may have seen anything or have home surveillance cameras to contact them at 813-231-6130. |
Influence of growth media on Escherichia coli cell composition and ceftazidime susceptibility Cell composition and surface properties of Escherichia coli were modified by using various growth media to investigate the role of yet uncharacterized components in ceftazidime susceptibility. An eightfold dilution of Luria broth was used as the basic growth medium and was supplemented with up to 4% phosphate, 5% glucose, or 12% L-glutamate. Decreases in cephaloridine and ceftazidime susceptibility, of two- and eightfold, respectively, were observed only in the glucose-enriched medium. The outer membrane permeability to ceftazidime and cephaloridine was evaluated by crypticity indices. Indices were unchanged under all growth conditions. Fluorometry of whole cells with 1-N-phenylnaphthylamine showed that glucose does not affect the interaction of this hydrophobic probe with the membranes but showed that elevated concentrations of phosphate or glutamate cause a marked increase in cell hydrophobicity, which, in turn, correlates with an increase in the susceptibility of E. coli to nalidixic acid. Growth in phosphate- or glutamate-enriched media caused an augmentation in major phospholipid species and may explain the increased hydrophobicity and susceptibility of E. coli to nalidixic acid. These data showed that E. coli susceptibility to ceftazidime is not influenced by cell surface hydrophobicity and suggested that the contribution of a nonspecific lipophilic diffusion route for entry of ceftazidime into cells is not likely to occur or is distinct from that of more hydrophobic molecules such as nalidixic acid. Finally, the penicillin-binding proteins of the E. coli cells were also investigated. Penicillin-binding protein 8 was only markedly labeled with 125I-penicillin V in inner membranes extracted from cells grown with glucose. Results of this study suggest that the unexpected change in penicillin-binding protein 8 observed in the presence of glucose may be responsible for the increase in MICs of cephaloridine and ceftazidime. |
. As MK-417, the S-enantiomer of the racemic compound MK-927, is the more active enantiomer in vitro, the potential differential ocular hypotensive activity was investigated in patients. The 1% concentration was chosen as the basis for comparison, as preliminary data indicated that the concentration would fall relatively steeply on the dose-response curve. This was a two-center crossover study of 1% MK-417, 1% MK-927, and placebo (common vehicle) in 27 patients with bilateral, relatively symmetric primary open-angle glaucoma or ocular hypertension. Following a washout period for ocular hypertensive therapy, IOP had to be greater than or equal to 23 mmHg at 10:00 o'clock with IOP difference between eyes less than or equal to 6 mmHg. Treatment days were separated by a 1-2 week washout period. IOP was measured at 9:30. At 10:00 patients received the test drug in one designated eye and placebo in the other eye. IOP was measured at 1, 2, 4, 6, and 8 h after the dose. IOP and the percentage of change in IOP from 30 min before the dose in the active drug-treated eye shows that MK-417 is slightly more potent than MK-927 in this patient model. |
RF Exploitation and Detection Techniques using Software Defined Radio: A Survey In order to mitigate the attacks involved in Radio Frequency (RF), various security techniques are developed in the literature. However, from replay attacks which can steal a car, to GPS attacks tricking vehicles into changing course, there are many threats that still exist today. With advancement of the technology, the vulnerabilities in RF also increases. The reverse engineering technique of wireless signals allows attackers to create dangerous new attacks every day. This paper provides a brief survey of various attack methodologies using software defined radio (SDR) and discusses common threats and defenses in detail. |
/**
* Context which records order of {@link Context#bindService()} and
* {@link Context#unbindService()} calls.
*/
private static class BindUnbindRecordingContext extends ContextWrapper {
private String mRecordPackage;
private ArrayList<Boolean> mStartStopServiceSequence = new ArrayList<>();
private HashSet<ServiceConnection> mTrackedConnections = new HashSet<>();
public BindUnbindRecordingContext(String recordPackage) {
super(null);
mRecordPackage = recordPackage;
}
public ArrayList<Boolean> getStartStopServiceSequence() {
return mStartStopServiceSequence;
}
@Override
public Context getApplicationContext() {
// Need to return real context so that ContextUtils#fetchAppSharedPreferences() does
// not crash.
return RuntimeEnvironment.application;
}
// Create pending connection.
@Override
public boolean bindService(Intent intent, ServiceConnection connection, int flags) {
connection.onServiceConnected(
new ComponentName(mRecordPackage, "random"), Mockito.mock(IBinder.class));
if (TextUtils.equals(intent.getPackage(), mRecordPackage)) {
mTrackedConnections.add(connection);
mStartStopServiceSequence.add(true);
}
return true;
}
@Override
public void unbindService(ServiceConnection connection) {
connection.onServiceDisconnected(new ComponentName(mRecordPackage, "random"));
if (mTrackedConnections.contains(connection)) {
mStartStopServiceSequence.add(false);
}
}
} |
RISK FACTORS CAUSING EVOLVEMENT OF ALIMENTARY-DEPENDENT DISEASES IN SPECIFIC GROUPS OF WORKERS EMPLOYED AT METALLURGY PRODUCTION AND PREVENTION MEAUSRES DEVELOPMENT Yu.V. Danilova, D.V. Turchaninov, V.M. Efremov 1 South-Urals State Medical University, 64 Vorovskogo Str., Chelyabinsk, 454092, Russian Federation 2 Omsk State Medical University Russian Ministry of Health, 12 Lenin Str., Omsk, 644099, Russian Federation 3 Administration of the Federal Supervision Service for Consumers Rishts Profection and Human Welfare in the Chelyabinsk Region, 73 Elkina Str., Chelyabinsk, 454092, Russian Federation Development of labor potential in our country, professional health preservation and prolonging working period of active population is a significant function of state authority and a base of social policy in the Russian Federation. Prevention of health losses among work-ing population is a very important task of prevention medicine and it is especially vital nowadays as there are negative forecasts in relation to labor resources dynamics in our country in medium-term period. Working population today is to be treated as a risk group as it constantly undergoes exposure to a whole set of production and nonproduction factors. And primarily lifestyle factors belong to the latter ones. It is very important not only preserve workers' health in working environment but also to improve it as work at industrial enterprises requires a lot of efforts. Such pathogenic factor as irrational nutrition exerts negative impact on population together with other environment factors (of chemical, physic, biological, and social nature) causing morbidity and mortality. Various scenarios can occur due to this exposure; among other phenomena, potentiation of negative effects on health can underlie them. Working conditions at a large metallurgic enterprise include physic factors, namely increased air temperature in a working area, increased noise and vibrations, impacts of various radiation, such as heat, ionizing, electromagnetic, and laser one, dustiness and gas pollution, unfavorable illumination environment. Besides that, plenty of inhalable agents are generated during production processes; among them there are gases, vapor, dust, and aerosols. These agents represent certain toxicological dangers as the exert irritating, fibrogenic, allergenic, carcinogenic, and mutagenic impacts on a human body. Metallurgic production is characterized with a combination of impacts exerted by negative physic and chemical environmental factors and high physical and neuro-psychic overloads. Therefore, complex impacts of these factors are fundamental in risk assessment. Working process, in its turn, is characterized with high load on musculoskeletal system and functional systems of a body, as well as on central nervous system. Nutrition is an unique environment factor which influences a human body; it is both an internal and an external factor. It's also a social factor if we consider nutrition structure and nutrition habits; it is also a biological factor as it is related to essential nutrients intake. Finally, this factor can become pathogenic but it can also raise protective functions of body physiological barriers as it lowers risks of exotoxins penetration and facilitates processes of binding poisons and products of their metabolism. It is these nutrition effects which a concept of medicalpreventive nutrition is based on. A number of works, both by Russian and foreign researchers, is dedicated to scientific grounds and practical implementation of such approaches. Functional deviations and chronic pathologies growth is one of the factors among certain occupational groups of workers employed at industrial enterprises; such pathology can be alimentary-dependent and it makes it necessary to find ways of improving prevention activities on the basis of up-to-date labor medicine data. First of all, we think it is advisable to perform a complex assessment of influence which occupational risk factor and lifestyle factors have on workers' health. In some authors' opinion, occupational risk concept which has been developing quite intensely over the recent years is a truly innovative and up-to-date approach used to define prevention priorities. We constantly face resources deficiency, so scientific grounds of prevention work priorities are very important for leading risk factors elimination. In relation to that, implementation of activities aimed at nutrition system reorganization is a vital task for the state as nutrition is a vital factor determining workers' health. All contemporary activities aimed at workers' health protection don't allow for a possibility of production-induced diseases formation, especially under joint impacts exerted by working conditions and lifestyle factors. Here health preservation depends not only on working conditions improvement but also on a set of social, hygienic, medical, and educational activities. At the same time, such important prevention activities as production control and periodical medical examinations are accomplished without taking productioninduced morbidity into account and it has negative influence on their efficiency. An attempt to estimate actual nutrition as a risk factor which can cause chronic pathology evolvement together with unfavorable working conditions and working process factors determined the importance of the chosen research issue for creating efficient preventive activities. Our research goal was to accomplish hygienic assessment of actual nutrition of workers with several occupations employed at metallurgic production in terms of its contribution into production-induced morbidity. Data and methods. Our research was performed at "Magnitogorskiy metallurgic plant" PLC (MMP). 1,208 steel workers and founders were our basic group. Average age of research participants was equal to 40.0 ± 0.75. Our sampling was representative. We studied actual nutrition of certain workers' groups employed at the enterprise over 2010-2015; when doing it, we analyzed food consumption frequency using extended database on foodstuffs chemical structure and analysis of menus with lists of dishes offered for organized groups nutrition. When analyzing whether ration was balanced, we assessed qualitative and quantitative indices. Then we compared the obtained consumption values for basic nutrients, energy, essential amino acids, lipids, vitamins, dietary fiber, essential and conditionally essential macro-and microbiological elements (60 nutrients totally, allowing for losses on a product peeling, eatable content, and other losses occurring at various treatments during cooking) with "Standards of physiological needs in nutrients and energy for various population groups in the RF". We assessed nutrition regime as well as its other features. We calculated consumption values and provision with nutrients with the help of an original computer program based on Visual Basic module to Excel-2000. This program included database on chemical structure of foodstuffs and dishes based on "Foodstuffs chemical structure" tables and data obtained via laboratory research of foodstuffs. Analysis was performed with the use of Statistica 6.0 software and MS Excel-2003. We checked normalcy of signs distribution with the use of Shapiro-Wilk criterion. We took p equal to 0.05 as a critical significance in all statistic analysis procedures. To check statistic hypotheses, we applied distribution-free techniques. To compare quantitative data from two independent groups, we used Mann-Whitney U-criterion. Results and discussion. As we assessed whether ration was balanced, we detected that proteins, lipids and hydrocarbons ration amounted to 1:1.6:5.1 with recommended level being 1:1.1:4.8, and it proves that nutrition type was mainly a fat one. Daily average values for separate foodstuffs which were consumed by workers employed at metallurgic production are given in table 1. Qualitative assessment revealed that specific weight of individuals with excessive energy consumption amounted to 41.6% (excess being equal to 43.7%) whereas only 7.8% respondents had ration with lowered energy value. Also, 26.0% workers didn't consume enough carbohydrates, while 19.5% consumed them in excessive quantity. Protein consumption was average, quite sufficient, and corresponded to physiological standards (109.2 %). We should note that specific weight of people who consumed food cholesterol in excessive quantity amounted to 75.3% (excess value being 139.5%); the same figure for triglycerides was 98.3% (excess value being 200.4%)/ When we analyzed omega-6-fatty acids contents we found out that specific weight of people who consumed them in excessive quantity was equal to 61.0% with excess value being 190.9%, and omega-6/omega-3-fatty acids (FA) content deviated from the recommended level rather substantially (table 2). Linolenic acid (w-3), mg 10,4 ± 0,9 19,5 ± 1,1 170,9 Arachidonic acid (w-6), mg 35,1 ± 1,4 9,1 ± 0,8 200,4 w-6 / w-3 ratio 11,7 ± 0,9 64,9 ± 1,4 111,9 Vitamin consumption in the examined group was higher than on average for population of the Urals and Siberia. It was due to the necessity to compensate for considerable energy consumption caused by high physical activity. However, we should point out that specific weight of people who didn't consume enough A vitamin amounted to 64.9%; folic acid, 80.5% (deficiency value being 58.0%); D vitamin, more than 90.0%/ If we take essential macro-and microelements, then special attention should be paid to insufficient calcium consumption (33.8% respondents) and Ca/P recommended ratio violation related to that (practically 1:1.4). Research of food status in separate MMP workers' groups revealed that clinical symptoms of vitamin deficiency occurred quite rarely and it corresponded to the data obtained via actual nutrition assessment. The figure below represents food status assessment for workers employed at metallurgic production as per body mass index. Such data coincide with the results of workers' actual nutrition assessment. We performed epidemiologic analysis of morbidity and a set of its outcomes (morbidity with temporary incapacity, disability, untimely deaths); the results correlated with the data obtained via hygienic assessment of nutrition which workers employed at metallurgic production received. Diseases with etiology wholly dependent on nutrition factor were characterized with apparent and statistically significant growth trend in overall morbidity dynamics for MMP workers ( pr was equal to +6.6; p<0.001). Alimentary -dependent diseases were on average equal to 21.6% in overall morbidity structure in 2010-2015. We worked out several model menus for the metallurgic plant canteens and recommended to adopt them in full conformity with sanitary regulations. We allowed for seasonality, necessary quantities of basic nutrients, and required caloric value of daily ration. Menus included foodstuffs which could help to prevent diseases caused by micro-nutrients deficiency. We also grounded our recommendations on reduction in consumption of animal saturated fats and growth in orega-3-fatty acids consumption. All this helped to make range of meat and vegetable dishes in the metallurgic plant canteens wider, increase number of workers who ate 2 or 3 times, to introduce hot breakfast and lunch, and to organize dietetic nutrition. Conclusions. Hygienic assessment of nutrition revealed that actual nutrition which certain workers' groups employed at metallurgic production received was irrational, imbalanced, and it didn't satisfy physiological needs. So, a risk of deviations in food status and alimentary-dependent diseases evolvement occurred. Clinically significant symptoms of skin damage related to insufficient provision with micro-nutrients didn't occur frequently. More than a half of the examined workers had excessive body mass (12.7% suffered from obesity with the 1st and 2nd degree). On average, alimentary-dependent diseases amounted to 21.6% in the structure of overall morbidity in 2010-2015. Diseases caused mostly by nutrition factor amounted to 10.0% of all diseases with temporary incapacity. Epidemiologic analysis of morbidity caused by diseases related to irrational nutrition allowed us to determine priority nosologies, risk groups, as well as risk factors. This information was essential for creating a set of preventive activities for workers employed at metallurgic production. |
<reponame>VinayTShetty/CompleNotes<filename>Durga Complete Notes/9_INNER CLASSES/INNER CLASSES_VIDEO_DURGA_4.java
TOPIC:-ANNONYMOUS INNER CLASS(NORMAL JAVA CLASS VS ANNOYMOUS INNER CLASS)
--------
VIDEO NO=4
-----------
NUMBER OF PICTURES=NULL
------------------
VIDEO COMPLETED=NO(That inner class interface some concept)
-----------------
IMPORTANT EXAMPLES:-
--------------------
Example=2(verify wheather parent class popcorn constructor will be executed or not.)
when we creating annonymous inner class...
----------------->START OF EXAMPLES<---------------------------
Example=1
=========
NOTE:-
-----
PROGRAME=1
=========
EXPLANATION:-
============
Annonymous inner class difference ---->122 long book page..
Popcorn p=new Popcorn()
{
};
***************************-----END of--->1<--------***************************
Example=2
=========
NOTE:-
-----
PROGRAME=2
=========
EXPLANATION:-
============
page 123 last point verify that
Please verify this is right or not
When we create annonymous inner class Object Parent class constructor will be executed or not....?
Popcorn p=new Popcorn()
{
};
Popcorn class constructor will be executed or not ...?
***************************-----END of--->2<--------***************************
Example=3
=========
NOTE:-
-----
previous video programe:-
PROGRAME=3
=========
class Test
{
public static void main(String[] args)
{
new Thread(new Runnable()
{
public void run()
{
for (int i=0;i<10;i++)
{
System.out.println("Child Thread 1");
}
}
}).start();
for (int i=0;i<10;i++)
{
System.out.println("main Thread-2");
}
}
}
C:\Users\DELL\Desktop>java Test
main Thread-2
main Thread-2
main Thread-2
main Thread-2
main Thread-2
main Thread-2
Child Thread 1
Child Thread 1
Child Thread 1
Child Thread 1
Child Thread 1
Child Thread 1
Child Thread 1
Child Thread 1
Child Thread 1
Child Thread 1
main Thread-2
main Thread-2
main Thread-2
main Thread-2
EXPLANATION:-
============
40:45 continiue from here...
***************************-----END of--->3<--------***************************
Example=4
=========
NOTE:-
-----
Static Nested class
PROGRAME=4
=========
class Outer
{
static class Nested
{
public void m1()
{
System.out.println("static nested class method");
}
}
public static void main(String[] args)
{
Nested n=new Nested();
n.m1();
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Outer
static nested class method
C:\Users\DELL\Desktop>
EXPLANATION:-
============
Without existing outer class object we can create static nested class object.
within the class we can call directly without creating outer class object..
Outer$Nested.class--->.class file generated name concept is same concept
***************************-----END of--->4<--------***************************
Example=5
=========
NOTE:-
-----
If u want to create Nested class Object outside of outer class..
Outside of outer class acessing static nested class...
PROGRAME=5
=========
class Outer
{
static class Nested
{
public void m1()
{
System.out.println("static nested class method");
}
}
}
class Test
{
public static void main(String[] args)
{
Outer.Nested n=new Outer.Nested();
n.m1();
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Test
static nested class method
C:\Users\DELL\Desktop>
EXPLANATION:-
============
***************************-----END of--->5<--------***************************
Example=6
=========
NOTE:-
-----
PROGRAME=6
=========
class Outer
{
static class Nested
{
public void m1()
{
System.out.println("static nested class Method 1");
}
}
public static void main(String[] args)
{
Outer.Nested n=new Outer.Nested();
n.m1();
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Outer
static nested class Method 1
C:\Users\DELL\Desktop>
EXPLANATION:-
============
Outer.Nested n=new Outer.Nested();
Within the same class we can take class name and create static nested class object but its not recomended approach...
We can call directly.
***************************-----END of--->6<--------***************************
Example=7
=========
NOTE:-
-----
For normal inner class/regular inner class we cannot declare static members.
Inner class cannot have static declaration..
(49:31)For static nested class without existing outer class object we can create static nested class object,
So we can declare static members including main method in static nested class
PROGRAME=7
=========
class Outer
{
static class Nested
{
public void m1()
{
}
public static void main(String[] args)
{
System.out.println("Inner class main method");
}
}
public static void main(String[] args)
{
System.out.println("Outer class main method");
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Outer
Outer class main method
C:\Users\DELL\Desktop>java Outer$Nested
Inner class main method
C:\Users\DELL\Desktop>
EXPLANATION:-
============
For normal or regular inner class we cannot declare any static members.
But in static nested class es,we can declare static members including main method.
Hence we can invoke static nested class directly from command prompt.
***************************-----END of--->7<--------***************************
Example=8
=========
NOTE:-
-----
PROGRAME=8
=========
Case 1:-
------
For normal inner class we can acess static and non static members of outer class directly...
See correctly after creating inner object and then printing it.(Do this later)
class Outer
{
int x=10;
static int y=100;
class Inner
{
public void m1()
{
System.out.println(x);
System.out.println(y);
}
}
public static void main(String[] args)
{
System.out.println("main method");
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Outer
main method
C:\Users\DELL\Desktop>
Case 2:-
-------
From static nested class we can acess directly static members of outer class.
but instance members outer class we cannot acess into static nested class.
class Outer
{
int x=10;
static int y=100;
static class Inner
{
public void m1()
{
System.out.println(x);
System.out.println(y);
}
}
public static void main(String[] args)
{
System.out.println("main method");
}
}
C:\Users\DELL\Desktop>javac Test.java
Test.java:10: error: non-static variable x cannot be referenced from a static context
System.out.println(x);
^
1 error
C:\Users\DELL\Desktop>
EXPLANATION:-
============
***************************-----END of--->8<--------***************************
Example=9
=========
NOTE:-
-----
PROGRAME=9
=========
EXPLANATION:-
============
***************************-----END of--->9<--------***************************
Example=10
=========
NOTE:-
-----
PROGRAME=10
=========
EXPLANATION:-
============
***************************-----END of--->10<--------***************************
Example=11
=========
NOTE:-
-----
PROGRAME=11
=========
EXPLANATION:-
============
***************************-----END of--->11<--------***************************
Example=12
=========
NOTE:-
-----
PROGRAME=12
=========
EXPLANATION:-
============
***************************-----END of--->12<--------***************************
Example=13
=========
NOTE:-
-----
PROGRAME=13
=========
EXPLANATION:-
============
***************************-----END of--->13<--------***************************
Example=14
=========
NOTE:-
-----
PROGRAME=14
=========
EXPLANATION:-
============
***************************-----END of--->14<--------***************************
Example=15
=========
NOTE:-
-----
PROGRAME=15
=========
EXPLANATION:-
============
***************************-----END of--->15<--------***************************
Example=16
=========
NOTE:-
-----
PROGRAME=16
=========
EXPLANATION:-
============
***************************-----END of--->16<--------***************************
Example=17
=========
NOTE:-
-----
PROGRAME=17
=========
EXPLANATION:-
============
***************************-----END of--->17<--------***************************
Example=18
=========
NOTE:-
-----
PROGRAME=18
=========
EXPLANATION:-
============
***************************-----END of--->18<--------***************************
Example=19
=========
NOTE:-
-----
PROGRAME=19
=========
EXPLANATION:-
============
***************************-----END of--->19<--------***************************
Example=20
=========
NOTE:-
-----
PROGRAME=20
=========
EXPLANATION:-
============
***************************-----END of--->20<--------***************************
Example=21
=========
NOTE:-
-----
PROGRAME=21
=========
EXPLANATION:-
============
***************************-----END of--->21<--------***************************
Example=22
=========
NOTE:-
-----
PROGRAME=22
=========
EXPLANATION:-
============
***************************-----END of--->22<--------***************************
Example=23
=========
NOTE:-
-----
PROGRAME=23
=========
EXPLANATION:-
============
***************************-----END of--->23<--------***************************
Example=24
=========
NOTE:-
-----
PROGRAME=24
=========
EXPLANATION:-
============
***************************-----END of--->24<--------***************************
Example=25
=========
NOTE:-
-----
PROGRAME=25
=========
EXPLANATION:-
============
***************************-----END of--->25<--------***************************
Example=26
=========
NOTE:-
-----
PROGRAME=26
=========
EXPLANATION:-
============
***************************-----END of--->26<--------***************************
Example=27
=========
NOTE:-
-----
PROGRAME=27
=========
EXPLANATION:-
============
***************************-----END of--->27<--------***************************
Example=28
=========
NOTE:-
-----
PROGRAME=28
=========
EXPLANATION:-
============
***************************-----END of--->28<--------***************************
Example=29
=========
NOTE:-
-----
PROGRAME=29
=========
EXPLANATION:-
============
***************************-----END of--->29<--------***************************
Example=30
=========
NOTE:-
-----
PROGRAME=30
=========
EXPLANATION:-
============
***************************-----END of--->30<--------***************************
Example=31
=========
NOTE:-
-----
PROGRAME=31
=========
EXPLANATION:-
============
***************************-----END of--->31<--------***************************
Example=32
=========
NOTE:-
-----
PROGRAME=32
=========
EXPLANATION:-
============
***************************-----END of--->32<--------***************************
Example=33
=========
NOTE:-
-----
PROGRAME=33
=========
EXPLANATION:-
============
***************************-----END of--->33<--------***************************
Example=34
=========
NOTE:-
-----
PROGRAME=34
=========
EXPLANATION:-
============
***************************-----END of--->34<--------***************************
Example=35
=========
NOTE:-
-----
PROGRAME=35
=========
EXPLANATION:-
============
***************************-----END of--->35<--------***************************
Example=36
=========
NOTE:-
-----
PROGRAME=36
=========
EXPLANATION:-
============
***************************-----END of--->36<--------***************************
Example=37
=========
NOTE:-
-----
PROGRAME=37
=========
EXPLANATION:-
============
***************************-----END of--->37<--------***************************
Example=38
=========
NOTE:-
-----
PROGRAME=38
=========
EXPLANATION:-
============
***************************-----END of--->38<--------***************************
Example=39
=========
NOTE:-
-----
PROGRAME=39
=========
EXPLANATION:-
============
***************************-----END of--->39<--------***************************
Example=40
=========
NOTE:-
-----
PROGRAME=40
=========
EXPLANATION:-
============
***************************-----END of--->40<--------***************************
Example=41
=========
NOTE:-
-----
PROGRAME=41
=========
EXPLANATION:-
============
***************************-----END of--->41<--------***************************
Example=42
=========
NOTE:-
-----
PROGRAME=42
=========
EXPLANATION:-
============
***************************-----END of--->42<--------***************************
Example=43
=========
NOTE:-
-----
PROGRAME=43
=========
EXPLANATION:-
============
***************************-----END of--->43<--------***************************
Example=44
=========
NOTE:-
-----
PROGRAME=44
=========
EXPLANATION:-
============
***************************-----END of--->44<--------***************************
Example=45
=========
NOTE:-
-----
PROGRAME=45
=========
EXPLANATION:-
============
***************************-----END of--->45<--------***************************
Example=46
=========
NOTE:-
-----
PROGRAME=46
=========
EXPLANATION:-
============
***************************-----END of--->46<--------***************************
Example=47
=========
NOTE:-
-----
PROGRAME=47
=========
EXPLANATION:-
============
***************************-----END of--->47<--------***************************
Example=48
=========
NOTE:-
-----
PROGRAME=48
=========
EXPLANATION:-
============
***************************-----END of--->48<--------***************************
Example=49
=========
NOTE:-
-----
PROGRAME=49
=========
EXPLANATION:-
============
***************************-----END of--->49<--------***************************
Example=50
=========
NOTE:-
-----
PROGRAME=50
=========
EXPLANATION:-
============
***************************-----END of--->50<--------***************************
Example=51
=========
NOTE:-
-----
PROGRAME=51
=========
EXPLANATION:-
============
***************************-----END of--->51<--------***************************
Example=52
=========
NOTE:-
-----
PROGRAME=52
=========
EXPLANATION:-
============
***************************-----END of--->52<--------***************************
Example=53
=========
NOTE:-
-----
PROGRAME=53
=========
EXPLANATION:-
============
***************************-----END of--->53<--------***************************
Example=54
=========
NOTE:-
-----
PROGRAME=54
=========
EXPLANATION:-
============
***************************-----END of--->54<--------***************************
Example=55
=========
NOTE:-
-----
PROGRAME=55
=========
EXPLANATION:-
============
***************************-----END of--->55<--------***************************
Example=56
=========
NOTE:-
-----
PROGRAME=56
=========
EXPLANATION:-
============
***************************-----END of--->56<--------***************************
Example=57
=========
NOTE:-
-----
PROGRAME=57
=========
EXPLANATION:-
============
***************************-----END of--->57<--------***************************
Example=58
=========
NOTE:-
-----
PROGRAME=58
=========
EXPLANATION:-
============
***************************-----END of--->58<--------***************************
Example=59
=========
NOTE:-
-----
PROGRAME=59
=========
EXPLANATION:-
============
***************************-----END of--->59<--------***************************
Example=60
=========
NOTE:-
-----
PROGRAME=60
=========
EXPLANATION:-
============
***************************-----END of--->60<--------***************************
Example=61
=========
NOTE:-
-----
PROGRAME=61
=========
EXPLANATION:-
============
***************************-----END of--->61<--------***************************
Example=62
=========
NOTE:-
-----
PROGRAME=62
=========
EXPLANATION:-
============
***************************-----END of--->62<--------***************************
Example=63
=========
NOTE:-
-----
PROGRAME=63
=========
EXPLANATION:-
============
***************************-----END of--->63<--------***************************
Example=64
=========
NOTE:-
-----
PROGRAME=64
=========
EXPLANATION:-
============
***************************-----END of--->64<--------***************************
Example=65
=========
NOTE:-
-----
PROGRAME=65
=========
EXPLANATION:-
============
***************************-----END of--->65<--------***************************
Example=66
=========
NOTE:-
-----
PROGRAME=66
=========
EXPLANATION:-
============
***************************-----END of--->66<--------***************************
Example=67
=========
NOTE:-
-----
PROGRAME=67
=========
EXPLANATION:-
============
***************************-----END of--->67<--------***************************
Example=68
=========
NOTE:-
-----
PROGRAME=68
=========
EXPLANATION:-
============
***************************-----END of--->68<--------***************************
Example=69
=========
NOTE:-
-----
PROGRAME=69
=========
EXPLANATION:-
============
***************************-----END of--->69<--------***************************
Example=70
=========
NOTE:-
-----
PROGRAME=70
=========
EXPLANATION:-
============
***************************-----END of--->70<--------***************************
Example=71
=========
NOTE:-
-----
PROGRAME=71
=========
EXPLANATION:-
============
***************************-----END of--->71<--------***************************
Example=72
=========
NOTE:-
-----
PROGRAME=72
=========
EXPLANATION:-
============
***************************-----END of--->72<--------***************************
Example=73
=========
NOTE:-
-----
PROGRAME=73
=========
EXPLANATION:-
============
***************************-----END of--->73<--------***************************
Example=74
=========
NOTE:-
-----
PROGRAME=74
=========
EXPLANATION:-
============
***************************-----END of--->74<--------***************************
Example=75
=========
NOTE:-
-----
PROGRAME=75
=========
EXPLANATION:-
============
***************************-----END of--->75<--------***************************
Example=76
=========
NOTE:-
-----
PROGRAME=76
=========
EXPLANATION:-
============
***************************-----END of--->76<--------***************************
Example=77
=========
NOTE:-
-----
PROGRAME=77
=========
EXPLANATION:-
============
***************************-----END of--->77<--------***************************
Example=78
=========
NOTE:-
-----
PROGRAME=78
=========
EXPLANATION:-
============
***************************-----END of--->78<--------***************************
Example=79
=========
NOTE:-
-----
PROGRAME=79
=========
EXPLANATION:-
============
***************************-----END of--->79<--------***************************
Example=80
=========
NOTE:-
-----
PROGRAME=80
=========
EXPLANATION:-
============
***************************-----END of--->80<--------***************************
Example=81
=========
NOTE:-
-----
PROGRAME=81
=========
EXPLANATION:-
============
***************************-----END of--->81<--------***************************
Example=82
=========
NOTE:-
-----
PROGRAME=82
=========
EXPLANATION:-
============
***************************-----END of--->82<--------***************************
Example=83
=========
NOTE:-
-----
PROGRAME=83
=========
EXPLANATION:-
============
***************************-----END of--->83<--------***************************
Example=84
=========
NOTE:-
-----
PROGRAME=84
=========
EXPLANATION:-
============
***************************-----END of--->84<--------***************************
Example=85
=========
NOTE:-
-----
PROGRAME=85
=========
EXPLANATION:-
============
***************************-----END of--->85<--------***************************
Example=86
=========
NOTE:-
-----
PROGRAME=86
=========
EXPLANATION:-
============
***************************-----END of--->86<--------***************************
Example=87
=========
NOTE:-
-----
PROGRAME=87
=========
EXPLANATION:-
============
***************************-----END of--->87<--------***************************
Example=88
=========
NOTE:-
-----
PROGRAME=88
=========
EXPLANATION:-
============
***************************-----END of--->88<--------***************************
Example=89
=========
NOTE:-
-----
PROGRAME=89
=========
EXPLANATION:-
============
***************************-----END of--->89<--------***************************
Example=90
=========
NOTE:-
-----
PROGRAME=90
=========
EXPLANATION:-
============
***************************-----END of--->90<--------***************************
Example=91
=========
NOTE:-
-----
PROGRAME=91
=========
EXPLANATION:-
============
***************************-----END of--->91<--------***************************
Example=92
=========
NOTE:-
-----
PROGRAME=92
=========
EXPLANATION:-
============
***************************-----END of--->92<--------***************************
Example=93
=========
NOTE:-
-----
PROGRAME=93
=========
EXPLANATION:-
============
***************************-----END of--->93<--------***************************
Example=94
=========
NOTE:-
-----
PROGRAME=94
=========
EXPLANATION:-
============
***************************-----END of--->94<--------***************************
Example=95
=========
NOTE:-
-----
PROGRAME=95
=========
EXPLANATION:-
============
***************************-----END of--->95<--------***************************
Example=96
=========
NOTE:-
-----
PROGRAME=96
=========
EXPLANATION:-
============
***************************-----END of--->96<--------***************************
Example=97
=========
NOTE:-
-----
PROGRAME=97
=========
EXPLANATION:-
============
***************************-----END of--->97<--------***************************
Example=98
=========
NOTE:-
-----
PROGRAME=98
=========
EXPLANATION:-
============
***************************-----END of--->98<--------***************************
Example=99
=========
NOTE:-
-----
PROGRAME=99
=========
EXPLANATION:-
============
***************************-----END of--->99<--------***************************
Example=100
=========
NOTE:-
-----
PROGRAME=100
=========
EXPLANATION:-
============
***************************-----END of--->100<--------***************************
|
package gui;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import commands.TurtleDisplay;
import controller.CommandController;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
* @author <NAME> ck174
* Creates an environment that holds all of the user interface together
*
*/
public class IDE {
public static final int WIDTH = 1000;
public static final int HEIGHT = 800;
private Scene myScene;
private Timeline animation = new Timeline();
private BorderPane layout;
private BorderPane bottomPane;
private BorderPane topPane;
private BorderPane centerPane;
private TurtleDisplay td;
private CommandController controller;
private List<Window> windows;
private VBox toolbar;
private VBox rightbar;
private BorderPane turtlePane;
private BorderPane consolePane;
private BorderPane viewerPane;
private WindowViewer viewer;
private ConsoleWindow console;
private Stage stage;
private static final int FRAMES_PER_SECOND = 2;
private static final int MILLISECOND_DELAY = 1000 / FRAMES_PER_SECOND;
private static final String COLOR = "resources.IDE/colors";
private static ResourceBundle styleResources = ResourceBundle.getBundle(COLOR);
public IDE(Stage s) {
controller = new CommandController();
layout = new BorderPane();
myScene = new Scene(layout, WIDTH, HEIGHT);
windows = new ArrayList<Window>();
stage = s;
setUpPanes();
animate();
}
public Scene getScene() {
return myScene;
}
/**
* Adds console to bottom right corner
*/
private void addConsole() {
ConsoleWindow w = new ConsoleWindow(consolePane, controller);
windows.add(w);
w.start();
console = w;
}
/**
* Adds turtle display to top right corner
*/
private void addTurtleDisplay() {
td = new TurtleDisplay(turtlePane);
windows.add(td);
controller.addDisplay(td);
td.start();
}
/**
* Adds window viewer to bottom left corner
*/
private void addWindowViewer() {
viewer = new WindowViewer(viewerPane, td, controller);
viewer.createViewer();
windows.add(viewer);
viewer.start();
}
/**
* Adds toolbar to top left corner
*/
private void addToolBar() {
// TODO: Implement addToolBar()
EditBar tools = new EditBar(toolbar,td,stage,console);
tools.start();
}
/**
* Sets up multiple panes so that the component panes can be added on
*/
private void setUpPanes() {
bottomPane = new BorderPane();
topPane = new BorderPane();
layout.setBottom(bottomPane);
layout.setTop(topPane);
//new
centerPane = new BorderPane();
layout.setCenter(centerPane);
toolbar = new VBox();
rightbar = new VBox();
//refactor
toolbar.setStyle(styleResources.getString("verticalStyle"));
toolbar.setPrefWidth(WIDTH * 1/6);
rightbar.setStyle(styleResources.getString("verticalStyle"));
rightbar.setPrefWidth(WIDTH * 1/6);
turtlePane = new BorderPane();
turtlePane.setPrefWidth(WIDTH*2/3);
turtlePane.setStyle(styleResources.getString("initTurtleStyle"));
centerPane.setLeft(toolbar);
centerPane.setCenter(turtlePane);
centerPane.setRight(rightbar);
consolePane = new BorderPane();
consolePane.setPrefWidth(WIDTH * 2/3);
viewerPane = new BorderPane();
bottomPane.setRight(consolePane);
bottomPane.setLeft(viewerPane);
addConsole();
addTurtleDisplay();
addToolBar();
addWindowViewer();
}
private void animate() {
KeyFrame frame = new KeyFrame(Duration.millis(MILLISECOND_DELAY), e -> step());
animation.setCycleCount(Timeline.INDEFINITE);
animation.getKeyFrames().add(frame);
animation.play();
}
private void step(){
for (Window w : windows) {
w.update();
}
}
}
|
#include "QPanda.h"
USING_QPANDA
int main(void)
{
auto qvm = initQuantumMachine(QMachineType::CPU);
auto qubits = qvm->allocateQubits(4);
auto cbits = qvm->allocateCBits(4);
QProg prog;
prog << X(qubits[0])
<< Y(qubits[1])
<< H(qubits[2])
<< RX(qubits[3], 3.14)
<< Measure(qubits[0], cbits[0]);
std::string instructions = convert_qprog_to_quil(prog, qvm);
std::cout << instructions << std::endl;
destroyQuantumMachine(qvm);
return 0;
} |
# dynamic programming
t = int(input())
for t_ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
if len(a)<=3:
print(a[0])
else:
x,y,z,w = 10,10,a[0],a[0]+a[1]
for i in range(2,n):
x,y,z,w = z, min(x,z)+a[i], min(y,w), y+a[i]
print(min(x,y,z,w))
|
Ryan Tannehill (17) completed 15-of-22 passes against the Jaguars, throwing for 146 yards and one touchdown. But he throw a pick-six in the fourth quarter that cost his team the game. Sunday was the sixth game this season that Tannehill threw for less than 200 yards. The movement plays that Miami feasted on earlier this season have vanished, and without that element in the offense, Tannehill has become a sitting duck who is easy to game plan for.
Frank Gore’s grinder style kept Miami’s running game consistent most of the season, but in the Dolphins’ first game without the 14-year veteran the running game stalled. Miami rushed for 62 yards on 18 attempts, and most of that production came on the game’s opening drive. Kenyan Drake (32) gained 23 yards on six carries, and Kalen Ballage gained 10 yards on four carries. Tannehill’s 22 yards on three scrambles made the Dolphins’ rushing yards look respectable.
Here is the South Florida Sun Sentinel's report card, evaluating how the Miami Dolphins performed against the Jacksonville Jaguars. |
/**
pfodWaitingForStart if outside msg
pfodMsgStarted if just seen opening {
pfodInMsg in msg after {
pfodMsgEnd if just seen closing }
*/
byte pfodParser::getParserState() {
if ((parserState == pfodWaitingForStart) ||
(parserState == pfodMsgStarted) ||
(parserState == pfodInMsg) ||
(parserState == pfodMsgEnd) ) {
return parserState;
}
return pfodInMsg;
} |
package Answer
import "testing"
func Test_f(t *testing.T) {
type args struct {
i int
}
tests := []struct {
name string
args args
want bool
}{
// TODO: Add test cases.
{name: "4", args: args{4}, want: false},
{name: "7", args: args{7}, want: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := f(tt.args.i); got != tt.want {
t.Errorf("f() = %v, want %v", got, tt.want)
}
})
}
}
|
Marshall activated; Partch optioned
Sean Marshall was activated from the disabled list (Photo: The Enquirer/Gary Landers)
CHICAGO -- The Reds activated left-hander Sean Marshall from the disabled list before today's game. To make room for Marshall on the roster, right-hander Curtis Partch was optioned to Triple-A Louisville.
Marshall was on the disabled list with shoulder problems. He gives the Reds two left-handers in the bullpen.
"It's not just having two lefties," Reds manager Bryan Price said. "It's having Sean Marshall back. He's really good."
Manny Parra has been the only left-hander in the bullpen until now.
"Just having Manny, we really had to be particular when we used him," Price said. "There were going to be those times when if he could get the ninth with the lead, Manny would be the best to match up with that particular section of the lineup. Yet, you might need him in the seventh or sixth."
Partch, 27, appeared three games. He did not allow a run over 4 1/3 innings, i.e., he did nothing to get demoted.
"It's always disappointing," Price said. "You don't have guys up here who you don't want up here. The one thing about Curtis is of all the guys we have up here, he's the guy who needs to pitch the most consistently because he's right on that edge of defining himself as a true big league pitcher. He certainly has the stuff, but the consistency isn't going to come without pitching."
Partch, the club's 26th-roud pick in 2007, throws up to 98.
NEWSLETTERS Get the Bengals Beat newsletter delivered to your inbox We're sorry, but something went wrong Please try again soon, or contact Customer Service at 1-800-876-4500. Delivery: Invalid email address Thank you! You're almost signed up for Bengals Beat Keep an eye out for an email to confirm your newsletter registration. More newsletters
Innings have been hard to come by for the Reds bullpen. Logan Ondrusek hasn't pitched his April 8. J.J. Hoover and Nick Christiani have pitched once in the last week.
"That has something to do with the two days we had off and the fact that the starters have been so good," Price said.
Read or Share this story: http://cin.ci/Qn3Gvf |
<reponame>wasdswag/MagicBox
# *****************************************************************************
# * | File : epd7in5.py
# * | Author : <NAME>
# * | Function : Electronic paper driver
# * | Info :
# *----------------
# * | This version: V4.0
# * | Date : 2019-06-20
# # | Info : python demo
# -----------------------------------------------------------------------------
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation 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
# furished 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 OR 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.
#
import logging
from . import epdconfig
# Display resolution
EPD_WIDTH = 800
EPD_HEIGHT = 480
logger = logging.getLogger(__name__)
class EPD:
def __init__(self):
self.reset_pin = epdconfig.RST_PIN
self.dc_pin = epdconfig.DC_PIN
self.busy_pin = epdconfig.BUSY_PIN
self.cs_pin = epdconfig.CS_PIN
self.width = EPD_WIDTH
self.height = EPD_HEIGHT
Voltage_Frame_7IN5_V2 = [
0x6, 0x3F, 0x3F, 0x11, 0x24, 0x7, 0x17,
]
LUT_VCOM_7IN5_V2 = [
0x0, 0xF, 0xF, 0x0, 0x0, 0x1,
0x0, 0xF, 0x1, 0xF, 0x1, 0x2,
0x0, 0xF, 0xF, 0x0, 0x0, 0x1,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
]
LUT_WW_7IN5_V2 = [
0x10, 0xF, 0xF, 0x0, 0x0, 0x1,
0x84, 0xF, 0x1, 0xF, 0x1, 0x2,
0x20, 0xF, 0xF, 0x0, 0x0, 0x1,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
]
LUT_BW_7IN5_V2 = [
0x10, 0xF, 0xF, 0x0, 0x0, 0x1,
0x84, 0xF, 0x1, 0xF, 0x1, 0x2,
0x20, 0xF, 0xF, 0x0, 0x0, 0x1,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
]
LUT_WB_7IN5_V2 = [
0x80, 0xF, 0xF, 0x0, 0x0, 0x1,
0x84, 0xF, 0x1, 0xF, 0x1, 0x2,
0x40, 0xF, 0xF, 0x0, 0x0, 0x1,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
]
LUT_BB_7IN5_V2 = [
0x80, 0xF, 0xF, 0x0, 0x0, 0x1,
0x84, 0xF, 0x1, 0xF, 0x1, 0x2,
0x40, 0xF, 0xF, 0x0, 0x0, 0x1,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
]
# Hardware reset
def reset(self):
epdconfig.digital_write(self.reset_pin, 1)
epdconfig.delay_ms(20)
epdconfig.digital_write(self.reset_pin, 0)
epdconfig.delay_ms(2)
epdconfig.digital_write(self.reset_pin, 1)
epdconfig.delay_ms(20)
def send_command(self, command):
epdconfig.digital_write(self.dc_pin, 0)
epdconfig.digital_write(self.cs_pin, 0)
epdconfig.spi_writebyte([command])
epdconfig.digital_write(self.cs_pin, 1)
def send_data(self, data):
epdconfig.digital_write(self.dc_pin, 1)
epdconfig.digital_write(self.cs_pin, 0)
epdconfig.spi_writebyte([data])
epdconfig.digital_write(self.cs_pin, 1)
def send_data2(self, data):
epdconfig.digital_write(self.dc_pin, 1)
epdconfig.digital_write(self.cs_pin, 0)
epdconfig.SPI.writebytes2(data)
epdconfig.digital_write(self.cs_pin, 1)
def ReadBusy(self):
logger.debug("e-Paper busy")
self.send_command(0x71)
busy = epdconfig.digital_read(self.busy_pin)
while(busy == 0):
self.send_command(0x71)
busy = epdconfig.digital_read(self.busy_pin)
epdconfig.delay_ms(20)
logger.debug("e-Paper busy release")
def SetLut(self, lut_vcom, lut_ww, lut_bw, lut_wb, lut_bb):
self.send_command(0x20)
for count in range(0, 42):
self.send_data(lut_vcom[count])
self.send_command(0x21)
for count in range(0, 42):
self.send_data(lut_ww[count])
self.send_command(0x22)
for count in range(0, 42):
self.send_data(lut_bw[count])
self.send_command(0x23)
for count in range(0, 42):
self.send_data(lut_wb[count])
self.send_command(0x24)
for count in range(0, 42):
self.send_data(lut_bb[count])
def init(self):
if (epdconfig.module_init() != 0):
return -1
# EPD hardware init start
self.reset()
# self.send_command(0x06) # btst
# self.send_data(0x17)
# self.send_data(0x17)
# self.send_data(0x28) # If an exception is displayed, try using 0x38
# self.send_data(0x17)
# self.send_command(0x01) #POWER SETTING
# self.send_data(0x07)
# self.send_data(0x07) #VGH=20V,VGL=-20V
# self.send_data(0x3f) #VDH=15V
# self.send_data(0x3f) #VDL=-15V
self.send_command(0x01); # power setting
self.send_data(0x17); # 1-0=11: internal power
self.send_data(self.Voltage_Frame_7IN5_V2[6]); # VGH&VGL
self.send_data(self.Voltage_Frame_7IN5_V2[1]); # VSH
self.send_data(self.Voltage_Frame_7IN5_V2[2]); # VSL
self.send_data(self.Voltage_Frame_7IN5_V2[3]); # VSHR
self.send_command(0x82); # VCOM DC Setting
self.send_data(self.Voltage_Frame_7IN5_V2[4]); # VCOM
self.send_command(0x06); # Booster Setting
self.send_data(0x27);
self.send_data(0x27);
self.send_data(0x2F);
self.send_data(0x17);
self.send_command(0x30); # OSC Setting
self.send_data(self.Voltage_Frame_7IN5_V2[0]); # 2-0=100: N=4 ; 5-3=111: M=7 ; 3C=50Hz 3A=100HZ
self.send_command(0x04) #POWER ON
epdconfig.delay_ms(100)
self.ReadBusy()
self.send_command(0X00) #PANNEL SETTING
self.send_data(0x3F) #KW-3f KWR-2F BWROTP 0f BWOTP 1f
self.send_command(0x61) #tres
self.send_data(0x03) #source 800
self.send_data(0x20)
self.send_data(0x01) #gate 480
self.send_data(0xE0)
self.send_command(0X15)
self.send_data(0x00)
self.send_command(0X50) #VCOM AND DATA INTERVAL SETTING
self.send_data(0x10)
self.send_data(0x07)
self.send_command(0X60) #TCON SETTING
self.send_data(0x22)
self.send_command(0x65); # Resolution setting
self.send_data(0x00);
self.send_data(0x00); # 800*480
self.send_data(0x00);
self.send_data(0x00);
self.SetLut(self.LUT_VCOM_7IN5_V2, self.LUT_WW_7IN5_V2, self.LUT_BW_7IN5_V2, self.LUT_WB_7IN5_V2, self.LUT_BB_7IN5_V2)
# EPD hardware init end
return 0
def getbuffer(self, image):
img = image
imwidth, imheight = img.size
if(imwidth == self.width and imheight == self.height):
img = img.convert('1')
elif(imwidth == self.height and imheight == self.width):
# image has correct dimensions, but needs to be rotated
img = img.rotate(90, expand=True).convert('1')
else:
logger.warning("Wrong image dimensions: must be " + str(self.width) + "x" + str(self.height))
# return a blank buffer
return [0x00] * (int(self.width/8) * self.height)
buf = bytearray(img.tobytes('raw'))
# The bytes need to be inverted, because in the PIL world 0=black and 1=white, but
# in the e-paper world 0=white and 1=black.
for i in range(len(buf)):
buf[i] ^= 0xFF
return buf
def display(self, image):
self.send_command(0x13)
self.send_data2(image)
self.send_command(0x12)
epdconfig.delay_ms(100)
self.ReadBusy()
def Clear(self):
buf = [0x00] * (int(self.width/8) * self.height)
self.send_command(0x10)
self.send_data2(buf)
self.send_command(0x13)
self.send_data2(buf)
self.send_command(0x12)
epdconfig.delay_ms(100)
self.ReadBusy()
def sleep(self):
self.send_command(0x02) # POWER_OFF
self.ReadBusy()
self.send_command(0x07) # DEEP_SLEEP
self.send_data(0XA5)
epdconfig.delay_ms(2000)
epdconfig.module_exit()
### END OF FILE ###
|
<gh_stars>100-1000
package cli
import (
"context"
"strings"
"github.com/pkg/errors"
"github.com/replicatedhq/ship/pkg/ship"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func Unfork() *cobra.Command {
cmd := &cobra.Command{
Use: "unfork FORK",
Short: "Unfork a previously forked Helm chart or Kubernetes YAML ",
Long: `Given an forked and modified Helm chart or Kubernetes YAML, create patches for the changes`,
RunE: func(cmd *cobra.Command, args []string) error {
v := viper.GetViper()
if len(args) == 0 {
_ = cmd.Help()
return errors.New("Error: please supply a fork")
}
v.Set("fork", args[0])
v.Set("headless", true) // We don't support headed unforking
s, err := ship.Get(v)
if err != nil {
return err
}
return s.UnforkAndMaybeExit(context.Background())
},
}
cmd.Flags().StringP("upstream", "", "", "path to the upstream")
_ = viper.BindPFlags(cmd.Flags())
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
return cmd
}
|
<reponame>rayzhoull/moby
package fs
import (
"os"
"golang.org/x/sys/windows"
)
func detectDirDiff(upper, lower string) *diffDirOptions {
return nil
}
func compareSysStat(s1, s2 interface{}) (bool, error) {
f1, ok := s1.(windows.Win32FileAttributeData)
if !ok {
return false, nil
}
f2, ok := s2.(windows.Win32FileAttributeData)
if !ok {
return false, nil
}
return f1.FileAttributes == f2.FileAttributes, nil
}
func compareCapabilities(p1, p2 string) (bool, error) {
// TODO: Use windows equivalent
return true, nil
}
func isLinked(os.FileInfo) bool {
return false
}
|
Analysis of main nutrients among different edible parts of Nainaiqingcai mustard under the alpine cold climate Bijie City, Guizhou Province belongs to the alpine cold climate. In order to understand the nutritional values of Nainaiqingcai mustard, the contents of main nutrients among different edible parts (leaves, petioles, and bolting stem) in Nainaiqingcai mustard under the alpine cold climate were investigated. The results showed that significant differences were found among different edible parts. The levels of chlorophyll, carotenoids, ascorbic acid, soluble soilds, and soluble proteins were followed as the trends of leaves > petioles > bolting stem.Whereas the sugar components showed different distributions, and the lowest content of sugar was detected in leaves. Moreover, significant negatively correlation were found between sugar and the other nutrients. Most of the extremely significant positive correlations were found between sugar components, and the correlation coefficient is high (except for the correlation between fructose and sucrose). The highest correlation coefficient was between chlorophyll and carotenoids, up to 1.000. In summary, the information in this study provides a theoretical reference for the study of nutritional quality of Nainaiqingcai mustard under the alpine cold climate. Introduction Brassica juncea is an annual herb of cruciferae brassica, which originated from spontaneous hybridization of the ancestors of B.rapa (AA, n=10) and B.nigra (BB, n=8). The variety 'Nainaiqingcai' belongs to the mustard vegetables of the cruciferous family. It usually takes the leaves, petioles, and bolting stem as the edible parts. People usually pickle it to eat kimchi, but also eat it as fresh vegetable directly. 'Nainaiqingcai' mustard is one of the local winter-spring vegetables in Bijie City, Guizhou Province, and has a large amount of consumption at the local. Bijie City belongs to the alpine cold climate. Despite being a Brassica vegetable that is widely consumed in winter and spring in Southwest China, there is lack of information available on 'Nainaiqingcai' mustard. In this experiment, in order to understand the nutritional value of 'Nainaiqingcai' mustard in a relatively systematic way, this study used 'Nainaiqingcai' mustard as the research material to analyze the difference between the main nutrients between different edible parts, which provided the basis and reference for the scientific consumption of 'Nainaiqingcai' mustard in the future. Plant materials The 'Nainaiqingcai' mustard were sampled on December 15, 2017 at the vegetable base of Bijie Institute of Agricultural Science of Bijie City, Guizhou Province, China (27°1834.36 -N105°1920.70-E). The robust, free of pest and mechanically damaged plants were selected at harvest stage. The samples were divided into three parts according to the leaves, petioles and bolting stem, and then all samples were frozen at −80°C, lyophilized, ground to a powder, and stored at −20°C. Test methods 2.2.1. Chlorophyll and carotenoid content. Two hundred milligrams of powder were extracted in 25 mL of ethanol solution for 20 min. The solution was stirred for 15 s using a vortex mixer, after which it was allowed to settle for 30 min. The solution was then centrifuged for 5 min at 8000 g and 1 mL transferred to a polypropylene tube. The absorbance of the reaction mixtures was measured at 665nm, 649nm and 470nm using a spectrophotometer. The content and concentration of chlorophyll and carotenoids were calculated according to the formula. 2.2.2. Ascorbic acid content. Ascorbic acid content was determined using the methods of 2,6-dichloroindophenoltitration. Two hundred mg of sample powder was extracted with 25 mL oxalic acid. The solution was stirred for 30 s using a vortex mixer, after which it was allowed to settle for 10 min. The solution was then centrifuged for 5 min at 8000 g and 5 mL transferred into an Erlenmeyer flask. Immediately titration with 2,6-dichloroindophenol solution to pink, no fading for 15 s. The volume of 2,6-dichloroindophenol solution consumed was recorded, and then calculate the content of ascorbic acid. 2.2.3. Soluble sugar content and sugar component. The determination of soluble sugar content was performed using the method proposed by Morris. Two hundred milligrams of powder were extracted in 25 mL of distilled water for 20 min at 90°C, following which the homogenates were centrifuged at 8000 g for 5 min. A combination of 1 mL of diluted sample, 0.25 mL anthrone-ethyl acetate reagent, and 2.5 mL concentrated sulfuric acid was homogenized and boiled for 5 min, and then cooled rapidly using ice water. The absorbance of the reaction mixtures was measured at 630 nm using a spectrophotometer, and the soluble sugar content was determined using a standard curve of sucrose. Sugar component: Two hundred milligrams of powder was extracted in 25 mL of distilled water for 20 min at 90°C. The solution was stirred for 15 s using a vortex mixer, following which the homogenyates were centrifuged at 8000 g for 5 min. The supernatant was drawn 2 ml into a new 10 ml centrifuge tube and then 2 ml of distilled water was added again in the residue The solution was then centrifuged for 5 min at 8000 g. The supernatant of 2 mL was absorbed, combined with the supernatant extracted for the first time, and the mixture was uniform. HPLC analysis of sugar component carried out using a Model Agilent 1260. The total sugar content is determined by the sum of the contents of fructose, glucose and sucrose. Soluble solids content. The content of soluble solids was determined by portable sugar meter. 2.2.5. Soluble proteins content. Two hundred milligrams of powder were extracted in 25 mL, after which it was allowed to settle for 40 min. The solution was then centrifuged for 5 min at 8000 g and 0.5 mL transferred to a polypropylene tube. Subsequently, 0.5 mL of distilled water and 5 mL of Coomassie brilliant blue G-250 was combined with 0.5 mL of supernatant. The absorbance was measured at 595 nm within 20 min after the reaction. Soluble proteins in the samples were calculated based on a standard curve of bovine serum albumin. Data analysis All assays were performed in quadruplicate. The results are shown as the mean ± standard deviation (SD). Microsoft Excel 2016 was adopted for data processing. Correlation analysis was performed using the PASWStatistics18 version. Differential significance analysis was performed using DPSSOFT 7.5 software. The results were subjected to one-way analysis of variance (ANOVA) and differences between means were located using Duncan test. Chlorophyll, carotenoids and ascorbic acid. There are significant differences in the chlorophyll, carotenoids and ascorbic acid between the different edible parts of the 'Nainaiqingcai' mustard. The above three nutrients showed the same trend, the leaves had the highest content, followed by the petioles and the lowest content in the bolting stem. In addition, the fold differences of different nutrients among different edible parts were also significantly different. The chlorophyll content in leaves was 53 times that of bolting stem, and the difference was the largest. The ascorbic acid content in leaves was 1.32 times that of bolting stem, and the difference was the smallest. Soluble proteins and soluble solids The content of soluble proteins and soluble solids in 'Nainaiqingcai' mustard were shown in Table 2. The soluble proteins content in the three edible parts ranged from 25.82 mgg -1 DW to 121.94 mgg -1 DW, which was expressed as leaves>bolting stem>petioles. The soluble proteins content of leaves was nearly five-fold of that in other edible parts. The trend of soluble solids in edible parts was concordant with soluble proteins. The soluble solids content in leaves was 2 times of that of petioles, and 1.2 times of that of bolting stem. (Figure 1). Soluble sugar and sugar components The soluble sugar content was lowest in the leaves, significantly lower than the contents of the petioles and bolting stem. The contents of three soluble sugars of sucrose, fructose and glucose were determined by HPLC. The distributions of three soluble sugars were similar with that of soluble sugar content, and the contents in the leaves significantly lower than those in the petioles and bolting stem. However, the distributions of three soluble sugars between petioles and bolting stem were remarkably distinct. Moreover, the content of glucose was also significantly more abundant than those of sucrose and fructose. Especially in the petioles, the glucose content was as high as 347.96 mgg -1 DW, which was 3 times more than that of fructose and 21 times more than that of sucrose. Correlation analysis The correlation analysis between the main nutrients of Nainaiqingcai' mustard was shown in Table 3. The positive correlation coefficient between chlorophyll and carotenoids was highest, the value came up to 1.000. While the greatest negative correlation coefficient was observed between fructose and chlorophyll, and the level was -0.992. In addition, all the five sugars index (soluble sugar, fructose, glucose, sucrose, total sugar) showed highly negative correlation with other nutrients measured. However, the correlations between sugars were extremely significant positive, except for that between fructose and sucrose. The correlation analysis indicated that Soluble proteins and soluble solids was significantly positively associated with chlorophyll, carotenoids and ascorbic acid (except that soluble solids and ascorbic acid were significantly higher at 0.05 level and the correlation coefficient was lower). The difference was that soluble solids and these three were extremely significantly lower than soluble proteins. Soluble proteins and soluble solids were significantly positively associated with chlorophyll, carotenoids and ascorbic acid. However, the correlation coefficients between soluble solids and these three above latter all were notably lower than those of soluble proteins. The correlation coefficients between chlorophyll, carotenoids and ascorbic acid were very high, and these values were all above 0.96 (Table 3). Discussion The present study was the first to assess the main nutrients of the different edible parts of 'Nainaiqingcai' mustard. Our results also indicated that there were significant differences in the contents of main nutrients among different parts of 'Nianaiqingcai' mustard. Many studies have indicated that significant differences exist among different plant organs/tissues in terms of nutritional composition and content. In our study, the content of major nutrients (except sugar) in the leaves was higher than other edibles parts. This phenomenon was consistent with the results of previous studies in other vegetables. For example, Liu et al. found that the contents of chlorophyll, carotenoids and ascorbic acid in the leaves were significantly higher than those in other edibles parts. Ma et al. found that the contents of chlorophyll, carotenoids and ascorbic acid in the leaves of peas were also significantly higher than those in other edible parts. Sun et al. also found the same phenomena in the studies of broccoli and Chinese kale. It might be related to the fact that leaves were the main photosynthesis organs. The main pigments of chlorophyll and carotenoids in chloroplasts are the material basis for the absorption, transmission and conversion of light energy during plant photosynthesis. Ascorbic acid was a small molecule antioxidant that plays an important role in resisting plant stress and can be rapidly oxidatively decomposed to form monodehydroascorbic acid and dehydroascorbic acid. The contents soluble solids and soluble proteins in leaves were higher than those in other edibles parts, and showed the trend of leaves>bolting stem>petioles, which was consistent with Sun et al.'s research on six varieties of Chinese kale. Sugar is an important class of energy substances that play an important role in the growth and development of plants. It not only provides energy for the daily metabolism of plants, but also is the main components of vegetable quality and flavor. In this experiment, the content and components of soluble sugar in different edibles parts of 'Nainaiqingcai' mustard was determined. Results showed that the components of soluble sugar did not differ between different edibles parts, but the content of soluble sugar was significantly different between different edibles parts. The contents of five sugar index (soluble sugar, fructose, glucose, sucrose, total sugar) were different. The distribution of soluble sugar, sucrose and fructose all were bolting stem>petioles>leaves, and the contents of glucose and total sugar both were petioles>bolting stem>leaves. In theory, soluble sugar should be consistent with the trends of fructose, glucose, and sucrose, and the same result as total sugar. The reason may be that the different detection methods of soluble sugar and other sugars, the soluble sugar was detected by the fluorenone colorimetric method, and fructose, glucose and sucrose were detected by HPLC. Only three kinds of sugars were detected in the test by HPLC, but the soluble sugar also included maltose and so on. This was why there was a slight difference between the sugar index. It was worth noting that the trend of the content of petioles and bolting stem may be different in sugar index, no matter which sugar index, the sugar content of leaves was much lower than those of other edible parts. The trend between the sugar components was glucose > fructose > sucrose. Compared with the research of An et al., the sugar components of some varieties of pear fruit were consistently distributed, and the distribution of sugar components varies depending on the plant species and varieties. In this experiment, the distribution of several main nutrients in leaves, petioles and bolting stem of 'Nainaiqingcai' mustard was analyzed. The information in this study provides a theoretical reference for human dietary nutrition and a foundation for the further study of 'Nainaiqingcai' mustard. |
package com.lotaris.jee.validation.preprocessing;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author <NAME> (<EMAIL>)
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ConstraintConverter {
String locationType();
int code();
}
|
<filename>measurer/hotspot-measurer/hotspot/src/cpu/sparc/vm/c1_FrameMap_sparc.cpp<gh_stars>100-1000
/*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "c1/c1_FrameMap.hpp"
#include "c1/c1_LIR.hpp"
#include "runtime/sharedRuntime.hpp"
#include "vmreg_sparc.inline.hpp"
const int FrameMap::pd_c_runtime_reserved_arg_size = 7;
LIR_Opr FrameMap::map_to_opr(BasicType type, VMRegPair* reg, bool outgoing) {
LIR_Opr opr = LIR_OprFact::illegalOpr;
VMReg r_1 = reg->first();
VMReg r_2 = reg->second();
if (r_1->is_stack()) {
// Convert stack slot to an SP offset
// The calling convention does not count the SharedRuntime::out_preserve_stack_slots() value
// so we must add it in here.
int st_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
opr = LIR_OprFact::address(new LIR_Address(SP_opr, st_off + STACK_BIAS, type));
} else if (r_1->is_Register()) {
Register reg = r_1->as_Register();
if (outgoing) {
assert(!reg->is_in(), "should be using I regs");
} else {
assert(!reg->is_out(), "should be using O regs");
}
if (r_2->is_Register() && (type == T_LONG || type == T_DOUBLE)) {
opr = as_long_opr(reg);
} else if (type == T_OBJECT || type == T_ARRAY) {
opr = as_oop_opr(reg);
} else {
opr = as_opr(reg);
}
} else if (r_1->is_FloatRegister()) {
assert(type == T_DOUBLE || type == T_FLOAT, "wrong type");
FloatRegister f = r_1->as_FloatRegister();
if (type == T_DOUBLE) {
opr = as_double_opr(f);
} else {
opr = as_float_opr(f);
}
}
return opr;
}
// FrameMap
//--------------------------------------------------------
FloatRegister FrameMap::_fpu_regs [FrameMap::nof_fpu_regs];
// some useful constant RInfo's:
LIR_Opr FrameMap::in_long_opr;
LIR_Opr FrameMap::out_long_opr;
LIR_Opr FrameMap::g1_long_single_opr;
LIR_Opr FrameMap::F0_opr;
LIR_Opr FrameMap::F0_double_opr;
LIR_Opr FrameMap::G0_opr;
LIR_Opr FrameMap::G1_opr;
LIR_Opr FrameMap::G2_opr;
LIR_Opr FrameMap::G3_opr;
LIR_Opr FrameMap::G4_opr;
LIR_Opr FrameMap::G5_opr;
LIR_Opr FrameMap::G6_opr;
LIR_Opr FrameMap::G7_opr;
LIR_Opr FrameMap::O0_opr;
LIR_Opr FrameMap::O1_opr;
LIR_Opr FrameMap::O2_opr;
LIR_Opr FrameMap::O3_opr;
LIR_Opr FrameMap::O4_opr;
LIR_Opr FrameMap::O5_opr;
LIR_Opr FrameMap::O6_opr;
LIR_Opr FrameMap::O7_opr;
LIR_Opr FrameMap::L0_opr;
LIR_Opr FrameMap::L1_opr;
LIR_Opr FrameMap::L2_opr;
LIR_Opr FrameMap::L3_opr;
LIR_Opr FrameMap::L4_opr;
LIR_Opr FrameMap::L5_opr;
LIR_Opr FrameMap::L6_opr;
LIR_Opr FrameMap::L7_opr;
LIR_Opr FrameMap::I0_opr;
LIR_Opr FrameMap::I1_opr;
LIR_Opr FrameMap::I2_opr;
LIR_Opr FrameMap::I3_opr;
LIR_Opr FrameMap::I4_opr;
LIR_Opr FrameMap::I5_opr;
LIR_Opr FrameMap::I6_opr;
LIR_Opr FrameMap::I7_opr;
LIR_Opr FrameMap::G0_oop_opr;
LIR_Opr FrameMap::G1_oop_opr;
LIR_Opr FrameMap::G2_oop_opr;
LIR_Opr FrameMap::G3_oop_opr;
LIR_Opr FrameMap::G4_oop_opr;
LIR_Opr FrameMap::G5_oop_opr;
LIR_Opr FrameMap::G6_oop_opr;
LIR_Opr FrameMap::G7_oop_opr;
LIR_Opr FrameMap::O0_oop_opr;
LIR_Opr FrameMap::O1_oop_opr;
LIR_Opr FrameMap::O2_oop_opr;
LIR_Opr FrameMap::O3_oop_opr;
LIR_Opr FrameMap::O4_oop_opr;
LIR_Opr FrameMap::O5_oop_opr;
LIR_Opr FrameMap::O6_oop_opr;
LIR_Opr FrameMap::O7_oop_opr;
LIR_Opr FrameMap::L0_oop_opr;
LIR_Opr FrameMap::L1_oop_opr;
LIR_Opr FrameMap::L2_oop_opr;
LIR_Opr FrameMap::L3_oop_opr;
LIR_Opr FrameMap::L4_oop_opr;
LIR_Opr FrameMap::L5_oop_opr;
LIR_Opr FrameMap::L6_oop_opr;
LIR_Opr FrameMap::L7_oop_opr;
LIR_Opr FrameMap::I0_oop_opr;
LIR_Opr FrameMap::I1_oop_opr;
LIR_Opr FrameMap::I2_oop_opr;
LIR_Opr FrameMap::I3_oop_opr;
LIR_Opr FrameMap::I4_oop_opr;
LIR_Opr FrameMap::I5_oop_opr;
LIR_Opr FrameMap::I6_oop_opr;
LIR_Opr FrameMap::I7_oop_opr;
LIR_Opr FrameMap::SP_opr;
LIR_Opr FrameMap::FP_opr;
LIR_Opr FrameMap::Oexception_opr;
LIR_Opr FrameMap::Oissuing_pc_opr;
LIR_Opr FrameMap::_caller_save_cpu_regs[] = { 0, };
LIR_Opr FrameMap::_caller_save_fpu_regs[] = { 0, };
FloatRegister FrameMap::nr2floatreg (int rnr) {
assert(_init_done, "tables not initialized");
debug_only(fpu_range_check(rnr);)
return _fpu_regs[rnr];
}
// returns true if reg could be smashed by a callee.
bool FrameMap::is_caller_save_register (LIR_Opr reg) {
if (reg->is_single_fpu() || reg->is_double_fpu()) { return true; }
if (reg->is_double_cpu()) {
return is_caller_save_register(reg->as_register_lo()) ||
is_caller_save_register(reg->as_register_hi());
}
return is_caller_save_register(reg->as_register());
}
NEEDS_CLEANUP // once the new calling convention is enabled, we no
// longer need to treat I5, I4 and L0 specially
// Because the interpreter destroys caller's I5, I4 and L0,
// we must spill them before doing a Java call as we may land in
// interpreter.
bool FrameMap::is_caller_save_register (Register r) {
return (r->is_global() && (r != G0)) || r->is_out();
}
void FrameMap::initialize() {
assert(!_init_done, "once");
int i=0;
// Register usage:
// O6: sp
// I6: fp
// I7: return address
// G0: zero
// G2: thread
// G7: not available
// G6: not available
/* 0 */ map_register(i++, L0);
/* 1 */ map_register(i++, L1);
/* 2 */ map_register(i++, L2);
/* 3 */ map_register(i++, L3);
/* 4 */ map_register(i++, L4);
/* 5 */ map_register(i++, L5);
/* 6 */ map_register(i++, L6);
/* 7 */ map_register(i++, L7);
/* 8 */ map_register(i++, I0);
/* 9 */ map_register(i++, I1);
/* 10 */ map_register(i++, I2);
/* 11 */ map_register(i++, I3);
/* 12 */ map_register(i++, I4);
/* 13 */ map_register(i++, I5);
/* 14 */ map_register(i++, O0);
/* 15 */ map_register(i++, O1);
/* 16 */ map_register(i++, O2);
/* 17 */ map_register(i++, O3);
/* 18 */ map_register(i++, O4);
/* 19 */ map_register(i++, O5); // <- last register visible in RegAlloc (RegAlloc::nof+cpu_regs)
/* 20 */ map_register(i++, G1);
/* 21 */ map_register(i++, G3);
/* 22 */ map_register(i++, G4);
/* 23 */ map_register(i++, G5);
/* 24 */ map_register(i++, G0);
// the following registers are not normally available
/* 25 */ map_register(i++, O7);
/* 26 */ map_register(i++, G2);
/* 27 */ map_register(i++, O6);
/* 28 */ map_register(i++, I6);
/* 29 */ map_register(i++, I7);
/* 30 */ map_register(i++, G6);
/* 31 */ map_register(i++, G7);
assert(i == nof_cpu_regs, "number of CPU registers");
for (i = 0; i < nof_fpu_regs; i++) {
_fpu_regs[i] = as_FloatRegister(i);
}
_init_done = true;
in_long_opr = as_long_opr(I0);
out_long_opr = as_long_opr(O0);
g1_long_single_opr = as_long_single_opr(G1);
G0_opr = as_opr(G0);
G1_opr = as_opr(G1);
G2_opr = as_opr(G2);
G3_opr = as_opr(G3);
G4_opr = as_opr(G4);
G5_opr = as_opr(G5);
G6_opr = as_opr(G6);
G7_opr = as_opr(G7);
O0_opr = as_opr(O0);
O1_opr = as_opr(O1);
O2_opr = as_opr(O2);
O3_opr = as_opr(O3);
O4_opr = as_opr(O4);
O5_opr = as_opr(O5);
O6_opr = as_opr(O6);
O7_opr = as_opr(O7);
L0_opr = as_opr(L0);
L1_opr = as_opr(L1);
L2_opr = as_opr(L2);
L3_opr = as_opr(L3);
L4_opr = as_opr(L4);
L5_opr = as_opr(L5);
L6_opr = as_opr(L6);
L7_opr = as_opr(L7);
I0_opr = as_opr(I0);
I1_opr = as_opr(I1);
I2_opr = as_opr(I2);
I3_opr = as_opr(I3);
I4_opr = as_opr(I4);
I5_opr = as_opr(I5);
I6_opr = as_opr(I6);
I7_opr = as_opr(I7);
G0_oop_opr = as_oop_opr(G0);
G1_oop_opr = as_oop_opr(G1);
G2_oop_opr = as_oop_opr(G2);
G3_oop_opr = as_oop_opr(G3);
G4_oop_opr = as_oop_opr(G4);
G5_oop_opr = as_oop_opr(G5);
G6_oop_opr = as_oop_opr(G6);
G7_oop_opr = as_oop_opr(G7);
O0_oop_opr = as_oop_opr(O0);
O1_oop_opr = as_oop_opr(O1);
O2_oop_opr = as_oop_opr(O2);
O3_oop_opr = as_oop_opr(O3);
O4_oop_opr = as_oop_opr(O4);
O5_oop_opr = as_oop_opr(O5);
O6_oop_opr = as_oop_opr(O6);
O7_oop_opr = as_oop_opr(O7);
L0_oop_opr = as_oop_opr(L0);
L1_oop_opr = as_oop_opr(L1);
L2_oop_opr = as_oop_opr(L2);
L3_oop_opr = as_oop_opr(L3);
L4_oop_opr = as_oop_opr(L4);
L5_oop_opr = as_oop_opr(L5);
L6_oop_opr = as_oop_opr(L6);
L7_oop_opr = as_oop_opr(L7);
I0_oop_opr = as_oop_opr(I0);
I1_oop_opr = as_oop_opr(I1);
I2_oop_opr = as_oop_opr(I2);
I3_oop_opr = as_oop_opr(I3);
I4_oop_opr = as_oop_opr(I4);
I5_oop_opr = as_oop_opr(I5);
I6_oop_opr = as_oop_opr(I6);
I7_oop_opr = as_oop_opr(I7);
FP_opr = as_pointer_opr(FP);
SP_opr = as_pointer_opr(SP);
F0_opr = as_float_opr(F0);
F0_double_opr = as_double_opr(F0);
Oexception_opr = as_oop_opr(Oexception);
Oissuing_pc_opr = as_opr(Oissuing_pc);
_caller_save_cpu_regs[0] = FrameMap::O0_opr;
_caller_save_cpu_regs[1] = FrameMap::O1_opr;
_caller_save_cpu_regs[2] = FrameMap::O2_opr;
_caller_save_cpu_regs[3] = FrameMap::O3_opr;
_caller_save_cpu_regs[4] = FrameMap::O4_opr;
_caller_save_cpu_regs[5] = FrameMap::O5_opr;
_caller_save_cpu_regs[6] = FrameMap::G1_opr;
_caller_save_cpu_regs[7] = FrameMap::G3_opr;
_caller_save_cpu_regs[8] = FrameMap::G4_opr;
_caller_save_cpu_regs[9] = FrameMap::G5_opr;
for (int i = 0; i < nof_caller_save_fpu_regs; i++) {
_caller_save_fpu_regs[i] = LIR_OprFact::single_fpu(i);
}
}
Address FrameMap::make_new_address(ByteSize sp_offset) const {
return Address(SP, STACK_BIAS + in_bytes(sp_offset));
}
VMReg FrameMap::fpu_regname (int n) {
return as_FloatRegister(n)->as_VMReg();
}
LIR_Opr FrameMap::stack_pointer() {
return SP_opr;
}
// JSR 292
LIR_Opr FrameMap::method_handle_invoke_SP_save_opr() {
assert(L7 == L7_mh_SP_save, "must be same register");
return L7_opr;
}
bool FrameMap::validate_frame() {
int max_offset = in_bytes(framesize_in_bytes());
int java_index = 0;
for (int i = 0; i < _incoming_arguments->length(); i++) {
LIR_Opr opr = _incoming_arguments->at(i);
if (opr->is_stack()) {
max_offset = MAX2(_argument_locations->at(java_index), max_offset);
}
java_index += type2size[opr->type()];
}
return Assembler::is_simm13(max_offset + STACK_BIAS);
}
|
// Validate implements validation for ContainerService
func (cs *ContainerService) Validate(isUpdate bool) error {
if e := cs.validateProperties(); e != nil {
return e
}
if e := cs.validateLocation(); e != nil {
return e
}
if e := cs.validateCustomCloudProfile(); e != nil {
return e
}
if e := cs.Properties.validate(isUpdate); e != nil {
return e
}
return nil
} |
Shiriyazaki Lighthouse
History
The Shiriyazaki Lighthouse was one of the 26 lighthouses built in Meiji period Japan by British engineer Richard Henry Brunton. The lighthouse was completed on October 20, 1876 (after Brunton had departed from Japan), and was the first western-style lighthouse in the Tōhoku region of Japan. On November 20, 1877, a fog bell was installed due to the high incidence of fogs and days of poor visibility in the area. This was the first fog bell in Japan, but the sound proved to be too weak, so on December 20, 1879 it was replaced by the first fog horn in Japan. Other noteworthy events include the installation of the first electric power generator for a lighthouse in Japan in 1901.
In 1945, during World War II, Shiriyazaki Lighthouse was bombarded by United States Navy warships, cracking its Fresnel lens and causing severe damage to its structure, killing its attendant. However, the following year, on several occasions, fishermen reported being able to see a light in the ruined lighthouse, which enabled them to land safely despite a deep fog. However, when authorities investigated, they found that the stairs were blocked with rubble and the light room was completely destroyed. A temporary light was installed in the ruined structure from August 1946, and the rumors ceased. The lighthouse was repaired and went back into operation in 1951. The lighthouse is maintained by the Japan Coast Guard.
The Shiriyazaki Lighthouse is registered with the Japanese government as an “A-grade Lighthouse” for historic preservation and is listed as one of the “50 Lighthouses of Japan” by the Japan Lighthouse Association. |
The Growing Impact of US Monetary Policy on Emerging Financial Markets: Evidence from India Much research has been devoted to studying the international spillover effects of US monetary policy. However, a lot of the focus has been on the recent unconventional monetary policies undertaken by the Federal Reserve. Combining high frequency financial market data with a time-varying parameter approach we show that US monetary policy decisions have had significant effects on the Indian stock markets well before the use of unconventional policy tools and that these effects have gotten stronger over time. In addition to the conventional channel of surprise changes in the policy rate, we find that US monetary shocks are also transmitted through an uncertainty channel, which is especially important for announcements about large scale asset purchases (quantitative easing). Using firm level stock prices, we also show that the higher sensitivity of the aggregate response is uniform across the stock market and is not driven by the increased exposure of any specific industry to US monetary policy. Instead, our results suggest that it is driven by the portfolio decisions of foreign institutional investors and the exchange rate becoming more sensitive to US monetary policy. |
////////////////////////////////////////////////////////////////////////////////
//! Formats a memory size value. Memory sizes are KB based.
tstring FormatMemoryValue(uint64 valueInKb)
{
const double valueInGb = valueInKb / (1024.0 * 1024.0);
return Core::fmt(TXT("%.1f GB"), valueInGb);
} |
Prevalence of skin tears in the extremities among elderly residents at a nursing home in Denmark. OBJECTIVE The aim of the study was to determine the prevalence of skin tears in the extremities and explore factors in relation to skin tears in elderly residents at a Danish nursing home. METHOD The study was designed as a point prevalence survey and conducted at a nursing home with 140 residents >65 years of age. The residents were assessed for presence, number and location of skin tears. Data were collected using a data collection sheet developed for this study. The survey team consisted of four expert nurses from a university hospital (two dermatology and two wound care nurses). Data were collected over a period of 10 hours spread over two days. RESULTS Of the 128 participating residents six had skin tears, yielding a prevalence of 4.6 %. In total, 10 skin tears were observed in the 6 residents. The frequency of previous skin tears was 19.5 %. This frequency was significantly higher in residents with skin tears than in those without skin tears (83.3 % versus 16.4 %, p<0.001). Analysis of the relation between skin tears or previous skin tears versus without skin tears or previous skin tears showed significant differences related to the presence of ecchymosis (76.9 %versus 14.7 %, p<0.0001). There were no other significant factors observed. CONCLUSION The low prevalence found in this study may reflect the focus on prevention of skin tears that the nursing home has maintained over the past year. Nevertheless, the appropriate prevention and management of residents with skin tears is an ongoing challenge for health professionals. |
<reponame>mindspore-ai/serving<filename>mindspore_serving/ccsrc/master/restful/http_process.cc
/**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "master/restful/http_process.h"
#include <map>
#include <vector>
#include <functional>
#include <utility>
#include <iostream>
#include <sstream>
#include <algorithm>
#include "common/serving_common.h"
#include "master/restful/http_handle.h"
#include "common/float16.h"
#include "master/server.h"
using mindspore::serving::proto::Instance;
using mindspore::serving::proto::PredictReply;
using mindspore::serving::proto::PredictRequest;
namespace mindspore {
namespace serving {
const int BUF_MAX = 0x7FFFFFFF;
static const std::map<DataType, HTTP_DATA_TYPE> infer_type2_http_type{{DataType::kMSI_Int32, HTTP_DATA_INT},
{DataType::kMSI_Float32, HTTP_DATA_FLOAT}};
static const std::map<HTTP_DATA_TYPE, DataType> http_type2_infer_type{{HTTP_DATA_INT, DataType::kMSI_Int32},
{HTTP_DATA_FLOAT, DataType::kMSI_Float32},
{HTTP_DATA_BOOL, DataType::kMSI_Bool},
{HTTP_DATA_STR, DataType::kMSI_String},
{HTTP_DATA_OBJ, DataType::kMSI_Bytes}};
static const std::map<std::string, DataType> str2_infer_type{
{"int8", DataType::kMSI_Int8}, {"int16", DataType::kMSI_Int16}, {"int32", DataType::kMSI_Int32},
{"int64", DataType::kMSI_Int64}, {"uint8", DataType::kMSI_Uint8}, {"uint16", DataType::kMSI_Uint16},
{"uint32", DataType::kMSI_Uint32}, {"uint64", DataType::kMSI_Uint64}, {"fp16", DataType::kMSI_Float16},
{"fp32", DataType::kMSI_Float32}, {"fp64", DataType::kMSI_Float64}, {"float16", DataType::kMSI_Float16},
{"float32", DataType::kMSI_Float32}, {"float64", DataType::kMSI_Float64}, {"bool", DataType::kMSI_Bool},
{"str", DataType::kMSI_String}, {"bytes", DataType::kMSI_Bytes}};
template <typename T>
bool RestfulService::IsString() {
return typeid(T).hash_code() == typeid(std::string).hash_code();
}
std::string RestfulService::GetString(const uint8_t *ptr, size_t length) {
std::string str;
for (size_t i = 0; i < length; i++) {
str += ptr[i];
}
return str;
}
Status RestfulService::CheckObjTypeMatchShape(DataType data_type, const std::vector<int64_t> &shape) {
if (data_type == kMSI_String || data_type == kMSI_Bytes) {
size_t elements_nums = std::accumulate(shape.begin(), shape.end(), 1LL, std::multiplies<size_t>());
if (elements_nums != 1) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "json object, only support scalar when data type is string or bytes, please check 'type' or 'shape'";
}
}
return SUCCESS;
}
RequestType RestfulService::GetReqType(const std::string &str) {
auto it = std::find(request_type_list_.begin(), request_type_list_.end(), str);
if (it == request_type_list_.end()) {
return kInvalidType;
}
if (*it == kInstancesRequest) {
return kInstanceType;
}
return kInvalidType;
}
std::string RestfulService::GetReqTypeStr(RequestType req_type) {
switch (req_type) {
case kInstanceType:
return kInstancesRequest;
default:
break;
}
return "";
}
Status RestfulService::CheckObjType(const string &type) {
Status status(SUCCESS);
auto it = str2_infer_type.find(type);
if (it == str2_infer_type.end()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json object, specified type:'" << type << "' is illegal";
}
return status;
}
DataType RestfulService::GetObjDataType(const json &js) {
DataType type = kMSI_Unknown;
if (!js.is_object()) {
return type;
}
auto it1 = js.find(kType);
if (it1 == js.end()) {
type = kMSI_Bytes;
} else {
auto type_str = it1.value();
auto it2 = str2_infer_type.find(type_str);
if (it2 != str2_infer_type.end()) {
type = it2->second;
}
}
return type;
}
std::string RestfulService::GetStringByDataType(DataType type) {
for (const auto &item : str2_infer_type) {
// cppcheck-suppress useStlAlgorithm
if (item.second == type) {
return item.first;
}
}
return "";
}
bool RestfulService::JsonMatchDataType(const json &js, DataType type) {
bool flag = false;
if (js.is_number_integer()) {
if (type >= kMSI_Int8 && type <= kMSI_Uint64) {
flag = true;
}
} else if (js.is_number_float()) {
if (type >= kMSI_Float16 && type <= kMSI_Float64) {
flag = true;
}
} else if (js.is_string()) {
if (type == kMSI_String) {
flag = true;
}
} else if (js.is_boolean()) {
if (type == kMSI_Bool) {
flag = true;
}
}
return flag;
}
std::vector<int64_t> RestfulService::GetObjShape(const json &js) {
std::vector<int64_t> shape;
auto it = js.find(kShape);
if (it != js.end()) {
shape = GetSpecifiedShape(it.value());
}
return shape;
}
std::vector<int64_t> RestfulService::GetArrayShape(const json &json_array) {
std::vector<int64_t> json_shape;
const json *tmp_json = &json_array;
while (tmp_json->is_array()) {
if (tmp_json->empty()) {
break;
}
json_shape.emplace_back(tmp_json->size());
tmp_json = &tmp_json->at(0);
}
return json_shape;
}
std::vector<int64_t> RestfulService::GetSpecifiedShape(const json &js) {
std::vector<int64_t> shape;
if (!js.is_array()) {
return shape;
}
if (js.empty()) {
return shape;
}
for (size_t i = 0; i < js.size(); i++) {
auto &item = js.at(i);
if (!item.is_number_unsigned()) {
return {};
} else {
shape.push_back(item.get<uint32_t>());
}
}
return shape;
}
DataType RestfulService::GetArrayDataType(const json &json_array, HTTP_DATA_TYPE *type_format_ptr) {
MSI_EXCEPTION_IF_NULL(type_format_ptr);
auto &type_format = *type_format_ptr;
DataType data_type = kMSI_Unknown;
const json *tmp_json = &json_array;
while (tmp_json->is_array()) {
if (tmp_json->empty()) {
return data_type;
}
tmp_json = &tmp_json->at(0);
}
if (tmp_json->is_number_integer()) {
type_format = HTTP_DATA_INT;
data_type = http_type2_infer_type.at(type_format);
} else if (tmp_json->is_number_float()) {
type_format = HTTP_DATA_FLOAT;
data_type = http_type2_infer_type.at(type_format);
} else if (tmp_json->is_boolean()) {
type_format = HTTP_DATA_BOOL;
data_type = http_type2_infer_type.at(type_format);
} else if (tmp_json->is_object()) {
type_format = HTTP_DATA_OBJ;
data_type = GetObjDataType(*tmp_json);
} else if (tmp_json->is_string()) {
type_format = HTTP_DATA_STR;
data_type = http_type2_infer_type.at(type_format);
}
return data_type;
}
Status RestfulService::CheckReqJsonValid(const json &js_msg) {
int count = 0;
for (auto &item : request_type_list_) {
auto it = js_msg.find(item);
if (it != js_msg.end()) {
count++;
auto request_type = GetReqType(item);
if (request_type == kInvalidType) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "only support instances mode";
}
request_type_ = request_type;
}
}
if (count != 1) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "key 'instances' expects to exist once, but actually " << count << " times";
}
return SUCCESS;
}
Status RestfulService::GetInstancesType(const json &instances) {
Status status{SUCCESS};
// Eg:{"instances" : 1}
if (!(instances.is_array() || instances.is_object())) {
instances_type_ = kNokeyWay;
return status;
}
// Eg:{"instances":{"A":1, "B":2}}
if (instances.is_object()) {
instances_type_ = kKeyWay;
return status;
}
// array:
if (instances.empty()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "instances value is array type, but no value";
}
auto first_instance = instances.at(0);
if (first_instance.is_object()) {
instances_type_ = kKeyWay;
} else {
instances_type_ = kNokeyWay;
}
return status;
}
Status RestfulService::CheckObj(const json &js) {
if (!js.is_object()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json is not object";
}
if (js.empty()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json object, value is empty";
}
// 1)required:b64 2)optional:type 3)optional:shape
if (js.size() > 3) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "json object, items size is more than 3, only support specified ['b64', 'type', 'shape']";
}
int b64_count = 0;
int shape_count = 0;
int type_count = 0;
for (auto item = js.begin(); item != js.end(); ++item) {
const auto &key = item.key();
auto value = item.value();
if (key == kB64) {
b64_count++;
} else if (key == kType) {
if (!value.is_string()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json object, key is 'type', value should be string type";
}
auto status = CheckObjType(value);
if (status != SUCCESS) {
return status;
}
type_count++;
} else if (key == kShape) {
if (!value.is_array()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json object, key is 'shape', value should be array type";
}
bool zero_dims_before = false;
for (auto it = value.begin(); it != value.end(); ++it) {
if (zero_dims_before) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "json object, key is 'shape', invalid shape value " << value.dump();
}
if (!(it->is_number_unsigned())) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "json object, key is 'shape', array value should be unsigned integer";
}
auto number = it->get<int32_t>();
if (number < 0) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "json object, key is 'shape', number value should not be negative number, shape value: "
<< value.dump();
}
if (number == 0) {
zero_dims_before = true;
}
}
shape_count++;
} else {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "json object, key is not ['b64', 'type', 'shape'], fail key:" << key;
}
}
if (b64_count != 1) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json object, 'b64' should be specified only one time";
}
if (type_count > 1) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json object, 'type' should be specified no more than one time";
}
if (shape_count > 1) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json object, 'shape' should be specified no more than one time";
}
return SUCCESS;
}
Status RestfulService::ParseItemScalar(const json &value, ProtoTensor *const pb_tensor) {
Status status(SUCCESS);
std::vector<int64_t> scalar_shape = {};
if (value.is_number_integer()) {
DataType type = kMSI_Int32;
pb_tensor->set_data_type(type);
pb_tensor->set_shape(scalar_shape);
pb_tensor->resize_data(pb_tensor->GetTypeSize(type));
status = GetScalarByType(type, value, 0, pb_tensor);
} else if (value.is_number_float()) {
DataType type = kMSI_Float32;
pb_tensor->set_data_type(type);
pb_tensor->set_shape(scalar_shape);
pb_tensor->resize_data(pb_tensor->GetTypeSize(type));
status = GetScalarByType(type, value, 0, pb_tensor);
} else if (value.is_boolean()) {
DataType type = kMSI_Bool;
pb_tensor->set_data_type(type);
pb_tensor->set_shape(scalar_shape);
pb_tensor->resize_data(pb_tensor->GetTypeSize(type));
status = GetScalarByType(type, value, 0, pb_tensor);
} else if (value.is_string()) {
DataType type = kMSI_String;
pb_tensor->set_data_type(type);
pb_tensor->set_shape(scalar_shape);
status = GetScalarByType(type, value, 0, pb_tensor);
} else if (value.is_null()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json value is null, it is not supported";
} else if (value.is_discarded()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json value is discarded type, it is not supported";
} else {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json value type is unregistered";
}
return status;
}
Status RestfulService::ParseItemObject(const json &value, ProtoTensor *const pb_tensor) {
auto status = CheckObj(value);
if (status != SUCCESS) {
return status;
}
DataType type = GetObjDataType(value);
if (type == kMSI_Unknown) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json object, type is unknown";
}
std::vector<int64_t> shape = GetObjShape(value);
bool is_tensor = false;
if (type != kMSI_String && type != kMSI_Bytes) {
is_tensor = true;
}
if (is_tensor) {
size_t shape_size = std::accumulate(shape.begin(), shape.end(), 1LL, std::multiplies<size_t>());
size_t type_size = pb_tensor->GetTypeSize(type);
pb_tensor->resize_data(shape_size * type_size);
}
status = CheckObjTypeMatchShape(type, shape);
if (status != SUCCESS) {
return status;
}
pb_tensor->set_data_type(type);
pb_tensor->set_shape(shape);
status = GetScalarByType(serving::kMSI_Bytes, value[kB64], 0, pb_tensor);
return status;
}
Status RestfulService::ParseItemArray(const json &value, ProtoTensor *const pb_tensor) {
HTTP_DATA_TYPE type_format = HTTP_DATA_NONE;
auto shape = GetArrayShape(value);
if (shape.empty()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json array, shape is empty";
}
DataType data_type = GetArrayDataType(value, &type_format);
if (data_type == kMSI_Unknown) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json array, data type is unknown";
}
bool is_tensor = false;
if (data_type != kMSI_String && data_type != kMSI_Bytes) {
is_tensor = true;
}
// instances mode:only support one item
if (request_type_ == kInstanceType) {
if (!is_tensor) {
size_t elements_nums = std::accumulate(shape.begin(), shape.end(), 1LL, std::multiplies<size_t>());
if (elements_nums != 1) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json array, string or bytes type only support one item";
}
}
}
// set real data type
pb_tensor->set_data_type(data_type);
pb_tensor->set_shape(shape);
if (is_tensor) {
size_t shape_size = std::accumulate(shape.begin(), shape.end(), 1LL, std::multiplies<size_t>());
size_t type_size = pb_tensor->GetTypeSize(data_type);
pb_tensor->resize_data(shape_size * type_size);
}
if (type_format == HTTP_DATA_OBJ) {
if (data_type != kMSI_Bytes && data_type != kMSI_String) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "json array, item is object type, object only support string or bytes type";
}
}
return RecursiveGetArray(value, 0, 0, type_format, pb_tensor);
}
// 1. parse request common func
Status RestfulService::ParseItem(const json &value, ProtoTensor *const pb_tensor) {
if (value.is_object()) {
return ParseItemObject(value, pb_tensor);
} else if (value.is_array()) {
return ParseItemArray(value, pb_tensor);
} else {
return ParseItemScalar(value, pb_tensor);
}
}
Status RestfulService::RecursiveGetArray(const json &json_data, size_t depth, size_t data_index,
HTTP_DATA_TYPE type_format, ProtoTensor *const request_tensor) {
Status status(SUCCESS);
std::vector<int64_t> required_shape = request_tensor->shape();
if (depth >= required_shape.size()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "invalid json array: current depth " << depth << " is more than shape dims " << required_shape.size();
}
if (!json_data.is_array()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "invalid json array: json type is not array";
}
if (json_data.size() != static_cast<size_t>(required_shape[depth])) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "invalid json array: json size is " << json_data.size() << ", the dim " << depth << " expected to be "
<< required_shape[depth];
}
if (depth + 1 < required_shape.size()) {
size_t sub_element_cnt =
std::accumulate(required_shape.begin() + depth + 1, required_shape.end(), 1LL, std::multiplies<size_t>());
for (size_t k = 0; k < json_data.size(); k++) {
status =
RecursiveGetArray(json_data[k], depth + 1, data_index + sub_element_cnt * k, type_format, request_tensor);
if (status != SUCCESS) {
return status;
}
}
} else {
status = GetArrayData(json_data, data_index, type_format, request_tensor);
if (status != SUCCESS) {
return status;
}
}
return status;
}
Status RestfulService::GetArrayData(const json &js, size_t data_index, HTTP_DATA_TYPE type,
ProtoTensor *const request_tensor) {
Status status(SUCCESS);
size_t element_nums = js.size();
if (type != HTTP_DATA_OBJ) {
for (size_t k = 0; k < element_nums; k++) {
auto &json_data = js[k];
if (!(json_data.is_number() || json_data.is_boolean() || json_data.is_string())) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json array, data should be number, bool, string or bytes";
}
auto flag = JsonMatchDataType(json_data, request_tensor->data_type());
if (!flag) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json array, elements type is not equal";
}
status = GetScalarByType(request_tensor->data_type(), json_data, data_index + k, request_tensor);
if (status != SUCCESS) {
return status;
}
}
} else {
for (size_t k = 0; k < element_nums; k++) {
auto &json_data = js[k];
auto value_type = GetObjDataType(json_data);
// Array:object only support string or bytes
if (value_type != kMSI_String && value_type != kMSI_Bytes) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json array, object type only support string or bytes type";
}
if (value_type != request_tensor->data_type()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json array, elements type is not equal";
}
status = GetScalarByType(value_type, json_data[kB64], data_index + k, request_tensor);
if (status != SUCCESS) {
return status;
}
}
}
return status;
}
Status RestfulService::GetScalarByType(DataType type, const json &js, size_t index, ProtoTensor *const request_tensor) {
Status status(SUCCESS);
if (type == kMSI_Unknown) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "data type is unknown";
}
switch (type) {
case kMSI_Bool:
status = GetScalarData<bool>(js, index, false, request_tensor);
break;
case kMSI_Int8:
status = GetScalarData<int8_t>(js, index, false, request_tensor);
break;
case kMSI_Int16:
status = GetScalarData<int16_t>(js, index, false, request_tensor);
break;
case kMSI_Int32:
status = GetScalarData<int32_t>(js, index, false, request_tensor);
break;
case kMSI_Int64:
status = GetScalarData<int64_t>(js, index, false, request_tensor);
break;
case kMSI_Uint8:
status = GetScalarData<uint8_t>(js, index, false, request_tensor);
break;
case kMSI_Uint16:
status = GetScalarData<uint16_t>(js, index, false, request_tensor);
break;
case kMSI_Uint32:
status = GetScalarData<uint32_t>(js, index, false, request_tensor);
break;
case kMSI_Uint64:
status = GetScalarData<uint64_t>(js, index, false, request_tensor);
break;
case kMSI_Float16:
status = GetScalarData<float>(js, index, false, request_tensor);
break;
case kMSI_Float32:
status = GetScalarData<float>(js, index, false, request_tensor);
break;
case kMSI_Float64:
status = GetScalarData<double>(js, index, false, request_tensor);
break;
case kMSI_String:
status = GetScalarData<std::string>(js, index, false, request_tensor);
break;
case kMSI_Bytes:
status = GetScalarData<std::string>(js, index, true, request_tensor);
break;
default:
auto type_str = GetStringByDataType(type);
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "data type:" << type_str << " is not supported";
}
return status;
}
template <typename T>
Status RestfulService::GetScalarData(const json &js, size_t index, bool is_bytes, ProtoTensor *const request_tensor) {
Status status(SUCCESS);
if (IsString<T>()) {
// 1.string
if (!js.is_string()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "get scalar data failed, type is string, but json is not string type";
}
auto value = js.get<std::string>();
if (is_bytes) {
DataType real_type = request_tensor->data_type();
auto tail_equal_size = GetTailEqualSize(value);
if (tail_equal_size == UINT32_MAX) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "'" << value << "' is illegal b64 encode string";
}
auto origin_size = GetB64OriginSize(value.length(), tail_equal_size);
std::vector<uint8_t> buffer(origin_size, 0);
auto target_size = Base64Decode(reinterpret_cast<uint8_t *>(value.data()), value.length(), buffer.data());
if (target_size != origin_size) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "decode base64 failed, size is not matched.";
}
if (real_type == kMSI_Bytes || real_type == kMSI_String) {
request_tensor->add_bytes_data(buffer.data(), origin_size);
} else {
auto type_size = request_tensor->GetTypeSize(real_type);
auto element_cnt = request_tensor->element_cnt();
if (origin_size != type_size * element_cnt) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "size is not matched, decode base64 size:" << origin_size
<< "; Given info: type:" << GetStringByDataType(real_type) << "; type size:" << type_size
<< "; element nums:" << element_cnt;
}
if (origin_size > 0) {
auto data = reinterpret_cast<T *>(request_tensor->mutable_data()) + index;
memcpy_s(data, origin_size, buffer.data(), buffer.size());
}
}
} else {
request_tensor->add_bytes_data(reinterpret_cast<uint8_t *>(value.data()), value.length());
}
} else {
DataType data_type = request_tensor->data_type();
auto flag = JsonMatchDataType(js, data_type);
if (!flag) {
auto type_str = GetStringByDataType(data_type);
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS)
<< "data type and json type is not matched, data type is:" << type_str;
}
// 2.number
if ((js.is_number() || js.is_boolean())) {
// 1)common number
auto data = reinterpret_cast<T *>(request_tensor->mutable_data()) + index;
*data = js.get<T>();
}
}
return status;
}
// 2.main
void RestfulService::RunRestful(const std::shared_ptr<RestfulRequest> &restful_request) {
auto restful_service = std::make_shared<RestfulService>();
restful_service->RunRestfulInner(restful_request, restful_service);
}
void RestfulService::RunRestfulInner(const std::shared_ptr<RestfulRequest> &restful_request,
const std::shared_ptr<RestfulService> &restful_service) {
MSI_TIME_STAMP_START(RunRestful)
auto status = ParseRequest(restful_request, &request_);
if (status != SUCCESS) {
std::string msg = "Parser request failed, " + status.StatusMessage();
restful_request->ErrorMessage(Status(status.StatusCode(), msg));
return;
}
auto callback = [restful_service, restful_request, time_start_RunRestful]() {
nlohmann::json predict_json;
Status status;
try {
status = restful_service->ParseReply(restful_service->reply_, &predict_json);
} catch (std::exception &e) {
MSI_LOG_ERROR << "Failed to construct the response: " << e.what();
restful_request->ErrorMessage(Status(status.StatusCode(), "Failed to construct the response"));
return;
}
if (status != SUCCESS) {
std::string msg = "Failed to construct the response: " + status.StatusMessage();
restful_request->ErrorMessage(Status(status.StatusCode(), msg));
} else {
restful_request->RestfulReplay(predict_json.dump());
}
MSI_TIME_STAMP_END(RunRestful)
};
auto dispatcher = Server::Instance().GetDispatcher();
dispatcher->DispatchAsync(request_, &reply_, callback);
}
// 3.parse request
Status RestfulService::ParseRequest(const std::shared_ptr<RestfulRequest> &restful_request,
PredictRequest *const request) {
Status status(SUCCESS);
// 1. parse common msg
status = ParseReqCommonMsg(restful_request, request);
if (status != SUCCESS) {
return status;
}
// 2. parse json
auto request_ptr = restful_request->decompose_event_request();
auto &js_msg = request_ptr->request_message_;
status = CheckReqJsonValid(js_msg);
if (status != SUCCESS) {
return status;
}
switch (request_type_) {
case kInstanceType:
status = ParseInstancesMsg(js_msg, request);
break;
default:
return INFER_STATUS_LOG_ERROR(FAILED) << "restful request only support instances mode";
}
return status;
}
Status RestfulService::ParseReqCommonMsg(const std::shared_ptr<RestfulRequest> &restful_request,
PredictRequest *const request) {
Status status(SUCCESS);
auto request_ptr = restful_request->decompose_event_request();
if (request_ptr == nullptr) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "Decompose event request is nullptr";
}
request->mutable_servable_spec()->set_name(request_ptr->model_name_);
request->mutable_servable_spec()->set_version_number(request_ptr->version_);
request->mutable_servable_spec()->set_method_name(request_ptr->service_method_);
return status;
}
Status RestfulService::ParseInstancesMsg(const json &js_msg, PredictRequest *const request) {
Status status = SUCCESS;
auto type = GetReqTypeStr(request_type_);
auto instances = js_msg.find(type);
if (instances == js_msg.end()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "instances request json should have instances key word";
}
// get instances way:{key, value} or {value}
status = GetInstancesType(*instances);
if (status != SUCCESS) {
return status;
}
switch (instances_type_) {
case kKeyWay: {
status = ParseKeyInstances(*instances, request);
break;
}
case kNokeyWay: {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "instances no key mode is not supported";
}
case kInvalidWay: {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "invalid request type";
}
}
return status;
}
Status RestfulService::ParseKeyInstances(const json &instances, PredictRequest *const request) {
Status status(SUCCESS);
if (instances.is_object()) {
// one instance:{"instances":{"A":1, "B": 2}}
if (instances.empty()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json object, value is empty";
}
status = PaserKeyOneInstance(instances, request);
if (status != SUCCESS) {
MSI_LOG_ERROR << "instances:parse one instance failed";
return status;
}
instances_nums_ = 1;
} else {
// multi instance:{"instances":[{}, {}]}
for (size_t i = 0; i < instances.size(); i++) {
auto &instance = instances.at(i);
if (!instance.is_object()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json array, instance is not object type";
}
if (instance.empty()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "json array, instance is object type, but no value";
}
status = PaserKeyOneInstance(instance, request);
if (status != SUCCESS) {
return status;
}
}
instances_nums_ = instances.size();
}
return status;
}
// instance_mgs:one instance, type is object
Status RestfulService::PaserKeyOneInstance(const json &instance_msg, PredictRequest *const request) {
Status status(SUCCESS);
auto instance = request->add_instances();
for (auto it = instance_msg.begin(); it != instance_msg.end(); ++it) {
auto key = it.key();
if (key.empty()) {
return INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "string key is empty";
}
auto value = it.value();
auto &map_item = *(instance->mutable_items());
proto::Tensor &tensor = map_item[key];
ProtoTensor pb_tensor(&tensor);
status = ParseItem(value, &pb_tensor);
if (status != SUCCESS) {
return status;
}
}
return status;
}
/************************************************************************************/
// 4.parse reply common func
Status RestfulService::ParseReplyDetail(const proto::Tensor &tensor, json *const js) {
Status status(SUCCESS);
const ProtoTensor pb_tensor(const_cast<proto::Tensor *>(&tensor));
auto shape = pb_tensor.shape();
if (shape.empty()) {
status = ParseScalar(pb_tensor, 0, js);
if (status != SUCCESS) {
return status;
}
} else {
status = CheckReply(pb_tensor);
if (status != SUCCESS) {
return status;
}
status = RecursiveParseArray(pb_tensor, 0, 0, js);
if (status != SUCCESS) {
return status;
}
}
return status;
}
Status RestfulService::ParseScalar(const ProtoTensor &pb_tensor, size_t index, json *const js) {
Status status(SUCCESS);
DataType data_type = pb_tensor.data_type();
if (data_type == kMSI_Unknown) {
return INFER_STATUS_LOG_ERROR(FAILED) << "Data type is unknown";
}
switch (data_type) {
case kMSI_Bool:
status = ParseScalarData<bool>(pb_tensor, false, index, js);
break;
case kMSI_Int8:
status = ParseScalarData<int8_t>(pb_tensor, false, index, js);
break;
case kMSI_Int16:
status = ParseScalarData<int16_t>(pb_tensor, false, index, js);
break;
case kMSI_Int32:
status = ParseScalarData<int32_t>(pb_tensor, false, index, js);
break;
case kMSI_Int64:
status = ParseScalarData<int64_t>(pb_tensor, false, index, js);
break;
case kMSI_Uint8:
status = ParseScalarData<uint8_t>(pb_tensor, false, index, js);
break;
case kMSI_Uint16:
status = ParseScalarData<uint16_t>(pb_tensor, false, index, js);
break;
case kMSI_Uint32:
status = ParseScalarData<uint32_t>(pb_tensor, false, index, js);
break;
case kMSI_Uint64:
status = ParseScalarData<uint64_t>(pb_tensor, false, index, js);
break;
case kMSI_Float16: {
const float16 *data = reinterpret_cast<const float16 *>(pb_tensor.data()) + index;
float value = half_to_float(*data);
*js = value;
break;
}
case kMSI_Float32:
status = ParseScalarData<float>(pb_tensor, false, index, js);
break;
case kMSI_Float64:
status = ParseScalarData<double>(pb_tensor, false, index, js);
break;
case kMSI_String:
status = ParseScalarData<std::string>(pb_tensor, false, index, js);
break;
case kMSI_Bytes:
status = ParseScalarData<std::string>(pb_tensor, true, index, js);
break;
default:
status = INFER_STATUS_LOG_ERROR(INVALID_INPUTS) << "reply data type is not supported";
break;
}
return status;
}
template <typename T>
Status RestfulService::ParseScalarData(const ProtoTensor &pb_tensor, bool is_bytes, size_t index, json *const js) {
Status status(SUCCESS);
if (!IsString<T>()) {
const T *data = reinterpret_cast<const T *>(pb_tensor.data()) + index;
T value = *data;
*js = value;
} else if (IsString<T>()) {
if (!is_bytes) {
auto str_nums = pb_tensor.bytes_data_size();
if (str_nums == 0) {
return INFER_STATUS_LOG_ERROR(FAILED) << "reply string, size is 0";
}
if (index >= str_nums) {
return INFER_STATUS_LOG_ERROR(FAILED) << "reply string, index:" << index << " is more than size:" << str_nums;
}
std::string value;
size_t length;
const uint8_t *ptr = nullptr;
pb_tensor.get_bytes_data(index, &ptr, &length);
value.resize(length);
memcpy_s(value.data(), length, reinterpret_cast<const char *>(ptr), length);
*js = value;
} else {
auto str_nums = pb_tensor.bytes_data_size();
if (str_nums == 0) {
return INFER_STATUS_LOG_ERROR(FAILED) << "reply bytes, size is 0";
}
if (index >= str_nums) {
return INFER_STATUS_LOG_ERROR(FAILED) << "reply bytes, index:" << index << " is more than size:" << str_nums;
}
std::string value;
size_t length;
const uint8_t *ptr = nullptr;
pb_tensor.get_bytes_data(index, &ptr, &length);
value.resize(length);
memcpy_s(value.data(), length, reinterpret_cast<const char *>(ptr), length);
auto target_size = GetB64TargetSize(length);
std::vector<uint8_t> buffer(target_size, 0);
auto size = Base64Encode(reinterpret_cast<uint8_t *>(value.data()), value.length(), buffer.data());
if (size != target_size) {
return INFER_STATUS_LOG_ERROR(FAILED)
<< "reply bytes, size is not matched, expected size:" << target_size << ", encode size:" << size;
}
std::string str = GetString(buffer.data(), buffer.size());
(*js)[kB64] = str;
}
}
return status;
}
Status RestfulService::RecursiveParseArray(const ProtoTensor &pb_tensor, size_t depth, size_t pos,
json *const out_json) {
Status status(SUCCESS);
std::vector<int64_t> required_shape = pb_tensor.shape();
if (depth >= required_shape.size()) {
return INFER_STATUS_LOG_ERROR(FAILED)
<< "result shape dims is larger than result shape size " << required_shape.size();
}
if (depth == required_shape.size() - 1) {
if (required_shape[depth] == 0) { // make empty array
out_json->push_back(json());
out_json->clear();
}
for (int i = 0; i < required_shape[depth]; i++) {
out_json->push_back(json());
json &scalar_json = out_json->back();
status = ParseScalar(pb_tensor, pos + i, &scalar_json);
if (status != SUCCESS) {
return status;
}
}
} else {
for (int i = 0; i < required_shape[depth]; i++) {
// array:
out_json->push_back(json());
json &tensor_json = out_json->back();
size_t sub_element_cnt =
std::accumulate(required_shape.begin() + depth + 1, required_shape.end(), 1LL, std::multiplies<size_t>());
status = RecursiveParseArray(pb_tensor, depth + 1, i * sub_element_cnt + pos, &tensor_json);
if (status != SUCCESS) {
return status;
}
}
}
return status;
}
Status RestfulService::CheckReply(const ProtoTensor &pb_tensor) {
Status status(SUCCESS);
DataType data_type = pb_tensor.data_type();
if (data_type == kMSI_Unknown) {
return INFER_STATUS_LOG_ERROR(FAILED) << "reply data type is unknown";
}
if (data_type == kMSI_String || data_type == kMSI_Bytes) {
auto shape = pb_tensor.shape();
if (shape.size() != 1) {
return INFER_STATUS_LOG_ERROR(FAILED)
<< "reply string or bytes, shape should be 1, given shape size:" << shape.size();
}
}
return status;
}
// 5.Parse reply
Status RestfulService::ParseReply(const PredictReply &reply, json *const out_json) {
Status status(SUCCESS);
switch (request_type_) {
case kInstanceType:
status = ParseInstancesReply(reply, out_json);
break;
default:
return INFER_STATUS_LOG_ERROR(FAILED) << "restful request only support instance mode";
}
return status;
}
Status RestfulService::ParseInstancesReply(const PredictReply &reply, json *const out_json) {
Status status(SUCCESS);
auto error_size = reply.error_msg_size();
auto reply_size = reply.instances().size();
if (error_size == 1 && reply_size == 0) {
(*out_json)[kErrorMsg] = reply.error_msg()[0].error_msg();
return SUCCESS;
}
if (error_size != 0 && error_size != instances_nums_) {
return INFER_STATUS_LOG_ERROR(FAILED) << "reply error size:" << error_size << " is not 0,1 or instances size "
<< instances_nums_ << ", reply instances size " << reply_size;
}
if (reply_size != instances_nums_) {
return INFER_STATUS_LOG_ERROR(FAILED)
<< "reply size:" << reply_size << " is not matched request size:" << instances_nums_;
}
(*out_json)[kInstancesReply] = json();
json &instances_json = (*out_json)[kInstancesReply];
for (int32_t i = 0; i < instances_nums_; i++) {
instances_json.push_back(json());
auto &instance = instances_json.back();
if (error_size != 0 && reply.error_msg()[i].error_code() != 0) {
instance[kErrorMsg] = reply.error_msg(i).error_msg();
continue;
}
auto &cur_instance = reply.instances(i);
auto &items = cur_instance.items();
if (items.empty()) {
return INFER_STATUS_LOG_ERROR(FAILED) << "reply instance items is empty";
}
for (auto &item : items) {
instance[item.first] = json();
auto &value_json = instance[item.first];
status = ParseReplyDetail(item.second, &value_json);
if (status != SUCCESS) {
return status;
}
}
}
return status;
}
} // namespace serving
} // namespace mindspore
|
The weekend is a good time to start backing up your mobile files and folders.
Losing your phone or having your tablet fall to its death can be hard on anyone, especially in this day and age where mobile devices have become an essential part of our lives. Just like with any computer, backing up your mobile apps and data can prove worthy when disaster strikes—or just after you’ve purchased a new phone and simply need to migrate data.
Thankfully, there are a plethora of applications in the Google Play store that provide backup services for devices of all types, but only a few we thought were worth considering. We tried to pick out the ones that stood out to us the most and offered what we’d want from a backup suite for our non-rooted devices. If you have any suggestions of applications you’ve used to back up your Android device that aren't listed here, feel free to tell us about it in the comments. We’ll do a follow-up in next week’s Android app roundup with your suggestions.
G Cloud Backup offers the ability to back up your messages, contacts, calendar appointments, music, applications, and other data to the cloud for easy restore to any other mobile device. All of the data is stored in G Cloud’s Amazon AWS cloud storage locker and is secured with 256-bit AES encryption. To access your data, G Cloud requires that you set up an account and password associated with your e-mail. You can store up to 1GB of data free and earn up to 8GB free by inviting friends to use the service or by completing simple tasks like mentioning the application on your Facebook page. You can also manage and check on your data online and schedule backups, as well as set when to stop backing up a device if the battery is below a certain percentage.
Enlarge / G Cloud's online backup manager.
G Cloud only allows the use of one particular handset to be associated with your account, but it offers the option to restore from a previous backup or start anew. On a new device, it will restore the backup in addition to existing data.
To backup data like text messages, call logs, and browser bookmarks, Super Backup is really quite "super" in its simplicity. This app allows you schedule backups for specific data at various intervals—starting from daily to monthly—as well as send the backup files to Gmail for safe keeping. You can also set up reminders to manually backup data from time to time, and there's a paid version for $1.99 if you’d rather not deal with advertisements.
App Backup & Restore works best at backing up and archiving specific applications on your device and offers features like batch backup, batch restore, quick uninstall, and multi-version backup. You can even send yourself an APK file by e-mail to safely hold on to side-loaded applications. It’s not as involved as other backup applications out there, but if you're looking for something to just simply backup applications, App Backup & Restore is very straightforward.
My Backup Pro has been touted as one of the best applications for backing up your device. You can easily restore, manage, and view all of the data that has been backed up and when you first start it up, MyBackup sets you sign up with a PIN number and password so that you can access your data online via the developer’s website (where you can also buy more space if you really enjoy the service). Backup to the cloud does take up a significant amount of time over backing up to the SD card, however, but you could always do both to ensure that you have two copies of all the data on your handset or tablet.
From the creators of the ever-popular Titanium Backup for rooted users comes Titanium Media Sync, which offers some very customizable options for backing up particular folders from your device. You can set the criteria for when to sync your device to help save yourself from eating up too much of your limited data plan, as well as set a time for the app to wait before it starts backing up after a reboot. You can also choose how much CPU priority to give the application and where to back up your data. Our favorite part about Titanium Media Sync is that you can back up specific folders to Dropbox or to your own personal FTP.
EDIT: I now realize this article was trying to give people to backup content as well as applications and app data. My apologies. I don't think Titanium Backup on its own can backup custom folders.
I use titanium backup free for regular backups and take a clockworkmod nandroid backup every few weeks for a whole phone backup. I also transfer any photo`s or other media to a pc regularly (along with the nandroid/titanium backups), where they get transfered to an external hd for safekeeping. Nothing else is needed.
Im not a fan of anything `cloudy` where personal data backup is concerned. You really dont know who is riffling through your files or if the service is going to lock you out of your data, either through a change of toc or just disappearing due to going bankrupt or a megaupload style takedown.
Florence. You forgot Carbon which backs up apps (and associated data), text messages and WiFi settings to your Google Drive / Dropbox account / SD card or Windows PC.
I use titanium backup free for regular backups and take a clockworkmod nandroid backup every few weeks for a whole phone backup. Nothing else is needed.
EDIT: Didn't see *your* edit.
That's a bit narrow-minded; the point of backing up is that you have it available off-device. You wouldn't store an image of your hard drive on the same hard drive you imaged, would you?
Nandroids mean nothing (not to mention, they don't backup content) if your phone is lost or if your phone completely dies (and you have things on internal storage).
I forgot to mention, I transfer the nandroid and titanium backups to an external hd via the pc. The sd card gets backed up regularly as well. I think I have all bases covered.
Carbon would have been a good addition to the list of apps.
I use a few thumbdrives (64,32gb, etc.) for backup. I have over 5gb just in Android apps, so cloud storage just wouldn't suffice. And call me old school for prefering to have physical backup over using the 'cloud'. I want to backup my movies and mp3s in a format that won't be erased because the cloud owner 'thinks' there may be copright issues.
you can then transfer it off to wherever...to the clouds, to a pc, etc.
I have the pro version (I used it often enough that I was able to justify paying the small price for it) and the pro has dropbox support.
This is a good list for the majority of non-rooted Android phones. Everyone who has root and doesn't know about Titanium Backup is missing out. It's a fantastic program that I didn't bat an eye to pay for. The default schedules are perfect for me as well. The utility of the application, in general, is vital to me on a regular basis. And it receives regular updates and improvements. Really just excellent stuff.
If you go Pro, you get its Ultrashell (or whatever it's called), which makes restores painless as you don't have to go through authorizing every install -- of which there can be hundreds.
I just saw your edit, please disregard my previous reply.
Seems that the backup service is manufacturer-dependant, I mean, not provided by Google. If Samsung or HTC doesn't support it, it is useless.
Probably that made sense 3 years ago in Android 2.2 when Google wanted to give some services for the manufacturers to provide (also lost device, I guess) but now it seems like a good idea to standardize, or at least to fall back to Google services when Samsung doesn't bother to implement a functionality.
It backs up to your google account if you set it up in the settings. It is manufacturer dependent only in whether it is implemented. My Galaxy S3 has the service installed (Settings - Back up and Reset) and I use it. I have been fortunate not to have had to actually use it yet though.
You can also implement full device (and mem card) encryption within Android (4.1+) options by setting up a full password or pin for security. I highly recommend that as well for a weekend "to do" while you are setting up a backup.
Whoa, you still need an app to do this on Android? I am genuinely very suprised to read this and thought Google would have had it sorted years ago. Or is this just a missing feature from non 4.x versions of Android?
How have people been migrating to new devices if they haven't been using one? Have they just been losing non-cloud based data?
Total aside, on my tablet( Android 2.3), the new mobile add for the Nest Thermostat DO NOT CLOSE. It obscures the first third of the article and even some of the comments here.
Especially in an article about Android, it's ironic that it's not possible to read the article because of something like that.
If you use a Google account and Google services, these backup tools are nearly pointless. I say nearly because Google won't back up your text messages unless you have your phone integrated with Google Voice. Photos, Apps, Contacts, Videos - all the rest can be automatically stored.
Google Services also does not backup apps that do not save to SD or settings (Bluetooth connections).
I love Titanium Backup Pro and TWRP for rooted phones.
I use My Backup Pro for none-rooted phones.
A good backup script is worth a thousand half-assed apps.
My Galaxy S3 has the service installed (Settings - Back up and Reset) and I use it. I have been fortunate not to have had to actually use it yet though.
Backup is the easy part – the real test is whether restore works. If possible, test restoring before you really need it… this, from bitter experience!
What? If you need a backup tool on your Android phone then you're doing it wrong.
Pretty much all data on my phone is an offline copy of some cloud or another. Why would you ever store local-only data in the first place?
If you're rooted, Orange Backup is the BEST system-wide backup solution. Granted, it is a *complete* Nandroid backup, so you can't restore individual apps, but I have Orange Backup make a full backup to my 16GB external SD card every night and keep the last two backups.
True, but why would I have my personal data on unencrypted access cloud than my own, local, quick upload speed FTP server? If they offer Wuala access, perhaps..
One of the main drawback of these apps are, they can back-up only specific kind of data like, they can back-up only contacts or only photos or only sms and contacts. That's when I came across the app truBackup ( https://play.google.com/store/apps/deta ... om.tfl.tbp ) which works like a dream when it comes to backing up your Android Device. It can store any kind of data like images, videos, apps, contacts and messages into a dropbox account with just a click. How cool is that? The premium version is now available for free. Try the app and see it for yourself.
I made a clockworkmod nand backup of my phone for the first time a few days back, prompted by an article I read online. Hours later, I managed to mess up a system setting, rendering my phone unusable and resulting in a boot loop. I did a restore, and everything was fixed to normal, with no data loss at all (not counting having to re-log in to the various services, and picking a few default apps once again). I was very pleasantly surprised how smoothly and painlessly the whole process went, considering my recklessness when causing the issue.
The apps I used are free versions, Online Nandroid and ROM Manager. My phone is of course rooted. |
Hormone release by primary amniotic fluid cell cultures Amniotic fluid cells have been widely used in prenatal diagnosis; however, there is great heterogeneity of the cells and their origin. In this study we analyze the karyotype and release of human chorionic gonadotropin (hCG), human chorionic somatomammotropin (hCS), free estriol (E 3), prolactin (PRL) and progesterone (P) of amniotic fluid cells from primary cultures of six normal and two anencephalic fetuses. In all the amniotic fluid samples there was release of hCG; in one amniotic fluid, in which several tetraploid colonies were found. PRL and P were also released. The heterogeneity of amniotic fluid cell morphology and their hormone release in culture was confirmed. The presence of hormones like hCG supports the trophoblastic origin of some amniotic fluid cells from normal and anencephalic fetuses. Other hormones, such as PRL and P could be used in the differential diagnosis between the karyotype of fetal membranes and the true fetal karyotype. Amniotic fluid cell cultures used in prenatal diagnosis yielded second trimester placental cells without any elaborate methods that could be used as cell models for hormone studies. |
<reponame>keerbin/cloudbreak<filename>core/src/main/java/com/sequenceiq/cloudbreak/reactor/api/event/stack/StackWithFingerprintsEvent.java
package com.sequenceiq.cloudbreak.reactor.api.event.stack;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.sequenceiq.cloudbreak.reactor.api.event.StackEvent;
public class StackWithFingerprintsEvent extends StackEvent {
private final Set<String> sshFingerprints;
public StackWithFingerprintsEvent(Long stackId, Set<String> sshFingerprints) {
super(stackId);
this.sshFingerprints = ImmutableSet.copyOf(sshFingerprints);
}
public Set<String> getSshFingerprints() {
return sshFingerprints;
}
}
|
Sequential test and parameter estimation for array processing of seismic data We present a sequential test and parameter estimation technique for measured seismic data from the GERESS array situated in Germany. A new approximation of the test statistic distribution and the test threshold is proposed. The sequentially rejecting Bonferroni-Holm test guarantees a global test level. This allows one to avoid the computationally expensive bootstrap method and leads to a simpler algorithm. Approximate conditional maximum likelihood estimates in the frequency domain are used to overcome the resolution limits of conventional methods for wideband signal processing and to construct the sequential test. The combination of global optimization via genetic algorithm and a local one using the scoring seems to be a good compromise to handle the problem of cumbersome maximization of the log-likelihood function over the parameters of interest. The algorithm for testing the number of signal phases is applied simultaneously with the estimation of the model parameters. |
MC premieres big-budget, Hype Williams-helmed clip in New York.
NEW YORK — With his determination to spare no expense in making his videos, chances are good that Kanye West is already a six-million-dollar man when it comes to spending money on his mini movies. But in his latest video endeavor, "Stronger," West conjures visions of Steve Austin, Lee Majors' "Six Million Dollar Man" character: The Louis Vuitton Don appears to be getting a few enhancements to his body.
On Tuesday night (technically Wednesday morning, as he was running a little late due to some last-minute edits), Kanye debuted the special-effects-filled video for "Stronger" at the Tribeca Cinemas. Legendary production duo and record label execs L.A. Reid and Babyface attended, as well as 'Ye's good friend Swizz Beatz.
"How you just gonna come up creepin'?" Swizz joked of Kanye's very low-profile entrance into his own affair. Swizz was standing outside, chatting with Hot 97's Miss Info, when Reid and Babyface pulled up to the red carpet in a black SUV. While attention was diverted to the legendary hitmaking duo, Kanye and his usual entourage (including longtime friend Don C) simply strolled to the door.
Inside, West thanked everyone for coming on such short notice. Make that almost no notice: E-mails about the gathering were sent out about five hours before the 9 p.m. "doors open" time, and warned people not to expect a night of dancing like at his recent birthday bash (which some say was the extravaganza of the year).
"This is not really a party, I just wanted y'all to see the video" before he left for Los Angeles a few hours later, 'Ye told the audience with a smile, noting "this is a rough [cut]" before the lights went low.
When it comes to "Stronger" — directed by Hype Williams, who also did West's recent "Can't Tell Me Nothing" clip — think longer. It took the pair some three months to make the video, from start to finish, and Kanye even had to convince Williams to stay on board because it was taking so long.
"Hype almost bailed three times," he divulged.
But Kanye also was proud of the fact that he had time to craft "Stronger" to his liking. "This is one of the first times we got to make a video like how we make music — we got to go back to it," he explained (see "Kanye, Cam'ron, More MCs Skip Million-Dollar Videos, Go Straight To The Web").
The MC also described the making of the video as part intricate planning, part run-and-gun, guerrilla-style shooting. They originally shot for nine days in Japan; the video's leading lady, singer Cassie, was called out on two days' notice and a genuine Japanese motorcycle gang was used in the video. For some scenes they knew exactly where they wanted to shoot, other shots were "stolen" in the streets — and they even had to ask friends for favors to film in locations such as the BAPE store and the BBC shop.
Perhaps most challenging of all, when they started filming, Kanye hadn't even written the second verse of the song.
Later, there were five days of re-shoots because 'Ye said the neon colors in the video reminded him too much of the colors used in recent 50 Cent and Maroon 5 clips.
As he tells it, Kanye knew "Stronger" would be a hit after he played Williams the song's sampled loop, which is from Daft Punk's "Harder, Better, Faster, Stronger" (West's DJ, A-Trak, played him the original Daft Punk record on tour last year).
"There were no drums or anything yet," Kanye said. Hype got hyped and started giving 'Ye inspiration to go futuristic — not just for the video, but for his entire Graduation LP. 'Ye said that's when the album started taking shape, whereas earlier he'd been "aimlessly making songs" (see " Kanye West Says He's 'Ready To Take Over The World Once Again' ").
"It inspired a whole movement," West said. He went back to some of the songs he had recorded and redid parts of them, and also watched films like "Total Recall" for more ideas. He recalled that when he was writing "Stronger," he started thinking about what he considers some of his recent mistakes.
"I made so many mistakes the past year, I started swimming in wack juice I needed to get out of," he said. "I would read blogs and they would be like, 'His shoelaces are untied, he's a b---h." He added that Late Registration co-producer Jon Brion even hinted that West should try to make music that made people see him as less annoying.
But instead of apologizing, Kanye uses the song's first verse to vent frustration: "Bow in the presence of greatness/ 'Cause right now thou has forsakenness this/ You should be honored by my lateness/ That I would even show up to this fake sh--."
"Instead of coming with, 'Oh, I'm sorry,' that song is an emancipation," Kanye explained.
As for the video itself ... Well, there's no way we're going to make Kanye abruptly end his West Coast trip, pack his Louis Vuitton bags, get back aboard a private jet and come straight to the MTV offices because we gave away the whole thing. But we can tell you this: There is an emphasis on performance and looking fly. There is a huge special-effects segment where Daft Punk, dressed as helmet-clad scientists or doctors, are pushing buttons in a control room while a machine big enough to fit a truck inside is working on Kanye as he lays on a table with wires attached to him — wearing nothing but a pair of boxers.
When the clip was finished, one person in the theater yelled out, "Cassie! I think I love you!" But most of the praise and applause were directed at Mr. West and the video. "I'mma talk sh-- and play it again," he said.
No one left the theater.
Kanye's Graduation LP comes out in late in August. |
UPDATE OCTOBER 14 6:50 PM PST — According to the University’s official Twitter account, Anita Sarkeesian has canceled her talk at the school.
I ran a story today about game designer Brianna Wu’s appearance on MSNBC, talking about #GamerGate. Once again, I was told that I’m ‘making a big deal over nothing,’ that it isn’t a thing, that I and all other social justice warriors are overreacting. Then I read this: Anita Sarkeesian, she of Feminist Frequency and the Tropes vs. Women in Video Games videos is once again the target of hate.
Sarkeesian is scheduled to speak at the Utah State University’s Center for Women and Gender Studies on October 15 for “Common Hour: Anita Sarkeesian.” The University received a threatening email. The (Standard Examiner has a link to it, and it’s horrifying. I’m not posting it, but I’m including the link so you can read it if you choose.) In the email, “the deadliest school shooting in American history” is threatened if they don’t cancel her appearance.
“If you do not cancel her talk, a Montreal Massacre style attack will be carried out against the attendees, as well as students and staff at the nearby Women’s Center,” the email says. “I have at my disposal a semi-automatic rifle, multiple pistols, and a collection of pipe bombs.”
Polygon explains: “The Montreal Massacre, also known as the École Polytechnique Massacre, took place in 1989 in Canada. Marc Lépine, who the email references, killed 14 women, injured 10 and killed four men in the name of ‘fighting feminism’ before committing suicide.”
“Feminists have ruined my life, and I will have my revenge, for my sake and the sake of all others they’ve wronged,” the writer, who claims to be a student at the school. He says increased security is futile. “We live in a nation of emasculated cowards too afraid to challenge the vile, misandrist harpies who seek to destroy them. Feminism has taken over every facet of our society, and women like Sarkeesian want to punish us for even fantasizing about being men,” he said.
The school is not canceling the talk. USU spokesman Tim Vitale said, “We’re an institution of higher learning. We educate people. This is what we do. This is a chance for students to listen for themselves to the topic, voice their opinions as they choose, and learn something.”
Big deal over nothing, huh? |
Historically used only in high-end supercomputers, interconnection networks are now found in systems of all sizes and all types: from large supercomputers to small embedded systems-on-a-chip (SoC) and from inter-processor networks to router fabrics. Indeed, as system complexity and integration continues to increase, many designers are finding in the interconnection networks technology more efficient ways to route packets and economic solutions to build computer clusters.
Interconnection networks for supercomputers in general, and particularly for recent massively parallel computing systems based on computer clusters, demand high performance requirements. The fundamental topics in the design of interconnection networks that determine the performance tradeoffs are: topology, routing, and flow-control.
Interconnection networks are built up of switching elements and topology is the pattern in which the individual switches are connected to other elements, like processors, memories and other switches. Among the known topologies, fat-trees have raised in popularity in the past few years and are used in many commercial high-performance switch-based point-to-point interconnects: for instance, InfiniBand connectivity products supplied by Mellanox Technologies (www.mellanox.com), Myrinet by Myricom (www.myri.com) and the networking products developed by Quadrics (www.quadrics.com).
Fat-tree topology is a particular case of a multistage interconnection/switching network, that is, a regular topology in which switches are identical and organized as a set of stages. Each stage is only connected to the previous and the next stage using regular connection patterns. A fat-tree topology is based on a complete tree: a set of processors is located at the leaves and each edge of the tree corresponds to a bidirectional channel. Unlike traditional trees, a fat-tree gets thicker near the root. In order not to increase the degree of the switches as they go nearer to the root, which makes the physical implementation unfeasible, an alternative implementation is the k-ary n-tree. In what follows, the term fat-tree also refers to k-ary n-trees.
A k-ary n-tree is composed of N=kn processing nodes and nkn−1 switches with a constant degree k≧1: each switch has 2k input ports and 2k outputs ports, being k of them ascending ports (through which the switch is connected to a next stage switch) and k descending ports (through which the switch is connected to a previous stage switch). Each processing node is represented as a n-tuple {0, 1, . . . k−1}n and each switch is defined as a pair <s, o>, being sε{0 . . . (n−1)} the stage at which the switch is located and stage 0 is considered as the closest one to the processing nodes, and o is a (n−1)-tuple {0, 1, . . . , k−1}n−1. In a fat-tree, two switches <s, on−2, . . . , o1, o0> and <s′, o′n−2, . . . , o′1, o′0> are connected by an edge, if and only if s′=s+1 and oi=o′i for all i≠s. On the other hand, there is an edge between the switch <0, on−2, . . . , o1, o0> and a processing node, represented the processing node as a series of n links: pn−1, . . . , p1, p0, if and only if oi=pi+1 for all iε{n−2, . . . , 1, 0}. Descending links of each switch will be labelled from 0 to k−1, and ascending links from k to 2k−1.
Routing is one of the most important design issues of interconnection networks. Routing schemes can be mainly classified as source and distributed routing. In source routing the entire path to the destination is known to the sender of a packet, so that the sender can specify the route, when sending data, which the packet takes through the network. Source routing is used in some networks, for instance in Myrinet, because routers are very simple. On the other hand, distributed routing allows more flexibility, but the routers are more complex. Distributed routing can be implemented by a fixed hardware specific to a routing function on a given topology, or by using forwarding tables that are very flexible but suffer from a lack of scalability. Examples of commercial interconnection networks using distributed routing are InfiniBand and Quadrics.
For both source and distributed routing, the routing strategy determines the path that each packet follows between a source-destination pair, performing adaptive or, otherwise, deterministic strategies or a combination of both. In deterministic routing, an injected packet traverses a fixed, predetermined, path between source and destination; while in adaptive routing schemes the packet may traverse one of the different alternative paths available from the packet source to its destination. Adaptive routing takes into account the status of the network when taking the routing decisions and usually better balances network traffic, and so this allows the network to obtain a higher throughput, however out-of-order packet delivery may be introduced, which is unacceptable for some applications. Deterministic routing algorithms usually do a very poor job balancing traffic among the network links, but they are usually easier to implement, easier to be deadlock-free and guarantee in-order delivery.
An adaptive routing algorithm is composed of the routing and selection functions. The routing function supplies a set of output channels based on the current and destination nodes. The selection function selects an output channel from the set of channels supplied by the routing function. For example, the selection function may choose at each stage the link with the lowest traffic load.
Routing in fat-trees is composed of two phases: an adaptive upwards phase and a deterministic downwards phase. The unique downwards path to the destination depends on the switch that has been reached in the upwards phase. In fat-trees, the decisions made in the upwards phase by the selection function can be critical, since it determines the switch reached in the ascending path and, hence, the unique downwards path to the destination. Therefore, the selection function in fat-trees has a strong impact on network performance.
A distributed deterministic routing strategy is implemented, for example, in InfiniBand, thus there is only one route per source-destination pair. Nonetheless, InfiniBand offers the possibility to use virtual destinations and there can be a plurality of virtual destinations corresponding to a real destination, allowing the traffic to be distributed through different adaptive routes determined between the source and each virtual destination, for the same source-destination pair. A sever drawback of this proposal [see “A Multiple LID Routing Scheme for Fat-Tree-Based InfiniBand Networks” by X. Lin, Y. Chung, and T. Huang, Parallel and Distributed Processing Symposium, April 2004], and in general of adaptive routing, is suffered when a given destination is congested, because the traffic keeps on being spread along the different adaptive routes, contributing to overall network congestion. |
<reponame>jcassidyav/nativescript-plugins
import { View } from '@nativescript/core';
export declare class CreditCardViewBase extends View {
}
export declare class CardMultilineWidgetBase extends View {
}
export declare function toPaymentMethodCardChecks(check: any): PaymentMethodCardCheckResult;
export declare function toPaymentMethodCardWalletType(type: any): PaymentMethodCardWalletType;
export declare function toCardFundingType(type: any): CardFundingType;
export declare function toSourceCard3DSecureStatus(status: any): SourceCard3DSecureStatus;
export declare function toSourceVerificationStatus(status: any): SourceVerificationStatus;
export declare function toSourceRedirectStatus(redirectStatus: any): SourceRedirectStatus;
export declare function toSourceType(type: any): SourceType;
export declare function toSourceUsage(usage: any): SourceUsage;
export declare function toSourceFlow(flow: any): SourceFlow;
export declare function toSourceStatus(status: any): SourceStatus;
export declare enum PaymentMethodCardCheckResult {
Pass = "pass",
Failed = "failed",
Unavailable = "unavailable",
Unchecked = "unchecked",
Unknown = "unknown"
}
export interface IPaymentMethodCardChecks {
readonly addressLine1Check: PaymentMethodCardCheckResult;
readonly addressPostalCodeCheck: PaymentMethodCardCheckResult;
readonly cvcCheck: PaymentMethodCardCheckResult;
}
export interface IPaymentMethodCardNetworks {
readonly available: string[];
readonly preferred: string;
}
export interface IPaymentMethodThreeDSecureUsage {
readonly supported: boolean;
}
export interface IPaymentMethodAddress {
readonly city: string;
readonly country: string;
readonly line1: string;
readonly line2: string;
readonly postalCode: string;
readonly state: string;
}
export interface IPaymentMethodCardWalletMasterpass {
readonly billingAddress: IPaymentMethodAddress;
readonly email: string;
readonly name: string;
readonly shippingAddress: IPaymentMethodAddress;
}
export declare enum PaymentMethodCardWalletType {
AmexExpressCheckout = "amexExpressCheckout",
ApplePay = "applePay",
GooglePay = "googlePay",
Masterpass = "masterpass",
SamsungPay = "samsungPay",
VisaCheckout = "visaCheckout",
Unknown = "unknown"
}
export interface IPaymentMethodCardWalletVisaCheckout {
readonly billingAddress: IPaymentMethodAddress;
readonly email: string;
readonly name: string;
readonly shippingAddress: IPaymentMethodAddress;
readonly dynamicLast4: string;
}
export interface IPaymentMethodCardWalletAmexExpressCheckout {
readonly dynamicLast4: string;
}
export interface IPaymentMethodCardWalletApplePay {
readonly dynamicLast4: string;
}
export interface IPaymentMethodCardWalletGooglePay {
readonly dynamicLast4: string;
}
export interface IPaymentMethodCardWalletSamsungPay {
readonly dynamicLast4: string;
}
export interface IPaymentMethodCardWallet {
readonly masterpass: IPaymentMethodCardWalletMasterpass;
readonly type: PaymentMethodCardWalletType;
readonly visaCheckout: IPaymentMethodCardWalletVisaCheckout;
}
export interface IPaymentMethodCard {
readonly brand: CardBrand;
readonly checks: IPaymentMethodCardChecks;
readonly country: string;
readonly expMonth: number;
readonly expYear: number;
readonly fingerprint: string;
readonly funding: string;
readonly last4: string;
readonly networks: IPaymentMethodCardNetworks;
readonly threeDSecureUsage: IPaymentMethodThreeDSecureUsage;
readonly wallet: IPaymentMethodCardWallet;
}
export interface IAddress {
city: string;
country: string;
email: string;
line1: string;
line2: string;
name: string;
phone: string;
postalCode: string;
state: string;
readonly ios: any;
readonly android: any;
}
export declare function GetBrand(brand: any): CardBrand;
export declare enum CardBrand {
AmericanExpress = "amex",
Discover = "discover",
JCB = "jcb",
DinersClub = "diners",
Visa = "visa",
MasterCard = "mastercard",
UnionPay = "unionpay",
Unknown = "unknown"
}
export declare enum CardFunding {
Credit = "credit",
Debit = "debit",
Prepaid = "prepaid",
Unknown = "unknown"
}
export declare enum PaymentMethodType {
Card = "card",
CardPresent = "cardPresent",
Fpx = "fpx",
Ideal = "ideal",
SepaDebit = "sepaDebit",
AuBecsDebit = "auBecsDebit",
BacsDebit = "bacsDebit",
Sofort = "sofort",
P24 = "p24",
Bancontact = "bancontact",
Giropay = "giropay",
Eps = "eps",
Oxxo = "oxxo",
Alipay = "alipay",
GrabPay = "grabPay",
PayPal = "payPal",
Unknown = "unknown"
}
export declare enum CaptureMethod {
Automatic = "automatic",
Manual = "manual"
}
export interface ICard {
readonly native: any;
readonly brand: CardBrand;
readonly name: string;
readonly address: IAddress;
readonly currency: string;
readonly last4: string;
readonly dynamicLast4: string;
readonly fingerprint: string;
readonly funding: CardFunding;
readonly country: string;
}
export interface ICardParams {
readonly native: any;
name: string;
currency: string;
address: IAddress;
}
export interface IToken {
id: string;
bankAccount: IBankAccount;
card: ICard;
created: Date;
ios: any;
android: any;
liveMode: boolean;
}
export declare enum SourceFlow {
Redirect = "redirect",
Receiver = "receiver",
CodeVerification = "codeVerification",
None = "none"
}
export declare enum SourceStatus {
Canceled = "canceled",
Chargeable = "chargeable",
Consumed = "consumed",
Failed = "failed",
Pending = "pending"
}
export declare enum CardFundingType {
Debit = "debit",
Credit = "credit",
Prepaid = "prepaid",
Other = "other"
}
export declare enum SourceCard3DSecureStatus {
Required = "required",
Optional = "optional",
NotSupported = "notSupported",
Recommended = "recommended",
Unknown = "unknown"
}
export interface ISourceCardDetails {
readonly brand: CardBrand;
readonly country: string;
readonly expMonth: number;
readonly expYear: number;
readonly funding: CardFundingType;
readonly isApplePayCard: boolean;
readonly last4: string;
readonly threeDSecureUsage: SourceCard3DSecureStatus;
readonly android: any;
readonly ios: any;
readonly dynamicLast4: string;
}
export interface ISourceKlarnaDetails {
readonly clientToken: string;
readonly purchaseCountry: string;
}
export interface ISourceOwner {
readonly address: IAddress;
readonly email: string;
readonly name: string;
readonly phone: string;
readonly verifiedAddress: IAddress;
readonly verifiedEmail: string;
readonly verifiedName: string;
readonly verifiedPhone: string;
}
export interface ISourceReceiver {
readonly address: string;
readonly amountCharged: number;
readonly amountReceived: number;
readonly amountReturned: number;
readonly apiResponse: Readonly<{}>;
}
export declare enum SourceRedirectStatus {
Pending = "pending",
Succeeded = "succeeded",
Failed = "failed",
NotRequired = "notRequired",
Unknown = "unknown"
}
export interface ISourceRedirect {
readonly returnURL: string;
readonly status: SourceRedirectStatus;
readonly url: string;
readonly apiResponse: Readonly<{}>;
readonly ios: any;
readonly android: any;
}
export interface ISourceSEPADebitDetails {
readonly bankCode: string;
readonly country: string;
readonly fingerprint: string;
readonly last4: string;
readonly mandateReference: string;
readonly mandateURL: string;
readonly apiResponse: Readonly<{}>;
readonly ios: any;
readonly android: any;
}
export declare enum SourceType {
Bancontact = "bancontact",
Card = "card",
Giropay = "giropay",
IDEAL = "ideal",
SEPADebit = "sepaDebit",
Sofort = "sofor",
ThreeDSecure = "threeDSecure",
Alipay = "alipay",
P24 = "p24",
EPS = "eps",
Multibanco = "multibanco",
WeChatPay = "wechatPay",
Klarna = "klarna",
Unknown = "unknown"
}
export declare enum SourceUsage {
Reusable = "reusable",
SingleUse = "singleUser",
Unknown = "unknown"
}
export declare enum SourceVerificationStatus {
Pending = "pending",
Succeeded = "succeeded",
Failed = "failed",
Unknown = "unknown"
}
export interface ISourceVerification {
readonly attemptsRemaining: number;
readonly status: SourceVerificationStatus;
readonly apiResponse: Readonly<{}>;
}
export interface ISourceWeChatPayDetails {
readonly weChatAppURL: string;
readonly apiResponse: Readonly<{}>;
}
export interface ISource {
/**in pennies*/
readonly amount: number;
readonly cardDetails: ISourceCardDetails;
readonly clientSecret?: string;
readonly created: Date;
readonly currency?: string;
readonly details: Readonly<{}>;
readonly flow: SourceFlow;
readonly klarnaDetails: ISourceKlarnaDetails;
readonly metaData: Readonly<{}>;
readonly owner: ISourceOwner;
readonly receiver: ISourceReceiver;
readonly redirect: ISourceRedirect;
readonly sepaDebitDetails: ISourceSEPADebitDetails;
readonly type: SourceType;
readonly usage: SourceUsage;
readonly verification: ISourceVerification;
readonly weChatPayDetails: ISourceWeChatPayDetails;
readonly apiResponse: Readonly<{}>;
readonly id: string;
readonly liveMode: boolean;
readonly status: SourceStatus;
readonly android: any;
readonly ios: any;
}
export interface IPaymentMethod {
readonly native: any;
id: string;
created: Date;
type: PaymentMethodType;
billingDetails: object;
card: IPaymentMethodCard;
customerId: string;
metadata: object;
}
export interface IStripePaymentIntent {
readonly native: any;
id: string;
clientSecret: string;
amount: number;
captureMethod: "manual" | "automatic";
created: Date;
currency: string;
description: string;
requiresAction: boolean;
status: StripePaymentIntentStatus;
}
export declare const enum StripePaymentIntentStatus {
RequiresPaymentMethod = "requires_payment_method",
RequiresConfirmation = "requires_confirmation",
RequiresAction = "requires_action",
Processing = "processing",
Succeeded = "succeeded",
RequiresCapture = "requires_capture",
Canceled = "canceled"
}
export declare const enum StripeRedirectState {
NotStarted = 0,
InProgress = 1,
Cancelled = 2,
Completed = 3
}
export declare enum BankAccountHolderType {
Individual = "individual",
Company = "company"
}
export declare enum BankAccountStatus {
New = "new",
Validated = "validated",
Verified = "verified",
VerificationFailed = "verificationFailed",
Errored = "errored"
}
export interface IBankAccount {
readonly accountHolderName: string;
readonly accountHolderType: BankAccountHolderType;
readonly bankName: string;
readonly country: string;
readonly currency: string;
readonly fingerprint: string;
readonly last4: string;
readonly metadata: Readonly<{}>;
readonly routingNumber: string;
readonly status: BankAccountStatus;
}
|
/**
* Validate the correctness of the result. Check if the page contains the attack string If it is so the risk is high
* that we have an XSS vulnerability
*/
@Override
protected void postValidate() throws Exception
{
final HtmlPage page = getHtmlPage();
final boolean check = page.getWebResponse().getContentAsString().contains(attackString);
Assert.assertFalse("Page contains attack string '" + attackString + "'.", check);
if (input == null)
{
for (final HtmlElement input : inputs)
{
Assert.assertFalse(inputValues.isEmpty());
((HtmlInput) input).setValueAttribute(inputValues.remove(0));
}
}
else
{
Assert.assertTrue(inputValues.size() == 1);
input.setValueAttribute(inputValues.get(0));
}
} |
Terry Fox won no races nor set any Canadian running records. There wasn't a frame of reference in 1980 for an above-the-knee amputee running almost a marathon daily on an artificial leg for 143 consecutive days.
An exhibit unveiled Tuesday at Canada's Sports Hall of Fame just days away from his namesake run would have meant a lot to Terry Fox, says younger brother Darrell.
Terry Fox saw his Marathon of Hope as much of an athletic endeavour as it was a campaign to raise money and awareness about cancer.
Story continues below advertisement
"Terry did not crave recognition for himself. In fact he ran away from it," Darrell said. "He did appreciate being recognized as an athlete.
"He thought what he did, what he accomplished was an athletic feat, but there were no benchmarks, no standards. He wasn't running against anyone. He was running in the greatest race of all."
The 36th edition of the Terry Fox Run will be held in cities and towns across Canada on Sunday. About $700 million has been raised in his name for cancer treatment and research.
Fox lost his right leg to bone cancer at the age of 18 in 1977.
On April 12, 1980, he dipped his prosthetic leg into ocean waters off of St. John's, N.L., to begin his cross-Canada run home to Vancouver. He was accompanied by 17-year-old Darrell and high-school buddy Doug Alward.
There were no cell phones nor social media heralding his journey. It was word of mouth and television and newspapers that helped Fox's story capture the heart and imagination of a country.
"We were three young guys in a stinky Ford van traversing the country one mile at a time," Darrell recalled.
Story continues below advertisement
Story continues below advertisement
"I was a sponge to what Terry was accomplishing. I was witnessing it, I was seeing the reaction of every day Canadians on the side of the road. That's what I experience every day now from that next generation who are learning the story. They're not only learning the story of Terry Fox. They're embracing it."
The return of cancer to his lungs halted Fox in Thunder Bay, Ont., after 5,342 kilometres. Fox died June 28, 1981 at age 22.
He was quickly inducted into Canada's Sports Hall of Fame two months after his death. Fox ranked second to Tommy Douglas in a 2004 "greatest Canadian" poll and program conducted by CBC.
"Survival rates for all forms of cancer have increased dramatically," Darrell said. "Terry, and the form of cancer he had in 1980, he was told he had a 20- to 30-per-cent chance of living.
"Today, he'd have an over 80-per-cent chance of living and he may not have lost his leg to cancer. That's very powerful and speaks to the investment in cancer research and that it is making a difference."
Two-time Olympic speedskating champion Catriona Le May Doan was a nine-year-old just starting to skate when she saw images of Fox on her television screen.
Story continues below advertisement
"As a little girl I thought 'why doesn't he just stop?"' the Hall of Fame inductee told a group of schoolchildren at the Hall of Fame. "As I got a little older I became so inspired that Terry Fox never gave up.
"Every one of us, adults and kids, until our last days, we hope to one day inspire somebody. We don't want to inspire somebody for a moment. We want to inspire somebody for a lifetime. That's what a true champion is. That's what Terry Fox did."
The Hall of Fame in Calgary devoted a room to the travelling exhibit entitled "Terry Fox: Running to the Heart of Canada" and organized by the Canadian Museum of History.
Marathon of Hope artifacts have also been on display this year in Saskatoon, Belleville, Ont., Winnipeg, Kitchener, Ont., and Nanaimo, B.C.
Children ran their fingers over a large bust of Fox's head in Calgary. Artifacts also include an Edmonton Oilers jersey given to Fox by Wayne Gretzky.
The exhibit will remain in Calgary until Dec. 31. |
from .prediction_problem_generator import * # noqa
from .prediction_problem import * # noqa
from .cutoff_strategy import CutoffStrategy # noqa
from .labeler import * # noqa
from .prediction_problem_saver import * # noqa
|
Several individuals and entities have begun distancing themselves from Saudi Arabia following the disappearance of journalist and prominent Saudi critic Jamal Khashoggi.
Khashoggi was last seen on October 2, when he entered into the Saudi Consulate in Istanbul to secure official documents for his upcoming wedding to his Turkish fiance Hatice Cengiz.
The 59-year-old, who formerly served as an adviser to senior officials in the Saudi government and who had been living in self-imposed exile in the US, has not been seen since.
Some have speculated that he could have been kidnapped or killed inside the consulate, reportedly at the order of the Crown Prince Mohammed bin Salman using a team of hit men flown in specially to undertake the task.
Official response to Khashoggi's disappearance have been mixed.
Saudi officials claim that The Washington Post contributor left the consulate, but haven't provided any definitive proof. Turkish officials previously alleged that Khashoggi was killed and claim there's no evidence he ever left the consulate, while Canada, the UN, and President Trump have expressed "concern" over the journalist's whereabouts.
In a story published Thursday, The Washington Post said the Turkish government told US officials it has audio and video showing that Khashoggi was killed inside the consulate.
Global business leaders, policymakers, media moguls and tech executives have also taken notice and are beginning to move away from dealings with Saudi Arabia and its crown prince, Mohammed bin Salman.
Sir Richard Branson with Saudi Crown Prince Mohammed bin Salman at Virgin Galactic's hanger in the Mojave desert, April 2, 2018.
Sir Richard Branson and Virgin Group are severing ties with Saudi Arabia because of the Khashoggi case.
In a blog post on Virgin Group's website, Branson announced that Virgin Galatic and Virgin Orbit will suspend its discussions with the Public Investment Fund of Saudi Arabia.
"What has reportedly happened in Turkey around the disappearance of journalist Jamal Khashoggi, if proved true, would clearly change the ability of any of us in the West to do business with the Saudi Government," Branson wrote. "We have asked for more information from the authorities in Saudi and to clarify their position in relation to Mr. Khashoggi."
Nearly two dozen senators, led by the Foreign Relations Committee chairman Bob Corker of Tennessee and the Democratic ranking member Sen. Bob Menendez of New Jersey, have sent a letter to US President Donald Trump, recommending an investigation and possible sanctions against those found to be involved in Khashoggi's disappearance.
Republican and Democratic lawmakers are also pushing to block Saudi arms sales.
Former US energy secretary Ernest Moniz suspended his membership on an advisory board for a $500 billion Saudi megacity project called Neom.
"Given current events, I am suspending my participation on the Neom board. Going forward, my engagement with the advisory board will depend on learning all the facts about Jamal Khashoggi's disappearance over the coming days and weeks," Moniz said in a statement provided to Business Insider.
Dan Doctoroff, the founder of Sidewalk Labs, an urban planning unit of the Google parent company, Alphabet, also retreated from the Neom project.
In a statement, spokesperson Dan Levitan indicated that Doctoroff's inclusion on the list of executives said to be on the advisory board — first reported by Saudi news outlet Argaam— was "incorrect."
"He is not a member of the Neom advisory board," Levitan said. The spokesman did not respond to follow-up questions from Business Insider news editor Rob Price about whether Doctoroff had ever been associated with the NEOM advisory board.
Kroes told The Wall Street Journal she was also suspending her role in the Neom project "until more is known" on Khashoggi's disappearance.
Altman was also on the advisory board for the Saudi mega-project.
"I am suspending my involvement with the Neom advisory board until the facts regarding Jamal Khashoggi's disappearance are known," Altman said, according to The Wall Street Journal.
The New York Times pulled its sponsorship of the Future Investment Initiative (FII), a major conference which was set to be hosted by the crown prince Mohammed bin Salman and the kingdom's sovereign wealth fund in Riyadh.
Andrew Ross Sorkin, a New York Times columnist, said he was "terribly distressed by the disappearance of journalist Jamal Khashoggi and reports of his murder," and said he would not attend the conference.
Zanny Minton Beddoes, who serves as editor-in-chief at The Economist, is also pulling away from the FII conference.
Spokeswoman Lauren Hackett told Reuters Beddoes would no longer be participating.
Huffington, who founded HuffPost and had a seat on the advisory board for FII, said she no longer plans to attend, The Wall Street Journal reported.
Case was scheduled to speak at the conference, but he said on Thursday: "I was looking forward to returning to Riyadh this month to speak at the Future Investment Initiative conference, and participate in a Red Sea Project meeting."
"In light of recent events, I have decided to put my plans on hold, pending further information regarding Jamal Khashoggi."
Darren McCollester/Getty Images for NantHealth, Inc.
"Dr. Patrick Soon-Shiong will not be attending the upcoming Future Investment Initiative event in Riyadh," a spokesman told CNBC.
A spokesman for Bakish said he has decided not to attend FII, per Reuters. Bakish was slated to speak at the event.
Harbour Group is one of several lobbying firms that represent the Saudi government. The firm earned $80,000 per month to represent the Saudi Embassy in Washington, but ended its contract on Thursday, The New York Times reported, citing the firm's managing director, Richard Mintz.
Uber CEO Dara Khosrowshahi withdrew from the conference on Thursday evening, where he was due to speak.
"I'm very troubled by the reports to date about Jamal Khashoggi," he said in a statement. "We are following the situation closely, and unless a substantially different set of facts emerges, I won't be attending the FII conference in Riyadh."
The Silicon Valley-based ride-sharing app is partly funded by Saudi Arabia — Saudi state's Public Investment Fund injected $3.5 billion into the company in June.
JP Morgan Chase & Co Chief Executive Jamie Dimon pulled away from the conference on Sunday.
The company did not elaborate on why Dimon pulled out or if it specifically had to do with Khashoggi's disappearance.
Ford Motor Co. said Chairman Bill Ford called off his upcoming trip to the Middle East, which included a stop at the conference in Riyadh. The company did not comment on whether Khashoggi's case played a role in his cancelation.
Fink pressed Saudi officials to postpone the event but later decided to drop out of the event, The New York Times reported, citing sources familiar with the matter.
Schwarzman also sought to get the event postponed before deciding to drop out, the Times reported.
Mnuchin pulled out of an appearance at FII on Thursday after initially saying outrage over Khashoggi's disappearance.
Fox Business pulled out of FII late Thursday.
The network was the last remaining American sponsor of the event. Its host Maria Bartiromo was scheduled to speak at the conference, but said she would not attend unless she was provided an "unrestricted interview" with Crown Prince Mohammed bin Salman, Axios said. |
This invention generally relates to a device for controlling the tone arm of a record player, and more particularly, the present invention relates to a device for controlling vertical and/or horizontal attitudes of the tone arm equipped with a moving coil type pickup.
In a record player having a pickup of moving coil type, the vertical and horizontal positions of the moving coil with respect to the provided magnetic field of the pickup has to be controlled so that the moving coil, which generates an output voltage indicative of the picked up information, is kept at an optimum position with respect to the magnetic field irrespective of the warp or curve of the playing phonograph disk. Namely, if the moving coil operates off the optimum position, the output signal from the pickup would be distorted.
In some conventional record players, the output signal of the moving coil type pickup is processed to produce a tone arm control signal. The vertical and horizontal position of the moving coil with respect to the yoke is thus controlled so that the moving coil(s) is(are) always kept at a right position irrespective of the warp and/or eccentricity of the disk. However, since the moving coil per se produces its output signal which is in proportion to the moving velocity thereof, the low frequency output voltage indicative of the warp of the disk available for controlling the arm is very low. For this reason, in the conventional record players, the position of the moving coil could not be accurately controlled to the optimum position especially in the case that the up-down frequency of the moving coil is very low. |
Above Photo: Glittering future. (Reuters/Carlos Barria)
One of the biggest criticisms of the renewable-energy industry is that it has been propped up by government subsidies. There is no doubt that without government help, it would have been much harder for the nascent technology to mature. But what’s more important is whether there has been a decent return on taxpayers’ investment.
A new analysis in Nature Energy gives renewable-energy subsidies the thumbs-up. Dev Millstein of Lawerence Berkeley National Laboratory and his colleagues find that the fossil fuels not burnt because of wind and solar energy helped avoid between 3,000 and 12,700 premature deaths in the US between 2007 and 2015. Fossil fuels produce large amounts of pollutants like carbon dioxide, sulfur dioxide, nitrogen oxides, and particulate matter, which are responsible for ill-health and negative climate effects.
The researchers found that the US saved between $35 billion and $220 billion in that period because of avoided deaths, fewer sick days, and climate-change mitigation.
How do these benefits compare to the US government’s outlays? “The monetary value of air quality and climate benefits are about equal or more than state and federal financial support to wind and solar industries,” says Millstein.
Between 2007 and 2015, Quartz’s own analysis* finds that the US government likely spent between $50 billion and $80 billion on subsidies for those two industries. Even on the lower end of the benefits and higher end of subsidies, just the health and climate benefits of renewable energy return about half of taxpayers’ money. If the US were to stop subsidies now, those benefits would continue to accrue for the lifetime of the already existing infrastructure, improving the long-term return of the investments.
What’s more, those benefits do not account for everything. Creation of a new industry spurs economic growth, creates new jobs, and leads to technology development. There isn’t yet an estimation of what sort of money that brings in, but it’s likely to be a tidy sum.
To be sure, the marginal benefits of additional renewable energy production will start to fall in the future. That is, for every new megawatt of renewable energy produced, an equal amount of pollution won’t be avoided, which means the number of lives saved, and monetary benefits generated, will fall. But Millstein thinks that we won’t reach that point for some time—at least in the US.
The debate whether subsidies to the renewable industry are worth it rages across the world. Though the results of this study are only directly applicable to the US, many rich countries have similar factors at play and are likely to produce similar cost-benefit analyses |
<reponame>cflowe/ACE<filename>ace/pre.h
// -*- C++ -*-
//=============================================================================
/**
* @file pre.h
*
* $Id: pre.h 97272 2013-08-09 17:58:02Z johnnyw $
*
* @author <NAME> <<EMAIL>>
*
* This file saves the original alignment rules and changes the alignment
* boundary to ACE's default.
*/
//=============================================================================
// No header guard
#if defined (_MSC_VER)
# pragma warning (disable:4103)
# pragma pack (push, 8)
#elif defined (__BORLANDC__)
# pragma option push -a8 -b -Ve- -Vx- -w-rvl -w-rch -w-ccc -w-obs -w-aus -w-pia -w-inl -w-sig
# if (__BORLANDC__ == 0x660)
// False warning: Function defined with different linkage, reported to
// Embarcadero as QC 117740
# pragma option push -w-8127
# endif
# pragma nopushoptwarn
# pragma nopackwarning
#endif
|
Research of algorithms for road marking recognition in the lane departure warning system The way to improve the safety of vehicles using ADAS systems has successfully proved itself in practice. The use of ADAS systems in vehicles is mandatory in many countries of the world and is accepted at the state level. One of the most widely used ADAS systems is the Lane Departure Warning System (LDWS). The paper describes the principles of operation of existing LDWS in the segment of light commercial vehicles (LCV). The algorithm and structure of the developed LDWS for the GAZelle Next vehicle are presented. The description and analysis of algorithms for recognition of road markings are given. The results and comparative analysis of virtual and road tests of the LDWS are presented. Conclusions are given on the operation of the system and the algorithm for recognizing road markings. Introduction The use of ADAS systems in vehicles is mandatory in many countries of the world and is accepted at the state level. One of the most widely used ADAS systems is the Lane Departure Warning System (LDWS). The LDWS occupies a wide niche in the passenger car segment, with the exception of budget models, and also partially in the light commercial vehicle segment. Typically, these systems are offered as optional equipment and are available from many major vehicle manufacturers. The Driver Lane Departure Assist System (LDWS) is a functionality designed to warn the driver that the vehicle is starting to leave the lane (if the turn signal is not turned on in this direction) on motorways, so that the driver is able to take the necessary corrective action. These systems are designed to minimize accidents by eliminating the root causes of collisions: driver errors, distractions and drowsiness. This paper is devoted to the study of algorithms for the operation of such systems. Overview of LDWS There are several systems currently on the market, most of which use a forward-facing video camera mounted behind the windshield. In rare cases, systems use infrared sensors or laser scanning technologies. Modern systems use different types of warnings: visual, audible or tactile, or its combinations. The operation of the LDWS based on a video camera is carried out by assessing the current position and direction of the vehicle within the lane, by determining the road marking lines delimiting the lane from the incoming video stream or images of road sections taken by a camera installed on the front windshield of the vehicle. All these systems are based on two successive stages: image processing from the camera located on the windshield of the vehicle in order to find the marking lines; the process of deciding whether to give the driver a lane departure warning. The stage of detecting road markings can also include several sequential steps: pre-filtering of the image to suppress possible noise; detection of the road marking using the methods of technical vision and/or neural networks; post-processing of found lines to cut off false or incorrect responses. The main situations are known that can lead to incorrect operation. Some of them are described in : fuzzy lines of road markings (overlapping lines, abrasion of lines, contamination of lines, lines do not contrast well with the roadway); heavy load of the rear axle of the vehicle; abrupt change of lighting (entrance / exit from the tunnel); presence of several lanes; overlapping of road marking lines by other vehicles; sharp turns; damage or contamination of the windscreen in the immediate vicinity of the sensor. Development of the LDWS A group of researchers from NNSTU n.a. R.E. Alekseev is developing its own LDWS for use in the segment of light commercial vehicles, in particular, on the Gazelle Next vehicle. The approach was based on machine vision algorithms. The choice of this approach was determined by a number of its advantages: Simplicity and transparency of the solution: the algorithms of this approach have been already developed and repeatedly tested. Performance: in general, the performance of algorithmic methods is higher than that of neural networks. This is an important advantage, since it is possible to reduce the cost of the entire system by choosing a less efficient computing unit, which will make the whole system more accessible. Adaptability: the whole solution is a set of sequential blocks. Each of the sequential blocks is dependent on the previous one in terms of input / output data, but the content of an individual block can be changed. For example, an algorithmic block for searching road markings in the future can be replaced 3 by a block that uses neural networks. Then, to preserve the operability of the entire system as a whole, it will be sufficient that its output is the same as that of the algorithmic one. Schematically, the main cycle of the system can be represented as follows: The above work cycle consists of the following key methods: Canny operator for borders detection. Applying this operation to a halftone image makes possible to select borders that correspond to the differences in colors (Fig. 2). In this case the markings have a color different from the asphalt, i.e. has a distinct color difference. Dilation (expansion) of the found borders. The borders found at the previous step go through the dilation procedure ( Fig. 3). This is a preparatory step for subsequent steps. The essence of this step is to simply expand the boundaries found in the image. Extraction of target colors in the image As mentioned earlier, the selection of borders using the Canny operator finds all the differences (gradients) of colors, however, they can refer not only to road markings. They can also be found on curbs along the road, or on shadows from objects on the road. In order to cut off unnecessary borders, an additional operation is performed to select the desired (target) colors in the image (white and yellow). Color extraction is performed using threshold cuts of image pixel values (Fig. 4). Before applying the clipping threshold, there is a need to apply the color distribution histogram equalization method, which improves the contrast of the image. Bitwise intersection of binary images Canny operator, unfortunately, can distinguish not only the road marking lines, but also side edges. The selection of target colors in the image using threshold values is often noisy because thresholds have to be lowered in order for them to work in different conditions. Therefore, to compensate for the disadvantages of these two approaches, their bitwise intersection should be performed. The input of this operation is the image from paragraph 2 (dilatation) and the image from paragraph 3 (selection of target colors). The resulting image (Fig. 5) is obtained by superimposing the input images on top of each other and includes only those pixels in which both images had a value other than zero. for finding straight lines The binary image obtained in the previous paragraph is sent to the input of the Hough transformation. It makes possible to select the parameters of straight lines that could be on the prepared binary image (colored lines in Fig. 6). Initial filtering of lines by slope After the parameters of possible marking lines have been found, they are initially filtered by the slope. This stage is needed to immediately weed out horizontal and vertical lines, which obviously cannot be the road markings. Along the way, the lines are divided into left and right straight lines by the angle of inclination (Fig. 7). Combining close lines into groups (clusters) The filtered lines must be clustered (Fig. 8) since several parameters of the straight lines can be matched to the same marking line. Clustering is needed to average all these parameters and get one line. The DBSCAN algorithm was chosen as the clustering method. Averaging the parameters of straight lines over clusters After clustering has been done, the straight lines in these clusters are averaged (Fig. 9) so that for each marking line there is only one straight line. Figure 9. Averaging the parameters of straight lines over clusters. At this stage, the lines are converted from the original image to the bird's eye view format (Fig. 10). Translating lines into bird's eye view format This makes them more separable from each other and allows meaningful physical restrictions to be imposed on them (example: the distance between two adjacent marking lines cannot be less than one meter). 3.10. Multi-object particle filter After the lines have been converted to bird's eye view, they are sent for processing to a multi-object particle filter. This makes it possible to compensate for the noise that may be present when selecting the parameters of the straight lines and to decrease the influence of outliers that occur due to various external conditions. In addition, this process for some time makes possible to restore lines that are no longer detected (Fig. 11). Decision making algorithm After the road markings have been detected and filtered, the relative position of the vehicle within the lane is calculated. Further, depending on the fulfillment of the conditions, the system will decide whether a warning signal should be given (Fig. 12). Tests The system was tested in accordance with two main normative documents for the LDWS: UNECE Regulations 130 ; Standard ISO 17361. All prepared and performed tests were directed to check the following points: Operation of the logical component of the system (switching on, activating, changing modes, etc.); Ability of the system to recognize road markings; Ability of the system to position the vehicle inside the lane; Ability of the system to issue a warning signal at the right time. Testing was carried out by two stages: Tests of software part of the system in the virtual environment of the Carla simulator ; Tests of the assembled prototype at a test site with real road markings. One of the important advantages of testing the system with a simulator is the ability to assess the performance of the system not only qualitatively, but also quantitatively. For example, to compare the distance to the marking lines, detected by LDWS, with the one that the simulator provides. This makes possible to quantify the positioning accuracy of the system in the lane. Below there is a demonstration of this assessment (Figure 13). with the one that the simulator provides. Testing the system with a simulator made it possible to detect a number of errors on the development stage and before assembling a real prototype. After the tests with the simulator, a real prototype was tested on a specially equipped section of the test site. As an example, here is a comparative test of the system in real and simulated conditions: unintentional departure from the lane. Test conditions are: We will start with a computer simulation of the test using the Carla simulator. In this example (Fig. 14) the vehicle leaves the traffic lane to the right side. Here the graph "a" shows the distance from the right wheel of the vehicle to the right line of road marking. The graph "b" reflects the fact that the vehicle has crossed the Warning Zone. It should be noted that the graph values correspond to the conditions described above. The graph "c" shows the lateral speed of the vehicle (lane departure speed). Positive speed values mean that the vehicle is moving to the right, negative -to the left. The graph "d" reflects the fact that there is a warning signal from the system. The signal is given only when the vehicle is in the Warning Zone, the lateral speed of the above-described threshold, as well as the direction of the lateral speed corresponds to the exit side. A similar test has been carried out on a real prototype at a test site (Fig. 15). The only difference is that here the departure from the lane was made to the left. Otherwise, the test conditions are fully consistent with the conditions of computer simulation. The system also gives a warning signal only when all the conditions described above are met. Below there is a demonstration of the system operation in areas with different types of road markings (Fig. 16 -17). The tests also involved simulating inadvertent lane departure without the corresponding turn signal. Below there are the results of these tests (Fig. 18 -19). From the point of view of the video camera, the shape, color, inclination and location of these structural elements fully correspond to the parameters of the solid white marking line. Also, during testing of a real prototype, the performance of the system was tested. The data was collected during the LDWS start (on the Nvidia Xavier computing unit), and the result showed an average performance of 26 fps. The results of the speed of the main work cycle are shown below in Table 2. |
/* Branch Monitor
* Introspection Client
* <NAME>, 2017
*/
#include "config.h"
#include "addresses.h"
/* Error messages */
static const char *enum_string[]={
"Everything OK",
"-bin not found",
"Other"
};
/* Error codes */
enum error_codes
{
FOUND_NO_ERROR, /* No error */
NO_BINARY, /* missing -bin */
UNDEF_VALUE /* could not convert string to address */
};
/* parser prototype */
/* TODO: check if getopt (or other) is a better option */
int parse(pimgs binary,pimgs libs,int argc,char *argv[],int *lib_count,int *pid); |
import argparse
import asyncio
import traceback
from typing import Dict, List, Optional, Set, Tuple
import websockets
from jsonrpcclient.clients.http_client import HTTPClient
from jsonrpcclient.clients.websockets_client import WebSocketsClient
SUCCEED_STATUS = 1
FAILED_STATUS = 0
async def call_async(endpoint: str, **kwargs) -> Dict:
"""Use this function to communicate with all Chainalytic services
Default service endpoints:
Upstream: localhost:5500
Aggregator: localhost:5510
Warehouse: localhost:5520
Provider: localhost:5530
Returns:
dict: {'status': bool, 'data': Any}
"""
try:
async with websockets.connect(f"ws://{endpoint}") as ws:
r = await WebSocketsClient(ws).request("_call", **kwargs)
return {'status': SUCCEED_STATUS, 'data': r.data.result}
except Exception as e:
return {'status': FAILED_STATUS, 'data': f'{str(e)}\n{traceback.format_exc()}'}
def call(endpoint: str, **kwargs) -> Dict:
"""Use this function to communicate with all Chainalytic services
Synchronous version of `call_async()`
Default service endpoints:
Upstream: localhost:5500
Aggregator: localhost:5510
Warehouse: localhost:5520
Provider: localhost:5530
Returns:
dict: {'status': bool, 'data': Any}
"""
return asyncio.get_event_loop().run_until_complete(call_async(endpoint, **kwargs))
def call_aiohttp(endpoint: str, **kwargs) -> Dict:
try:
client = HTTPClient(f'http://{endpoint}')
r = client.request("_call", **kwargs)
return {'status': SUCCEED_STATUS, 'data': r.data.result}
except Exception as e:
return {'status': FAILED_STATUS, 'data': f'{str(e)}\n{traceback.format_exc()}'}
|
class TestNormalMixed:
"""
Mixed function and class test modules, normal display mode.
"""
# TODO: currently undefined; spec never even really worked for this
pass |
/* (Intentionally not javadoc'd)
* Implements the method <code>IProgressMonitor.subTask</code>.
*/
public void subTask(String name) {
if ((style & SUPPRESS_SUBTASK_LABEL) != 0) {
return;
}
hasSubTask = true;
String label = name;
if ((style & PREPEND_MAIN_LABEL_TO_SUBTASK) != 0 && mainTaskLabel != null && mainTaskLabel.length() > 0) {
label = mainTaskLabel + ' ' + label;
}
super.subTask(label);
} |
<gh_stars>0
/*
*
* Copyright 2019 Asylo 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.
*
*/
#ifndef ASYLO_CRYPTO_CERTIFICATE_UTIL_H_
#define ASYLO_CRYPTO_CERTIFICATE_UTIL_H_
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/types/span.h"
#include "asylo/crypto/certificate.pb.h"
#include "asylo/crypto/certificate_interface.h"
#include "asylo/util/status.h"
#include "asylo/util/statusor.h"
namespace asylo {
// A map from a CertificateFormat to the factory function to use when creating
// CertificateInterface objects.
using CertificateFactoryMap = absl::flat_hash_map<
Certificate::CertificateFormat,
std::function<StatusOr<std::unique_ptr<CertificateInterface>>(
Certificate)>>;
using CertificateInterfaceVector =
std::vector<std::unique_ptr<CertificateInterface>>;
using CertificateInterfaceSpan =
absl::Span<const std::unique_ptr<CertificateInterface>>;
// Validates a CertificateSigningRequest message. Returns an OK status if and
// only if the message is valid.
//
// This function does NOT verify the contained CSR. It only checks that |csr|'s
// |format| and |data| fields are set and its |format| is not UNKNOWN.
Status ValidateCertificateSigningRequest(const CertificateSigningRequest &csr);
// Validates a Certificate message. Returns an OK status if and only if the
// message is valid.
//
// This function does NOT verify the contained certificate. It only checks that
// |certificate|'s |format| and |data| fields are set and its |format| is not
// UNKNOWN.
Status ValidateCertificate(const Certificate &certificate);
// Validates a CertificateChain message. Returns an OK status if and only if the
// message is valid.
//
// This function does NOT verify the contained certificate chain. It only checks
// that each certificate in |certificate_chain| is valid according to
// ValidateCertificate().
Status ValidateCertificateChain(const CertificateChain &certificate_chain);
// Validates a CertificateRevocationList message. Returns an OK status if and
// only if the message is valid.
//
// This function does NOT verify the contained CRL. It only checks that |crl|'s
// |format| and |data| fields are set and its |format| is not UNKNOWN.
Status ValidateCertificateRevocationList(const CertificateRevocationList &crl);
// Parses |chain| and returns a CertificateInterfaceVector. Uses |factory_map|
// to determine which CertificateInterface factory to use for each format.
// Returns a non-OK Status if there were errors while parsing or if any format
// was unknown.
StatusOr<CertificateInterfaceVector> CreateCertificateChain(
const CertificateFactoryMap &factory_map, const CertificateChain &chain);
// Checks if |certificate_chain| is a valid chain of certificates. The last
// certificate must be self-signed. Checks signatures and, depending on whether
// they are applicable for the format, checks the additional constraints set in
// |verification_config|. Returns a non-OK Status if the certificate chain is
// invalid, or if there were errors while verifying.
Status VerifyCertificateChain(CertificateInterfaceSpan certificate_chain,
const VerificationConfig &verification_config);
// Parses PEM-encoded certificate |pem_cert| into Certificate protobuf.
// Returns a non-OK Status if |pem_cert| is not X.509 PEM encoded.
StatusOr<Certificate> GetCertificateFromPem(absl::string_view pem_cert);
// Parses PEM-encoded certificate chain |pem_cert_chain| into CertificateChain
// protobuf. |pem_cert_chain| should be a series of X509 PEM-encoded
// certificates starting with "-----BEGIN CERTIFICATE-----" and ending with
// "-----END CERTIFICATE-----". Returns a non-OK Status if |pem_cert_chain|
// does not contain at least one pair of "-----BEGIN CERTIFICATE-----" to
// "-----END CERTIFICATE-----" or if any of the PEM certificates cannot be
// parsed as a PEM string.
StatusOr<CertificateChain> GetCertificateChainFromPem(
absl::string_view pem_cert_chain);
// Parses PEM-encoded Certificate Revocation List (CRL) |pem_crl| into
// CertificateRevocationList protobuf. Returns a non-OK Status if
// |pem_crl| is not X.509 PEM encoded.
StatusOr<CertificateRevocationList> GetCrlFromPem(absl::string_view pem_crl);
} // namespace asylo
#endif // ASYLO_CRYPTO_CERTIFICATE_UTIL_H_
|
package com.andreistraut.gaps.controller.dispatchers;
import com.andreistraut.gaps.controller.Controller;
import com.andreistraut.gaps.controller.MessageRequest;
import com.andreistraut.gaps.controller.MessageType;
import com.andreistraut.gaps.datamodel.graph.DirectedWeightedGraph;
import com.andreistraut.gaps.datamodel.graph.DirectedWeightedGraphPath;
import com.andreistraut.gaps.datamodel.mock.MessageRequestMock;
import com.andreistraut.gaps.datamodel.mock.SessionMock;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.Session;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class EvolveMessageDispatcherTest {
private Controller controller;
private Session session;
private MessageRequestMock messageRequestMock;
private GetGraphMessageDispatcher graphDispatcher;
private ComputePathMessageDispatcher pathDispatcher;
private DirectedWeightedGraph graph;
private ArrayList<DirectedWeightedGraphPath> paths;
public EvolveMessageDispatcherTest() {
}
@BeforeClass
public static void setUpClass() {
Logger.getLogger(EvolveMessageDispatcherTest.class.getName()).log(Level.INFO,
"{0} TEST: EvolveMessageDispatcher",
EvolveMessageDispatcherTest.class.toString());
}
@Before
public void setUp() throws Exception {
this.controller = new Controller();
this.session = new SessionMock().getSession();
this.messageRequestMock = new MessageRequestMock();
this.graphDispatcher = new GetGraphMessageDispatcher(this.controller, this.session, MessageType.GETGRAPH);
this.graphDispatcher.setSendUpdates(false);
MessageRequest getGraphRequest = this.messageRequestMock.getGetGraphRequest();
this.graphDispatcher.setRequest(getGraphRequest);
this.graphDispatcher.setParameters(new ArrayList<>());
this.graphDispatcher.process();
this.graph = graphDispatcher.getGraph();
this.pathDispatcher = new ComputePathMessageDispatcher(this.controller, this.session, MessageType.COMPUTEPATHS);
this.pathDispatcher.setSendUpdates(false);
MessageRequest pathRequest = this.messageRequestMock.getComputePathsRequest();
this.pathDispatcher.setRequest(pathRequest);
ArrayList<Object> parameters = new ArrayList<>();
parameters.add(this.graph);
this.pathDispatcher.setParameters(parameters);
this.pathDispatcher.process();
this.paths = pathDispatcher.getPaths();
}
@Test
public void testSetRequestValid() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
Assert.assertTrue(evolveDispatcher.request.equals(evolveRequest));
}
@Test
public void testSetRequestInvalidMissingNumberOfEvolutions() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveRequest.getData().remove("numberOfEvolutions");
try {
evolveDispatcher.setRequest(evolveRequest);
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("Genetic request malformed, missing parameters"));
}
}
@Test
public void testSetRequestInvalidMissingStopConditionPercent() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveRequest.getData().remove("stopConditionPercent");
try {
evolveDispatcher.setRequest(evolveRequest);
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("Genetic request malformed, missing parameters"));
}
}
@Test
public void testSetRequestInvalidMissingParameters() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveRequest.getData().remove("numberOfEvolutions");
evolveRequest.getData().remove("stopConditionPercent");
try {
evolveDispatcher.setRequest(evolveRequest);
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("Genetic request malformed, missing parameters"));
}
}
@Test
public void testSetRequestInvalidDifferentRequest() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest getGraphRequest = this.messageRequestMock.getGetGraphRequest();
try {
evolveDispatcher.setRequest(getGraphRequest);
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("Genetic request malformed, missing parameters"));
}
}
@Test
public void testSetRequestInvalidNullRequest() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = null;
try {
evolveDispatcher.setRequest(evolveRequest);
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("Request invalid, missing data"));
}
}
@Test
public void testSetParametersValid() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
ArrayList<Object> parameters = new ArrayList<>();
parameters.add(this.graph);
parameters.add(this.paths);
evolveDispatcher.setParameters(parameters);
Assert.assertTrue(((DirectedWeightedGraph) evolveDispatcher.parameters.get(0))
.equals(this.graph));
Assert.assertTrue(((ArrayList) evolveDispatcher.parameters.get(1))
.equals(this.paths));
}
@Test
public void testSetParametersInvalidGraphDifferentObject() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
ArrayList<Object> parameters = new ArrayList<>();
parameters.add(new Object());
parameters.add(this.paths);
try {
evolveDispatcher.setParameters(parameters);
} catch(Exception e) {
Assert.assertTrue(e.getMessage().contains("Could not find computed graph. Cannot continue"));
}
}
@Test
public void testSetParametersInvalidGraphNull() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
ArrayList<Object> parameters = new ArrayList<>();
parameters.add(null);
parameters.add(this.paths);
try {
evolveDispatcher.setParameters(parameters);
} catch(Exception e) {
Assert.assertTrue(e.getMessage().contains("Could not find computed graph. Cannot continue"));
}
}
@Test
public void testSetParametersInvalidPathsDifferentObject() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
ArrayList<Object> parameters = new ArrayList<>();
parameters.add(this.graph);
parameters.add(new Object());
try {
evolveDispatcher.setParameters(parameters);
} catch(Exception e) {
Assert.assertTrue(e.getMessage().contains("Could not find computed paths. Cannot continue"));
}
}
@Test
public void testSetParametersInvalidPathsEmpty() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
ArrayList<Object> parameters = new ArrayList<>();
parameters.add(this.graph);
parameters.add(new ArrayList<Object>());
try {
evolveDispatcher.setParameters(parameters);
} catch(Exception e) {
Assert.assertTrue(e.getMessage().contains("Could not find computed paths. Cannot continue"));
}
}
@Test
public void testSetParametersInvalidEmpty() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
ArrayList<Object> parameters = new ArrayList<>();
try {
evolveDispatcher.setParameters(parameters);
} catch(Exception e) {
Assert.assertTrue(e.getMessage().contains("Parameters cannot be empty"));
}
}
@Test
public void testSetParametersInvalidNull() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
ArrayList<Object> parameters = null;
try {
evolveDispatcher.setParameters(parameters);
} catch(Exception e) {
Assert.assertTrue(e.getMessage().contains("Parameters cannot be empty"));
}
}
@Test
public void testSetParametersInvalidPathsNull() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
ArrayList<Object> parameters = new ArrayList<>();
parameters.add(this.graph);
parameters.add(null);
try {
evolveDispatcher.setParameters(parameters);
} catch(Exception e) {
Assert.assertTrue(e.getMessage().contains("Could not find computed paths. Cannot continue"));
}
}
@Test
public void testProcess() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
MessageRequest evolveRequest = this.messageRequestMock.getEvolveRequest();
evolveDispatcher.setRequest(evolveRequest);
ArrayList<Object> parameters = new ArrayList<>();
parameters.add(this.graph);
parameters.add(this.paths);
evolveDispatcher.setParameters(parameters);
boolean evolveResult = evolveDispatcher.process();
Assert.assertTrue(evolveResult);
}
@Test
public void testProcessInvalidNoRequestSet() throws Exception {
EvolveMessageDispatcher evolveDispatcher = new EvolveMessageDispatcher(
controller, session, MessageType.EVOLVE);
evolveDispatcher.setSendUpdates(false);
try {
boolean compareResult = evolveDispatcher.process();
//This MUST throw exception, if we get here, it's an error
Assert.assertTrue(false);
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("Request invalid, missing data"));
}
}
}
|
Distributed Frequency Estimation Over Sensor Network Frequency estimation is a common problem in a variety of applications. In recent years, adaptive notch filtering methods have been widely adopted for solving frequency estimation problems. For frequency estimation performed by a single node, the sampling time may not be long enough, the sampling rate may not be high enough, and the noise effect may be serious. In such situations, most existing algorithms for frequency estimation can not produce accurate enough results. Here, we propose using wireless sensor networks for sampling data distributedly, and using distributed notch filtering method for dealing with this problem. In particular, we propose two distributed algorithms over sensor network, a least mean square-based distributed notch filtering (dNF) algorithm and a total least square-based dNF algorithm. The communication cost of the new proposed algorithms is low, as each node exchanges only with its neighbors the estimates other than the original data. The proposed algorithms are applied to both synthetic and real examples. Simulation results demonstrate the effectiveness of the new proposed algorithms. |
Brinzolamide is a carbonic anhydrase inhibitor used to lower intraocular pressure in patients with ocular hypertension or open-angle glaucoma. Brinzolamide is chemically (R)-(+)-4-ethylamino-2-(3-methoxypropyl)-3,4-dihydro-2H-thieno[3,2-e]-1,2-thiazine-6-sulfonamide-1,1-dioxide and has the empirical formula C12H21N3O5S3. Brinzolamide has a molecular weight of 383.5 and a melting point of about 131° C.
This compound is disclosed in U.S. Pat. No. 5,378,703 (Dean, et al.). The compound is also disclosed in European patent EP 527801. U.S. Pat. No. 6,071,904 discloses processes for preparation of brinzolamide ophthalmic composition.
Brinzolamide in the form of ophthalmic suspension is developed and marketed by Alcon Laboratories Inc. in United States under the brand name Azopt® (brinzolamide ophthalmic suspension 1%). Brinzolamide is indicated for lowering elevated intra-ocular pressure (TOP) in patients with open-angle glaucoma or ocular hypertension (OHT).
Various methods have been disclosed in the prior art for the preparation of brinzolamide ophthalmic suspension. International patent application WO 98/25620 teaches that conventional sterilization methods cannot be employed in the manufacture of suspensions comprising brinzolamide since the compound recrystallizes as large needle-shaped crystals, upon cooling, after autoclaving.
According to WO 98/25620, dry heat sterilization is also not suitable, since it causes melting of the material, whereas sterilization by ethylene oxide and gamma irradiation introduces unacceptable degradation products.
EP0941094 discloses a process for making brinzolamide suspension by autoclaving of concentrated slurry of brinzolamide and tyloxapol; or brinzolamide and Triton X in milling bottle, and ball milling of the hot slurry after autoclaving, and then adding the slurry to the rest of the ingredients. It should be noted here that high temperatures and pressures of autoclave will dissolve brinzolamide. Later, when autoclaving is complete, upon cooling brinzolamide precipitates as large shaped crystals, having particle size of 1000 to 5000 μm. However, inclusion of tyloxapol and/or Triton X in the slurry allows the crystals to break up easily by ball milling. Brinzolamide cannot be administered as these large needle shaped crystals, as they will damage the eyes. Hence, precipitated brinzolamide crystals need to be milled to reduce their particle size.
Thus, the reference discloses autoclaving of the slurry of brinzolamide and surfactant and further ball milling the slurry. However, the drawback associated with this method is that it requires a milling bottle in which the slurry of brinzolamide could initially be autoclaved and then ball milled for further size reduction of needle shaped crystals of brinzolamide that are formed during autoclaving.
Dry heat sterilization causes melting of the material. Sterilization by ethylene oxide introduces unacceptable degradation products and residues, and sterilization by gamma irradiation of micronized material produces degradation products unacceptable for regulatory filing.
In most cases crystallization of active ingredients useful for ophthalmic use like carbonic anhydrase inhibitor, or others actives, occurs during preparation. Sterilization by autoclaving at temperature of 121° C. and 115 lbs of pressure leads to increase in solubility of the actives in the preparation and at that temperature brinzolamide goes into solution. However, upon cooling, brinzolamide precipitates as needle shaped crystals. These needle-shaped crystals are difficult to break and suspend. In different references either tyloxapol is used in solution so that the crystals are easier to break or special equipment such as ball mill and/or jet mill is used to break the large needle-shaped crystals.
The majority of the suspensions disclosed in the references faced the problem of crystallization and agglomeration of active ingredients during preparation as well as during storage. Crystallization or agglomeration of active leads to non-uniformity of dose, difficulty of administration, irritation to eye due to large drug particles and/or any ocular adverse effect due to high drug concentration.
So, there remains a need to formulate a dosage form in which drugs like brinzolamide, having low solubility can be solubilized or the drug is present in an amorphous form, to increase the permeability and bioavailability of the drug. None of the prior art disclosed above teaches about increased solubility of brinzolamide or converting it in an amorphous form.
The inventors of the present invention has formulated a sterile, ophthalmic pharmaceutical formulation, wherein when the active ingredient with low aqueous solubility (such as brinzolamide) in combination with polymers like Soluplus® and a surfactant like polysorbate 80, is either autoclaved or dissolved after heating above 50° C. Upon cooling, the active ingredient brinzolamide does not precipitate and stays in solution or in a partially amorphous form. |
from __future__ import absolute_import
from datetime import date
from datetime import datetime
from dateutil.tz import tzutc
from time import mktime
# A timezone aware datetime object representing the UTC epoch.
EPOCH = datetime.utcfromtimestamp(0).replace(tzinfo=tzutc())
def datetime_to_epoch_time(dt):
"""
If `dt` is a native datetime object (not timezone aware)
then this function assumes that the timezone in UTC.
"""
if not isinstance(dt, datetime) and isinstance(dt, date):
dt = datetime.fromtimestamp(mktime(dt.timetuple()))
# If the datetime is native, assume that the timezone is UTC.
if not dt.tzinfo:
dt = dt.replace(tzinfo=tzutc())
return (dt - EPOCH).total_seconds()
def datetime_to_kronos_time(dt):
"""
Kronos expects timestamps to be the number of 100ns intervals since the epoch.
This function takes a Python `datetime` object and returns the corresponding
Kronos timestamp.
"""
return epoch_time_to_kronos_time(datetime_to_epoch_time(dt))
def kronos_time_to_datetime(time):
return (datetime
.utcfromtimestamp(kronos_time_to_epoch_time(time))
.replace(tzinfo=tzutc()))
def epoch_time_to_kronos_time(time):
return int(time * 1e7)
def kronos_time_to_epoch_time(time):
return int(time * 1e-7)
def kronos_time_now():
return datetime_to_kronos_time(datetime.now(tz=tzutc()))
def timedelta_to_kronos_time(td):
return datetime_to_kronos_time(EPOCH + td)
|
Many automobiles and work machines, particularly, earth working machines, use a continuously variable transmission (CVT) to drive wheels or tracks for propulsion. An engine provides power to the transmission, which controls the speed and torque applied to the wheels or tracks. The transmission can increase output torque by decreasing the output speed. A transmission can also decrease output torque by increasing the output speed.
A manual transmission only provides a discrete number of fixed gear ratios. In contrast, a CVT provides an infinite number of transmission ratios to generate an output at any speed in its operating range. One example of a CVT is a hydrostatic transmission consisting of a variable speed hydraulic pump and a hydraulic motor. An example of such a hydrostatic transmission is disclosed in U.S. Pat. Nos. 6,385,970 and 6,424,902 to Kuras et al. With this type of transmission, the transmission ratio is adjusted by controlling the displacement of the hydraulic pump. Another example of a CVT is an electric motor and inverter as is used in hybrid-electric cars. In a hybrid-electric system, a gasoline engine is mechanically coupled to an electric generator, which provides electric power to an electric motor. An inverter contains the power electronics that control the output speed and torque of the electric motor—thus the transmission ratio is adjusted electronically by the inverter.
One important function of a transmission is to decrease output speed when the engine picks up a heavy load that causes the engine to lug. For example, if an automobile is driving along a road and suddenly starts climbing a very steep hill, the engine may begin lugging due to the increased load and may eventually stall unless the transmission is downshifted to reduce output speed and increase output torque. If the automobile has a manual transmission, the operator will be required to downshift when he or she senses that the engine is lugging.
U.S. Pat. No. 6,385,970 to Kuras et al. discloses an engine underspeed control system that performs the same function of reducing output speed for a CVT. Specifically, the engine underspeed control system senses when the engine begins lugging and adjusts the transmission ratio of a hydraulic CVT to reduce output speed and increase output torque to prevent the engine from stalling.
Another function of an engine underspeed control system is to adjust the transmission ratio so that the engine is running at an optimal speed condition—i.e., within a range of speeds where the engine is operating most efficiently. The engine underspeed control thus both helps to prevent the engine from stalling when increased loads are encountered and also ensures that the engine is running efficiently.
With work machines, the engine can become loaded much quicker than in an automobile. For example, during slot dozing, a heavy load can be picked up suddenly when the blade is dropped to the ground and begins pushing dirt heavily. When such a heavy load is suddenly encountered, it is important for the engine underspeed control to respond quickly to prevent the engine from stalling.
If an operator requests an excessive increase in machine output speed, the CVT control system may lose its ability to respond quickly to a subsequent request to decrease output speed—the subsequent request to decrease output speed could come from the engine underspeed control or from the operator. More generally, whenever the requested motor speed becomes much greater or lesser than the actual motor speed, the CVT control system may lose responsiveness. This can also cause the engine underspeed control to lose its ability to respond quickly when a heavy load is encountered to prevent the engine from stalling. Furthermore, a request for an excessive increase or decrease in motor speed could cause physical damage to the motor and/or transmission. Thus, what is needed is a system and method for controlling a CVT that maintains responsiveness, prevents damage to the motor and transmission, allows the engine underspeed control to respond rapidly, and allows the transmission ratio to be adjusted smoothly (i.e., without jerking) to keep the engine running at an optimal speed condition. The disclosed system may satisfy one or more of these existing needs. |
<filename>src/app/services/soumission/soumission.service.ts
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from '@angular/common/http';
import {
baseUrl,listsoumission,getsoumission,deletesoumission
} from '../../../environments/Config/AppConfig';
import { AddContact } from 'src/app/models/contact/Addcontact';
import { Contact } from 'src/app/models/contact/contact';
import { Addformation } from 'src/app/models/formation/addformation';
import { Formation } from 'src/app/models/formation/formation';
import {AuthService} from '../../services/auth/auth.service';
import { Soumission } from 'src/app/models/Soumission/Soumission';
@Injectable({
providedIn: 'root'
})
export class SoumissionService {
constructor(private http: HttpClient , private auth :AuthService) { }
getSoumission(id:number) {
const headers = new HttpHeaders({ 'Authorization': 'Bearer ' + this.auth.token });
const url = baseUrl.url + getsoumission + "/" +id;
return this.http.get(url, {headers : headers});
}
listSoumission() {
const headers = new HttpHeaders({ 'Authorization': 'Bearer ' + this.auth.token });
const url = baseUrl.url + listsoumission;
return this.http.get(url , {headers : headers});
}
delete(id:number) {
const headers = new HttpHeaders({ 'Authorization': 'Bearer ' + this.auth.token });
const url = baseUrl.url + deletesoumission +"/"+id ;
return this.http.delete(url, {headers : headers});
}
}
|
Well-known are internal combustion engines which are provided with a three way catalyzer in their exhaust systems for reducing undesirable components, such as hydrocarbons (HC), carbon monoxide (CO) and nitrogen oxides (NO.sub.x), contained in exhaust gas. The above-mentioned three way catalyzer achieve their highest converting efficiency when the secondary air fuel ratio is suitably controlled so that it is maintained at the stoichiometric air fuel ratio. (The term "secondary air fuel ratio" as used herein is defined as the total amount of air, including secondary air, to the amount of the fuel fed into the engine.) Accordingly, many types of secondary air control devices have been proposed for maintaining the secondary air fuel ratio at the stoichiometric air fuel ratio. However, these proposed devices are intended to control the secondary air fuel ratio so that it coincides with the stoichiometric air fuel ratio at all times and are very complicated. Such complicated devices are difficult to adjust and maintain, and may be easily damaged. In addition, at least one part of such devices is always exposed to a high temperature caused by the exhaust gas and may also be thermally damaged thereby.
To eliminate the above-mentioned defects, the inventor of the present invention has conducted tests and confirmed that the alternate oscillation of the secondary air fuel ratio between the lean side and the rich side of the stoichiometric air fuel ratio can generate a higher converting efficiency of the three way catalyzer for reducing undesirable components, such as HC, CO and NO.sub.x, than maintaining the secondary air fuel ratio at the stoichiometric air fuel ratio. |
<gh_stars>1-10
import torch
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from sklearn.metrics import recall_score
import numpy as np
def torch_to_numpy(y):
if torch.cuda.is_available():
return y.detach().cpu().numpy()
return y.detach().numpy()
def cont_to_binary(y):
return [1 if x >= 0.5 else 0 for x in y]
def recall(y_hat, y):
y = torch_to_numpy(y)
y_hat = cont_to_binary(torch_to_numpy(y_hat))
return recall_score(y, y_hat)
def f1(y_hat, y):
y = torch_to_numpy(y)
y_hat = cont_to_binary(torch_to_numpy(y_hat))
return f1_score(y, y_hat)
def accuracy(y_hat, y):
final_y_hat = []
if torch.cuda.is_available():
y_hat = y_hat.detach().cpu().numpy()
y = y.detach().cpu().numpy()
else:
y_hat = y_hat.detach().numpy()
y = y.detach().numpy()
final_y_hat += [1 if x > 0.5 else 0 for x in y_hat]
return (sum(1 for a, b in zip(final_y_hat, y) if a == b) / float(len(final_y_hat)))*100
def cm(y_hat, y):
final_y_hat = []
final_y = []
if torch.cuda.is_available():
y_hat = y_hat.detach().cpu().numpy()
y = y.detach().cpu().numpy()
else:
y_hat = y_hat.detach().numpy()
y = y.detach().numpy()
final_y_hat += [1 if x > 0.5 else 0 for x in y_hat]
final_y += [1 if x > 0.5 else 0 for x in y]
tn, fp, fn, tp = confusion_matrix(final_y, final_y_hat).ravel()
# False Positive, False, negative, True positive, true negative
return [tp, tn, fp, fn]
def average_array(data):
if data == []: return 0
return sum(data)/len(data)
def average_arrays(data):
return np.average(data, axis=0) |
Optical Slip Rings for Home Security High-Definition Cameras A new optical transmission slip ring which has a light pipe at the center of rotation in order to provide a stable 1.25 Gbps high-speed transmission line for high-definition video. This design, using a conventional slip ring, has made it possible to realize the development of a 360-degree endless panning home security camera that supports the transmission of high-definition video with high frame rate. |
package varOp
import "fmt"
func Logic() {
a := true
b := false
c := true
fmt.Printf("a=%t\n", a)
fmt.Printf("a=%t\n", b)
fmt.Printf("a=%t\n", c)
fmt.Printf("a&&b:%t\n", a && b)
fmt.Printf("a&&c:%t\n", a && c)
fmt.Printf("a||b:%t\n", a || b)
fmt.Printf("!a:%t\n", !a)
}
|
Adding throw pillows helps to visually connect mismatched furniture pieces.
The living room is an area where mismatched furniture may be the most obvious since most guests at least see this room. Visually connect mismatched chairs, sofas and loveseats with throw pillows, including the original pillows that belong with these seats. For example, if you have a beige couch and a blue couch, mix their pillows so some of each color are on both sofas. For several pieces that don't match, use patterned pillows featuring colors that will look good with all the seating, such as a blue, red and tan pillow. A throw blanket over the back of a chair or couch also adds splashes of colors around the room. Repeat colors a few times throughout your living room; for instance, place a framed photo of a green apple on an end table or wall to match an apple-green chaise across the room.
In your kitchen or dining area, don't feel as if you have to match your chair with your table; in fact, you don't even to match the chairs with each other. Paint all chair legs and the legs of the dining table the same color, such as red, for a cohesive and surprising look that adds a bit of playfulness to the space. Display other eclectic collectibles in the room, such as vintage food advertisements framed on the wall in mismatched frames, or a collection of vintage lunchboxes in assorted colors atop kitchen cabinets or an open shelving area. Paint wood chairs each a different color for a more quirky, eclectic look. Tie the look together, if you like, by painting a graphic image on each chair back, such as a silhouette of a bird or a fork and spoon.
A bedroom with mismatched furniture may result in dark and light wood furnishings in the same space -- such as two different dressers -- and a bed that matches neither piece. Paint dressers and desks alike or all separate colors for a colorful look; the fresh coat of paint on each will tie them together even if they're different colors. Hardware is another option; replace old drawer knobs and handles on all furniture that has them, using hardware common to each, such as smooth platinum. Repainting all the hardware the same color is another frugal option. Tie together a bed and chair by matching a pillow on the chair with the bedding or a throw pillow on the bed.
Whether you shop for furniture or discover an interesting piece by accident at a thrift store or yard sale, check its structure before purchasing. Even an old, beat-up chair with an upholstered seat can be made into something more modern looking with fresh paint or new fabric. Just about any piece that is structurally sound and has a shape you find visually pleasing can be styled to fit in with your existing decor. Customizing the pieces yourself allows you to have furnishings not found in any shop. Mismatched furniture also goes well with mismatched accent decor, which means that African statue just may look good next to the vintage Chinese checkerboard.
Adams, Kathy. "How to Decorate Your Home With Mismatched Furniture." Home Guides | SF Gate, http://homeguides.sfgate.com/decorate-home-mismatched-furniture-72472.html. Accessed 24 April 2019. |
We’ll admit it, we were sucked in. Sitting there huddled around our TV on the night of April 21, 1986, we had no idea what we would see inside Al Capone’s secret vault. Would there be dead bodies? Piles and piles of cash and gold? At the very least, there must be all kinds of cool 1920’s-era artifacts; we were about to be let in on a super-cool time capsule, and some guy named Geraldo Rivera was to be our tour guide on this fascinating journey.
Yes, before he launched his own Sally Jesse-ish talk show (and got his nose broken during the famous skinhead brawl), our man Geraldo saw an opportunity in the basement of Chicago’s Lexington Hotel, and he jumped at it.
While crews were looking over The Lexington in advance of some renovations in the mid-80s, surveyors tripped on an elaborate tunnel system and a huge hidden vault. Geraldo jumped at the opportunity, and immediately set to work on a 2-hour syndicated show that would culminate with the vault being blasted open to reveal its vast fortunes.
…which brings us back to the night of the April 21st. For two hours we sat there, learning everything we could ever hope to about Capone, Prohibition, Chicago, the 20s, ‘The Untouchables’, tax evasion, The Lexington Hotel, how to blow up concrete wall, hidden vaults, and what should (or could) be inside. Medical examiners were invited to the site, so they could be there to take care of the corpses that would undoubtedly be inside. And IRS agents were there to scoop up all the booty.
And there in the middle of it all was Geraldo… openly giddy at the prospect of what we were all about to see.
Then the moment came, and with a series of booms and a strong yank, the huge, heavy vault door was opened. When the dust settled, well…
Dirt. And a bottle.
No dead bodies, no money. No nothing. Just a huge pile of dirt and one, lowly, empty bottle.
Geraldo later went on to say that the moment didn’t destroy his career, it created it… and the fact that he’s still around today certainly makes you think he had a point, but for us, well… Sorry, but we still can’t look at him (even 25 years later) without thinking how embarrassing that moment was. And how duped we all felt. The show may have held the top spot as the most watched syndicated program for a while there, but it was all for nothing. Zip. Zilch.
So, Geraldo… you might still be around, but guess what? The term ‘Al Capone’s Vault’ (meaning ‘all hype with no payoff’) is, too, pal. And for us Children of the 80s, you and that term will always go together. Just like peanut butter and chocolate.
We ♥ Geraldo and Al Capone’s Vault.
Like this: Like Loading... Related
Posted in Television
Tags: 80s, capone's vault, eighties, geraldo, Television |
At night, the same playgrounds become their place to sleep, curled up in the play structures wrapped in blankets.
Lisa Roberts and her 15-month-old son, Liam, spend their days at the Whitby library or walking around parks and playgrounds.
Roberts, 38 — who is nearly eight months pregnant with a girl — and her son have been homeless since the beginning of May, when she had to leave her basement apartment in Whitby because her landlord’s son was returning from university.
Living off welfare, she has been unable to find a one-bedroom apartment for less than $800 in Durham Region.
Roberts has doctors in Ajax but is having trouble getting to them, and missed her last prenatal care appointment. Liam is healthy for now, she says.
“I was told there is a 12-year waiting list (for affordable housing),” she says. And when a rental apartment is listed online, she says, landlords just don’t want to rent to people with children “because they can be destructive.”
Roberts is one among a growing number of women who are having to wait longer and longer to find homes in Durham Region, says Atiya Siddiquei, manager of the Muslim Welfare Centre, the region’s only shelter that caters specifically to women and children who are homeless but not fleeing abuse (there are separate shelters for that in Oshawa and Ajax).
“Honestly speaking, it’s really getting tougher and tougher every day,” she sighs. The 40-bed shelter is usually filled to capacity.
“Most landlords don’t want to rent to people from shelters. Bad credit is another problem; many people have been evicted in the past. It makes it very hard to find places for these women. It’s a long process (to get into affordable housing). If they are not abused, just homeless, they have to wait years and years, with no other option than rental properties.”
However, she says, even though women are now spending three months or more at the shelter while seeking housing, instead of six to eight weeks, it’s even worse in Toronto.
“We’re really finding women are getting stuck,” agrees Ruth Crammond, director of shelter and clinical services at the YWCA, which runs shelters in Toronto for women who are homeless or are fleeing violence. “Women are staying in Toronto shelters longer.”
The number of women and children entering the mainstream shelter system is also on the rise, according to a study noted in the first ever national report card on homelessness, released this week.
“It’s difficult to say why, but it could be a product of the pressure on low-income families, whose earning power is decreasing … as housing costs are increasing, which squeezes you out of the housing market and leaves you one crisis away from homelessness,” says Tim Richter, president and CEO of the Canadian Alliance to End Homelessness.
The report card called for all levels of government to contribute to building affordable housing. Ontario’s problem with affordable rental housing was recently described in an Ontario Non-Profit Housing Association report as “staggering and worsening.”
Women with children, in particular, want to find housing that is both affordable and in an area where they feel safe, notes Crammond. But after months in a shelter, they often accept substandard housing that can put them at risk of violence or further violence, she says.
“In rare cases we see women returning to their abusers … or entering relationships quickly to secure a place to live.”
Cases of homeless parents and children are investigated and dealt with based on severity, said Caroline Newton, spokesperson for the Ontario Association of Children’s Aid Societies. A child will only be taken away from a homeless parent if there’s “an immediate risk of safety,” Newton said, adding that efforts are always made to get in touch with other family members who may be able to help temporarily take care of the child, or place the parent and child in a proper shelter.
If a child is taken into CAS care, the aim is to eventually reunite that child with his or her family, said Newton. “The protection and the well-being of the child is paramount, but the goal is not to just scoop as many kids as possible,” she said. “The goal is to be as least disruptive as possible.”
Back in Whitby, Roberts is frantically continuing her search for a home, poring over online listings provided by her social worker at the library every day. She takes breaks to collect batteries, which she exchanges for cash to help her feed her son.
She says that after spending one night in a shelter, that just isn’t an option — “it didn’t feel safe for my son. He stayed awake all night shaking,” she says.
Though her father lives in Whitby, living with him isn’t on the table. She says their relationship is strained — documented in passionate poetry and prose Roberts has penned over the years and one day hopes to publish. And she is no longer with the father of Liam and her as-yet-unborn daughter.
“I’m hoping to find something soon, before my baby is born,” she says. She has name picked out for the girl: Ailey. “After that, I don’t know what I’m going to do.” |
#include <bits/stdc++.h>
using namespace std;
#define INT_INF 0x3f3f3f3f
#define LL_INF 0x3f3f3f3f3f3f3f3f
#define D_INF numeric_limits<double>::infinity()
#define MIN(a, b) ((a) = min((a), (b)))
#define MAX(a, b) ((a) = max((a), (b)))
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define f first
#define s second
#define all(a) (a).begin(), (a).end()
#define For(i, a, b) for (auto i = (a); i < (b); i++)
#define FOR(i, b) For(i, 0, b)
#define Rev(i, a, b) for (auto i = (a); i > (b); i--)
#define REV(i, a) Rev(i, a, -1)
#define sz(a) ((int) (a).size())
#define nl '\n'
#define sp ' '
#define uint unsigned int
#define ull unsigned long long
#define ll long long
#define ld long double
#define pii pair<int, int>
#define pll pair<ll, ll>
#define pill pair<int, ll>
#define plli pair<ll, int>
#define pdd pair<double, double>
#define uset unordered_set
#define umap unordered_map
#define pq priority_queue
template<typename T> using minpq = pq<T, vector<T>, greater<T>>;
template<typename T> using maxpq = pq<T, vector<T>, less<T>>;
template<typename T1,typename T2,typename H1=hash<T1>,typename H2=hash<T2>>struct pair_hash{size_t operator()(const pair<T1,T2>&p)const{return 31*H1{}(p.first)+H2{}(p.second);}};
#define _bufferSize 4096
#define _maxNumLength 128
char _inputBuffer[_bufferSize+1],*_inputPtr=_inputBuffer,_outputBuffer[_bufferSize],_c,_sign,*_tempInputBuf=nullptr,_numBuf[_maxNumLength],_tempOutputBuf[_maxNumLength],_fill=' ';
const char*_delimiter=" ";int _cur,_outputPtr=0,_numPtr=0,_precision=6,_width=0,_tempOutputPtr=0,_cnt;ull _precisionBase=1000000;
#define _peekchar() (*_inputPtr?*_inputPtr:(_inputBuffer[fread(_inputPtr=_inputBuffer,1,_bufferSize,stdin)]='\0',*_inputPtr))
#define _getchar() (*_inputPtr?*_inputPtr++:(_inputBuffer[fread(_inputPtr=_inputBuffer,1,_bufferSize,stdin)]='\0',*_inputPtr++))
#define _hasNext() (*_inputPtr||!feof(stdin))
#define _readSignAndNum(x) do{(x)=_getchar();}while((x)<=' ');_sign=(x)=='-';if(_sign)(x)=_getchar();for((x)-='0';(_c=_getchar())>='0';(x)=(x)*10+_c-'0')
#define _readFloatingPoint(x,T) for(T _div=1.0;(_c=_getchar())>='0';(x)+=(_c-'0')/(_div*=10))
#define rc(x) do{do{(x)=_getchar();}while((x)<=' ');}while(0)
#define ri(x) do{_readSignAndNum(x);if(_sign)(x)=-(x);}while(0)
#define rd(x) do{_readSignAndNum(x);if(_c=='.')_readFloatingPoint(x,double);if(_sign)(x)=-(x);}while(0)
#define rld(x) do{_readSignAndNum(x);if(_c=='.')_readFloatingPoint(x,ld);if(_sign)(x)=-(x);}while(0)
#define rcs(x) do{_cur=0;do{_c=_getchar();}while(_c<=' ');do{(x)[_cur++]=_c;}while((_c=_getchar())>' ');(x)[_cur]='\0';}while(0)
#define rs(x) do{if(!_tempInputBuf)assert(0);rcs(_tempInputBuf);(x)=string(_tempInputBuf,_cur);}while(0)
#define rcln(x) do{_cur=0;do{_c=_getchar();}while(_c<=' ');do{(x)[_cur++]=_c;}while((_c=_getchar())>=' ');(x)[_cur]='\0';}while(0)
#define rln(x) do{if(!_tempInputBuf)assert(0);rcln(_tempInputBuf);(x)=string(_tempInputBuf,_cur);}while(0)
#define setLength(x) do{if(_tempInputBuf)delete[](_tempInputBuf);_tempInputBuf=new char[(x)+1];}while(0)
void read(int&x){ri(x);}void read(uint&x){ri(x);}void read(ll&x){ri(x);}void read(ull&x){ri(x);}void read(double&x){rd(x);}void read(ld&x){rld(x);}
void read(char&x){rc(x);}void read(char*x){rcs(x);}void read(string&x){rs(x);}bool hasNext(){while(_hasNext()&&_peekchar()<=' ')_getchar();return _hasNext();}
template<typename T,typename...Ts>void read(T&&x,Ts&&...xs){read(x);read(forward<Ts>(xs)...);}
#define _flush() do{_flushBuf();fflush(stdout);}while(0)
#define _flushBuf() (fwrite(_outputBuffer,1,_outputPtr,stdout),_outputPtr=0)
#define _putchar(x) (_outputBuffer[_outputPtr==_bufferSize?_flushBuf():_outputPtr]=(x),_outputPtr++)
#define _writeTempBuf(x) (_tempOutputBuf[_tempOutputPtr++]=(x))
#define _writeOutput() for(int _i=0;_i<_tempOutputPtr;_putchar(_tempOutputBuf[_i++]));_tempOutputPtr=0
#define _writeNum(x,T,digits) _cnt=0;for(T _y=(x);_y;_y/=10,_cnt++)_numBuf[_numPtr++]='0'+_y%10;for(;_cnt<digits;_cnt++)_numBuf[_numPtr++]='0';_flushNumBuf();
#define _writeFloatingPoint(x,T) ull _I=(ull)(x);ull _F=((x)-_I)*_precisionBase+(T)(0.5);if(_F>=_precisionBase){_I++;_F=0;}_writeNum(_I,ull,1);_writeTempBuf('.');_writeNum(_F,ull,_precision)
#define _checkFinite(x) if(std::isnan(x)){wcs("NaN");}else if(std::isinf(x)){wcs("Inf");}
#define _flushNumBuf() for(;_numPtr;_writeTempBuf(_numBuf[--_numPtr]))
#define _fillBuf(x) for(int _i=0;_i<(x);_i++)_putchar(_fill)
#define _flushTempBuf() int _tempLen=_tempOutputPtr;_fillBuf(_width-_tempLen);_writeOutput();_fillBuf(-_width-_tempLen)
#define wb(x) do{if(x)_writeTempBuf('1');else _writeTempBuf('0');_flushTempBuf();}while(0)
#define wc(x) do{_writeTempBuf(x); _flushTempBuf();}while(0)
#define wi(x) do{if((x)<0){_writeTempBuf('-');_writeNum(-(x),uint,1);}else{_writeNum(x,uint,1);}_flushTempBuf();}while(0)
#define wll(x) do{if((x)<0){_writeTempBuf('-');_writeNum(-(x),ull,1);}else{_writeNum(x,ull,1);}_flushTempBuf();}while(0)
#define wd(x) do{_checkFinite(x)else if((x)<0){_writeTempBuf('-');_writeFloatingPoint(-(x),double);}else{_writeFloatingPoint(x,double);}_flushTempBuf();}while(0)
#define wld(x) do{_checkFinite(x)else if((x)<0){_writeTempBuf('-');_writeFloatingPoint(-(x),ld);}else{_writeFloatingPoint(x,ld);}_flushTempBuf();}while(0)
#define wcs(x) do{int _slen=strlen(x);_fillBuf(_width-_slen);for(const char*_p=(x);*_p;_putchar(*_p++));_fillBuf(-_width-_slen);}while(0)
#define ws(x) do{_fillBuf(_width-(int)(x).length());for(int _i=0;_i<(int)(x).length();_putchar(x[_i++]));_fillBuf(-_width-(int)(x).length());}while(0)
#define setPrecision(x) do{_precision=(x);_precisionBase=1;for(int _i=0;_i<(x);_i++,_precisionBase*=10);}while(0)
#define setDelimiter(x) do{_delimiter=(x);}while(0)
#define setWidth(x) do{_width=(x);}while(0)
#define setFill(x) do{_fill=(x);}while(0)
void write(bool x){wb(x);}void write(int x){wi(x);}void write(uint x){wi(x);}void write(ll x){wll(x);}void write(ull x){wll(x);}void write(double x){wd(x);}void write(ld x){wld(x);}
void write(char x){wc(x);}void write(char*x){wcs(x);}void write(const char*x){wcs(x);}void write(string&x){ws(x);}
template<typename T,typename...Ts>void write(T&&x,Ts&&...xs){write(x);for(const char*_p=_delimiter;*_p;_putchar(*_p++));write(forward<Ts>(xs)...);}
void writeln(){_putchar('\n');}template<typename...Ts>void writeln(Ts&&...xs){write(forward<Ts>(xs)...);_putchar('\n');}
void flush(){_flush();}class IOManager{public:~IOManager(){flush();}};unique_ptr<IOManager>iomanager;
int N;
ll A[2][300005], suf[300005], cur[2], dp[2][2];
int main() {
// freopen("out.txt", "w", stdout);
// freopen("in.txt", "r", stdin);
iomanager.reset(new IOManager());
read(N);
FOR(i, 2) FOR(j, N) read(A[i][j]);
suf[N] = 0;
REV(i, N - 1) suf[i] = suf[i + 1] + A[0][i] + A[1][i];
FOR(i, 2) dp[i][(N - 1) % 2] = cur[i] = A[1 - i][N - 1];
REV(j, N - 2) FOR(i, 2) dp[i][j % 2] = max(cur[i] += suf[j + 1] + A[1 - i][j] * (2 * (N - j) - 1), A[1 - i][j] + dp[1 - i][1 - j % 2] + 2 * suf[j + 1]);
writeln(dp[0][0]);
return 0;
}
|
LENNON Cradock is daring to dream after playing on one of the biggest stages of his career.
The teenager, from Witney, has his sights set on a professional career following an appearance at Alexandra Palace last month.
Oxfordshire county star Cradock lost to Dutch youngster Jurjen van der Velde in the final of the Junior Darts Corporation World Championship.
Played during the PDC World Championship, it proved an opportunity for the 17-year-old, who is studying for A-Levels at Wood Green School, Witney, to get a taste of the big time.
And Cradock is hoping to be a regular at the London venue in the future.
He said: “I obviously want to be professional, I would love that.
“I’ve played the youth development tour already and youth PDC.
Cradock reached the final after progressing through the early stages in Bristol.
He was involved in an entertaining contest with Van der Velde, but was beaten 4-2.
The opening four legs all went with the throw, before the Dutch player threw the only 180 of the contest as he broke the Cradock throw to go 3-2 up.
Van der Velde then wrapped up the sixth leg to secure victory.
Despite the defeat, Cradock, who plays for Democrats in the Cowley Workers ODDA, enjoyed the occasion.
He said: “I didn’t play my best stuff, but I was happy to get to the final.
“I went into it just trying to get out of the group stage – I felt if I could do that it would be an achievement.
“The final was an amazing experience and there’s always pressure regardless of where you play. |
<gh_stars>0
package com.company;
public class BST {
class Node {
int key;
Node left;
Node right;
public Node(int key) {
this.key = key;
}
}
Node root;
public void insert(int key){
root = insert(root, key);
}
public Node insert(Node root, int key){
if(root == null){
root = new Node(key);
return root;
}
if(key<root.key){
root.left = insert(root.left, key);
}
else if (key>root.key){
root.right = insert(root.right, key);
}
return root;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.