text stringlengths 1 1.05M |
|---|
# -*- coding: utf-8 -*-
import unittest
from blo.BloArticle import BloArticle
class TestBloArticle(unittest.TestCase):
def setUp(self):
self.blo_article = BloArticle('./templates')
self.base_file_path_1 = "./test_article_1.md"
self.base_file_path_2 = "./test_article_2.md"
def test_failed_load_from_file(self):
with self.assertRaises(FileNotFoundError):
self.blo_article.load_from_file("")
def test_success_load_from_file(self):
expected_str = '# Test Article\nfirst paragraph \n\nsecond paragraph with semi long length string and the quick brown fox jumps over the lazy dog repeat the quick brown fox jumps over the lazy dog repeat the quick brown fox jumps over the lazy dog.\n\nthird paragraph with bullet list\n- 1st\n - 1st c1\n - 1st c2\n- 2nd\n- 3rd\n - 3rd c1\n - 3rd c2\n- 4th\n\n**Strong text** *Italic text*'
self.assertIsNone(self.blo_article.load_from_file(self.base_file_path_1))
self.assertEqual(expected_str, self.blo_article._raw_text)
def test_convert_to_simple_html_1(self):
expected_html = '<h1>Test Article</h1>\n<p>first paragraph</p>\n<p>second paragraph with semi long length string and the quick brown fox jumps over the lazy dog repeat the quick brown fox jumps over the lazy dog repeat the quick brown fox jumps over the lazy dog.</p>\n<p>third paragraph with bullet list</p>\n<ul>\n<li>1st\n<ul>\n<li>1st c1</li>\n<li>1st c2</li>\n</ul>\n</li>\n<li>2nd</li>\n<li>3rd\n<ul>\n<li>3rd c1</li>\n<li>3rd c2</li>\n</ul>\n</li>\n<li>4th</li>\n</ul>\n<p><strong>Strong text</strong> <em>Italic text</em></p>\n'
self.blo_article.load_from_file(self.base_file_path_1)
self.assertMultiLineEqual(expected_html, self.blo_article._convert_to_html())
def test_convert_to_simple_html_2(self):
expected_html = """<h1>日本語を含んだテストパターンファイル</h1>
<h2>天文と俳句(現代仮名遣い風に編集)</h2>
<h3>寺田寅彦</h3>
<p>俳句季題の分類は普通に <strong>時候</strong> 、''天文'''、 地理 、<code>人事</code>、動物、植物という風になっている。
これらのうちで後の三つは別として、初めの三つの項目中における各季題の分け方は現代の科学知識から見ると、
決して合理的であるとは思われない。</p>
<h2>天文と俳句(原文をそのまま青空文庫より引用)</h2>
<h3>寺田寅彦</h3>
<p><code>俳句季題の分類は普通に時候、天文、地理、人事、動物、植物といふ風になつて居る。此等のうちで後の三つは別として、初めの三つの項目中に於ける各季題の分け方は現代の科學知識から見ると、決して合理的であるとは思はれない。</code></p>
<h2>いくつかの記述要素</h2>
<p>リストを記述する</p>
<ul>
<li>リスト項目1
<ul>
<li>子リスト項目1</li>
<li>子リスト項目2</li>
</ul>
</li>
<li>with english text
<ul>
<li><em>in itarlic</em></li>
<li>日本語の表記と英語( <em>English</em> )の表記を併記した状態でテストを行うためのデータ</li>
</ul>
</li>
</ul>
"""
self.blo_article.load_from_file(self.base_file_path_2)
self.assertMultiLineEqual(expected_html, self.blo_article._convert_to_html())
def test_convert_to_template_html(self):
pass
def test_get_digest_1(self):
expected_html = '<h1>Test Article</h1>\n<p>first paragraph</p>\n<p>second paragraph with semi long length string and the quick brown fox jumps over the lazy dog repeat the quick brown fox jumps over the lazy dog repeat the quick brown fox jumps over the lazy dog.</p>\n<p>third paragraph with bullet list</p>\n<ul>\n<li>1st\n<ul>\n<li>1st c1</li>\n<li>1st c2</li>\n</ul>\n</li>\n<li>2nd</li>\n<li>3rd\n<ul>\n<li>3rd c1</li>\n<li>3rd c2</li>\n</ul>\n</li>\n<li>4th</li>\n</ul>\n<p><strong>Strong text</strong> <em>Italic text</em></p>\n'
self.blo_article.load_from_file(self.base_file_path_1)
self.blo_article.get_html()
from hashlib import sha512
hs = sha512()
hs.update(expected_html.encode('utf-8'))
self.assertEqual(hs.hexdigest(), self.blo_article.get_digest())
def test_get_digest_2(self):
expected_html = """<h1>日本語を含んだテストパターンファイル</h1>
<h2>天文と俳句(現代仮名遣い風に編集)</h2>
<h3>寺田寅彦</h3>
<p>俳句季題の分類は普通に <strong>時候</strong> 、''天文'''、 地理 、<code>人事</code>、動物、植物という風になっている。
これらのうちで後の三つは別として、初めの三つの項目中における各季題の分け方は現代の科学知識から見ると、
決して合理的であるとは思われない。</p>
<h2>天文と俳句(原文をそのまま青空文庫より引用)</h2>
<h3>寺田寅彦</h3>
<p><code>俳句季題の分類は普通に時候、天文、地理、人事、動物、植物といふ風になつて居る。此等のうちで後の三つは別として、初めの三つの項目中に於ける各季題の分け方は現代の科學知識から見ると、決して合理的であるとは思はれない。</code></p>
<h2>いくつかの記述要素</h2>
<p>リストを記述する</p>
<ul>
<li>リスト項目1
<ul>
<li>子リスト項目1</li>
<li>子リスト項目2</li>
</ul>
</li>
<li>with english text
<ul>
<li><em>in itarlic</em></li>
<li>日本語の表記と英語( <em>English</em> )の表記を併記した状態でテストを行うためのデータ</li>
</ul>
</li>
</ul>
"""
self.blo_article.load_from_file(self.base_file_path_2)
self.blo_article.get_html()
from hashlib import sha512
hs = sha512()
hs.update(expected_html.encode('utf-8'))
self.assertEqual(hs.hexdigest(), self.blo_article.get_digest())
def test_get_raw_text_body_2(self):
expected_txt = """日本語を含んだテストパターンファイル\n天文と俳句(現代仮名遣い風に編集)\n寺田寅彦\n俳句季題の分類は普通に 時候 、''天文'''、 地理 、人事、動物、植物という風になっている。\nこれらのうちで後の三つは別として、初めの三つの項目中における各季題の分け方は現代の科学知識から見ると、\n決して合理的であるとは思われない。\n天文と俳句(原文をそのまま青空文庫より引用)\n寺田寅彦\n俳句季題の分類は普通に時候、天文、地理、人事、動物、植物といふ風になつて居る。此等のうちで後の三つは別として、初めの三つの項目中に於ける各季題の分け方は現代の科學知識から見ると、決して合理的であるとは思はれない。\nいくつかの記述要素\nリストを記述する\nリスト項目1\n子リスト項目1\n子リスト項目2\nwith english text\nin itarlic\n日本語の表記と英語( English )の表記を併記した状態でテストを行うためのデータ\n"""
self.blo_article.load_from_file(self.base_file_path_2)
base_txt = self.blo_article._get_raw_text_body()
self.assertEqual(expected_txt, base_txt)
def text_get_wakati_text_body_2(self):
expected_txt = "日本語 を 含ん だ テストパターン ファイル 天文 と 俳句 ( 現代 仮名遣い 風 に 編集 ) 寺田 寅彦 俳句 季題 の 分類 は 普通 に 時候 、 '' 天文 '''、 地理 、 人事 、 動物 、 植物 という 風 に なっ て いる 。 これら の うち で 後 の 三つ は 別 として 、 初め の 三つ の 項目 中 における 各 季題 の 分け 方 は 現代 の 科学 知識 から 見る と 、 決して 合理 的 で ある と は 思わ れ ない 。 天文 と 俳句 ( 原文 を そのまま 青空 文庫 より 引用 ) 寺田 寅彦 俳句 季題 の 分類 は 普通 に 時候 、 天文 、 地理 、 人事 、 動物 、 植物 といふ 風 に なつ て 居る 。 此等 の うち で 後 の 三つ は 別 として 、 初め の 三つ の 項目 中 に 於け る 各 季題 の 分け 方 は 現代 の 科 學 知識 から 見る と 、 決して 合理 的 で ある と は 思は れ ない 。 いくつ か の 記述 要素 リスト を 記述 する リスト 項目 1 子 リスト 項目 1 子 リスト 項目 2 with english text in itarlic 日本語 の 表記 と 英語 ( English ) の 表記 を 併記 し た 状態 で テスト を 行う ため の データ \n"
self.blo_article.load_from_file(self.base_file_path_2)
self.blo_article._get_raw_text_body()
wakati_txt = self.blo_article.get_wakati_txt()
self.assertEqual(expected_txt, wakati_txt)
def test_template(self):
expected_txt = '''<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Test Article</title>
</head>
<body>
<h1>Test Article</h1>
<p>first paragraph</p>
<p>second paragraph with semi long length string and the quick brown fox jumps over the lazy dog repeat the quick brown fox jumps over the lazy dog repeat the quick brown fox jumps over the lazy dog.</p>
<p>third paragraph with bullet list</p>
<ul>
<li>1st
<ul>
<li>1st c1</li>
<li>1st c2</li>
</ul>
</li>
<li>2nd</li>
<li>3rd
<ul>
<li>3rd c1</li>
<li>3rd c2</li>
</ul>
</li>
<li>4th</li>
</ul>
<p><strong>Strong text</strong> <em>Italic text</em></p>
</body>
</html>'''
self.blo_article.load_from_file(self.base_file_path_1)
html_txt = self.blo_article.get_html('test_success.html')
self.assertEqual(expected_txt, html_txt)
|
<reponame>radamstx/ss-ui-test<gh_stars>0
# frozen_string_literal: true
require_relative 'element_requires'
class BaseElement
include WaitCondition
# @param by [Symbol] (:id, :css, :xpath, etc.)
# @param locator [String] locator value
def initialize(by, locator)
@by = by
@locator = locator
end
def text
wait { element.text }
end
def attribute(name)
wait { element.attribute(name) }
end
def id
wait { element.attribute('id') }
end
def value
wait { element.attribute('value') }
end
# rubocop:disable Metrics/MethodLength
def visible?
max_time = Time.now + TIMEOUT
while Time.now < max_time
begin
return DriverManager.driver.find_element(@by, @locator).displayed?
rescue Selenium::WebDriver::Error::InvalidElementStateError,
Selenium::WebDriver::Error::StaleElementReferenceError,
Selenium::WebDriver::Error::UnknownError
sleep(POLL_INTERVAL)
rescue Selenium::WebDriver::Error::NoSuchElementError
return false
end
end
raise Error::WaitExpiredException
end
# rubocop:enable Metrics/MethodLength
# Wait until the element is visible
def wait_until_visible
wait_for_visibility(true) { DriverManager.driver.find_element(@by, @locator).displayed? }
end
# Wait until the element is not visible
def wait_until_not_visible
wait_for_visibility(false) { DriverManager.driver.find_element(@by, @locator).displayed? }
end
# Wait for attribute name to equal attribute value
def wait_for_attribute_to_equal(attribute_name, attribute_value)
wait_until_equality(attribute_value, true) { element.attribute(attribute_name) == attribute_value }
end
# Wait for attribute name to not equal attribute value
def wait_for_attribute_to_not_equal(attribute_name, attribute_value)
wait_until_equality(attribute_value, false) { element.attribute(attribute_name) != attribute_value }
end
# Wait for element to have class
def wait_for_class(wait_for_class)
wait_until_condition(true) { element.attribute('class').include? wait_for_class }
end
# Wait for element to not have class
def wait_for_absence_of_class(wait_for_absence_of_class)
wait_until_condition(false) { element.attribute('class').include? wait_for_absence_of_class }
end
# Does the element have the specified class?
# @return [TrueClass, FalseClass]
def class?(has_class)
attribute('class').include? has_class
end
protected
# Wraps element lookup and returns a Selenium::WebDriver::Element to interact with inside of other
# wait conditions so we're catching things like StaleElementReferenceException
# @return [Selenium::WebDriver::Element]
def element
wait { DriverManager.driver.find_element(@by, @locator) }
end
end
|
<gh_stars>0
package bttv.emote;
import bttv.Data;
import io.reactivex.Single;
import tv.twitch.android.shared.chat.model.EmoteCardModel;
import tv.twitch.android.shared.chat.parser.EmoteCardModelParser;
public class EmoteCardUtil {
public static class BTTVEmoteCardModel extends EmoteCardModel.GlobalEmoteCardModel {
public BTTVEmoteCardModel(String emoteId, String token) {
super(emoteId, token);
}
}
public static Single<EmoteCardModelParser.EmoteCardModelResponse> getEmoteResponseOrNull(String emoteId) {
if (!emoteId.startsWith("BTTV-")) {
return null;
}
String realId = emoteId.split("BTTV-")[1];
Emote emote = Emotes.getEmoteById(realId);
if (emote == null) { // triggers error dialog
return null;
}
EmoteCardModel model = new BTTVEmoteCardModel(emoteId, emote.code);
EmoteCardModelParser.EmoteCardModelResponse resp = new EmoteCardModelParser.EmoteCardModelResponse.Success(
model);
return Single.just(resp);
}
}
|
kratos proto server ./api/kratosdemouser/kratosDemoUser.proto -t ./internal/service |
<gh_stars>10-100
package com.telenav.osv.ui.custom;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.StringDef;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import com.google.common.base.Strings;
import com.telenav.osv.R;
import com.telenav.osv.utils.Utils;
/**
* Visualizing the score for the recording
*/
@SuppressWarnings("SuspiciousNameCombination")
public class ByodPaymentIndicator extends View {
public static final String TAG = "ScoreView";
private static final int FONT_SIZE_SMALL = 12;
private static final int FONT_SIZE_LARGE = 18;
private static final int STATE_HIDDEN = 1;
private static final int STATE_DOT = 3;
private static final int STATE_EXTENDED = 5;
private boolean mDrawTexts = true;
private boolean mActive;
private boolean displayingDrawable;
private Drawable displayedDrawable = null;
private Paint mPaintTextLarge;
private Paint mPaintTextSmall;
private Paint mPaintLarge;
private Paint mPaintLargeOutline;
private Paint mPaintDot;
private Paint mPaintDotOutline;
private int mColorBlue;
private int mColorLightBlue;
private int mColorGray;
private int mColorLightGray;
private int mColorYellow;
private int mColorLightYellow;
private float mOutlineWidth;
private String mValueText = "0";
private int mMultiplier = 0;
private int mCurrentState = STATE_HIDDEN;
private float mWidth;
private float mHeight;
private RectF leftArc;
private RectF rectangle;
private RectF rightArc;
private float oneDip = 0;
private String mMultiplierPrefix = "x";
private String mMultiplierText = "0";
@ScoreSuffix
private String mValueSuffix = ScoreSuffix.POINTS; //points as default
private int mPrefixX;
private int mPrefixY;
private int mMultiplierY;
private int mMultiplierX;
private int mScoreY;
private int mScoreX;
private int mScoreSuffixY;
private int mScoreSuffixX;
private boolean displayBubble;
private String mDefaultValue;
private int currentSize;
public ByodPaymentIndicator(Context context) {
super(context);
initialize();
}
public ByodPaymentIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
public ByodPaymentIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
@SuppressWarnings("unused")
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public ByodPaymentIndicator(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initialize();
}
@Override
protected void onDraw(Canvas canvas) {
mPaintLargeOutline.setStrokeWidth(mOutlineWidth);
mPaintDotOutline.setStrokeWidth(mOutlineWidth);
float left = 0;
float top = 0;
float radius = mHeight / 2;
float centerY = mHeight / 2;
leftArc.set(left, centerY - radius, left + 2 * radius, centerY + radius);
rectangle.set(left + radius, top, mWidth - radius, mHeight);
rightArc.set(mWidth - 2 * radius, centerY - radius, mWidth, centerY + radius);
canvas.drawRect(rectangle, mPaintLarge);
canvas.drawArc(rightArc, 270, 180, false, mPaintLarge);
if (displayBubble || displayingDrawable) {
canvas.drawArc(leftArc, 90, 360, false, mPaintDot);
} else {
canvas.drawArc(leftArc, 90, 180, false, mPaintDot);
}
rightArc.inset(mOutlineWidth / 2, mOutlineWidth / 2);
rectangle.inset(0, mOutlineWidth / 2);
leftArc.inset(mOutlineWidth / 2, mOutlineWidth / 2);
canvas.drawLine(rectangle.left, rectangle.top, rectangle.right, rectangle.top, mPaintLargeOutline);
canvas.drawLine(rectangle.left, rectangle.bottom, rectangle.right, rectangle.bottom, mPaintLargeOutline);
canvas.drawArc(rightArc, 270, 180, false, mPaintLargeOutline);
if (displayBubble || displayingDrawable) {
canvas.drawArc(leftArc, 90, 360, false, mPaintDotOutline);
} else {
canvas.drawArc(leftArc, 90, 180, false, mPaintDotOutline);
}
if (displayingDrawable && displayedDrawable != null) {
displayedDrawable.setBounds(0, 0, (int) mHeight, (int) mHeight);
displayedDrawable.draw(canvas);
}
if (!displayingDrawable && displayBubble) {
canvas.drawText(mMultiplierPrefix, mPrefixX, mPrefixY, mPaintTextSmall);
canvas.drawText(mMultiplierText, mMultiplierX, mMultiplierY, mPaintTextLarge);
}
if (mDrawTexts) {
canvas.drawText(mValueText, mScoreX, mScoreY, mPaintTextLarge);
if (!displayingDrawable) {
canvas.drawText(mValueSuffix, mScoreSuffixX, mScoreSuffixY, mPaintTextSmall);
}
}
super.onDraw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredHeight = (int) getHeightForState(mCurrentState);
int desiredWidth = (int) getWidthForState(mCurrentState);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
mHeight = height;
mWidth = width;
mOutlineWidth = mHeight / 14.666f;
//MUST CALL THIS
setMeasuredDimension(width, height);
invalidate();
}
public void setDefaultValue(@Nullable String defaultValue) {
mDefaultValue = defaultValue;
}
public boolean isActive() {
return mActive;
}
// ===========================================================================================================================
public void showText() {
if (!mActive) {
setDrawableDisplayed(false);
currentSize = 0;
mActive = true;
if (mDefaultValue != null) {
mValueText = mDefaultValue;
}
transitionToState(mCurrentState, STATE_EXTENDED);
requestLayout();
invalidate();
}
}
// ===========================================================================================================================
public void showTextWithInitialValue(@Nullable String payRate) {
if (!mActive) {
setDrawableDisplayed(false);
currentSize = 0;
mActive = true;
if (mDefaultValue != null) {
mValueText = payRate;
}
transitionToState(mCurrentState, STATE_EXTENDED);
requestLayout();
invalidate();
}
}
public void showDrawable(@DrawableRes int drawable) {
showDrawable(getResources().getDrawable(drawable, null), null);
}
public void showDrawable(@DrawableRes int drawable, @Nullable String description) {
showDrawable(getResources().getDrawable(drawable, null), description);
}
public void showDrawable(@NonNull Drawable drawable, @Nullable String description) {
currentSize = 0;
setDrawableDisplayed(true);
displayedDrawable = drawable;
mValueText = Strings.nullToEmpty(description);
mActive = true;
if (Strings.isNullOrEmpty(mValueText)) {
transitionToState(mCurrentState, STATE_DOT);
} else {
transitionToState(mCurrentState, STATE_EXTENDED);
}
requestLayout();
invalidate();
}
public void hide() {
if (mActive) {
mActive = false;
transitionToState(mCurrentState, STATE_HIDDEN);
requestLayout();
invalidate();
}
}
public void updateScore(@Nullable String score) {
//displaying text, not a drawable now
setDrawableDisplayed(false);
mValueText = Strings.nullToEmpty(score);
if (mCurrentState == STATE_EXTENDED) {
int newSize = measureElements();
if (newSize != currentSize) {
requestLayout();
}
currentSize = newSize;
invalidate();
} else {
transitionToState(mCurrentState, STATE_EXTENDED);
}
}
public void setMultiplier(int multiplier) {
setDrawableDisplayed(false);
if (mMultiplier == multiplier || multiplier < 1) {
return;
}
mMultiplier = multiplier;
requestLayout();
invalidate();
}
public void setScoreSuffix(@ScoreSuffix String suffix) {
setDrawableDisplayed(false);
this.mValueSuffix = suffix;
}
public void setDisplayBubble(boolean displayBubble) {
setDrawableDisplayed(false);
this.displayBubble = displayBubble;
}
private void setDrawableDisplayed(boolean displayed) {
if (displayingDrawable != displayed) {
displayingDrawable = displayed;
updateOutlineColors();
}
}
private void initialize() {
mHeight = (int) Utils.dpToPx(getContext(), 48);
mOutlineWidth = mHeight / 14.666f;
rectangle = new RectF();
rightArc = new RectF();
leftArc = new RectF();
mColorBlue = getResources().getColor(R.color.score_background_blue);
mColorLightBlue = getResources().getColor(R.color.score_background_light_blue);
mColorGray = getResources().getColor(R.color.score_background_gray);
mColorLightGray = getResources().getColor(R.color.score_background_light_gray);
mColorYellow = getResources().getColor(R.color.score_background_yellow);
mColorLightYellow = getResources().getColor(R.color.score_background_light_yellow);
mPaintLarge = new Paint();
mPaintLarge.setColor(mColorBlue);
mPaintLarge.setStrokeWidth(0);
mPaintLarge.setStyle(Paint.Style.FILL);
mPaintLargeOutline = new Paint();
mPaintLargeOutline.setColor(mColorLightBlue);
mOutlineWidth = 15;
mPaintLargeOutline.setStrokeWidth(mOutlineWidth);
mPaintLargeOutline.setStyle(Paint.Style.STROKE);
mPaintDot = new Paint();
mPaintDot.setColor(mColorBlue);
mPaintDot.setStrokeWidth(0);
mPaintDot.setStyle(Paint.Style.FILL);
mPaintDotOutline = new Paint();
mPaintDotOutline.setColor(mColorLightBlue);
mPaintDotOutline.setStrokeWidth(mOutlineWidth);
mPaintDotOutline.setStyle(Paint.Style.STROKE);
mPaintTextLarge = new Paint();
mPaintTextLarge.setColor(Color.WHITE);
mPaintTextLarge.setTextAlign(Paint.Align.CENTER);
mPaintTextLarge.setAntiAlias(true);
mPaintTextLarge.setTypeface(Typeface.SANS_SERIF);
mPaintTextLarge.setTextSize(Utils.dpToPx(getContext(), FONT_SIZE_LARGE));
mPaintTextSmall = new Paint();
mPaintTextSmall.setColor(Color.WHITE);
mPaintTextSmall.setTextAlign(Paint.Align.CENTER);
mPaintTextLarge.setAntiAlias(true);
mPaintTextLarge.setTypeface(Typeface.SANS_SERIF);
mPaintTextSmall.setTextSize(Utils.dpToPx(getContext(), FONT_SIZE_SMALL));
oneDip = Utils.dpToPx(getContext(), 1);
}
private float getWidthForState(int state) {
switch (state) {
case STATE_DOT:
// Log.d(TAG, "getWidthForState: DOT");
return (int) Utils.dpToPx(getContext(), 48);
case STATE_EXTENDED:
// Log.d(TAG, "getWidthForState: EXTENDED");
return measureElements();
default:
case STATE_HIDDEN:
// Log.d(TAG, "getWidthForState: HIDDEN");
return 0;
}
}
private float getHeightForState(int state) {
switch (state) {
case STATE_DOT:
case STATE_EXTENDED:
return (int) Utils.dpToPx(getContext(), 48);
default:
case STATE_HIDDEN:
return 0;
}
}
private void transitionToState(final int current, final int next) {
final Runnable changeState = () -> mCurrentState = next;
switch (current << next) {
case STATE_HIDDEN << STATE_DOT:
appearAnimation(changeState);
break;
case STATE_EXTENDED << STATE_DOT:
retractAnimation(changeState);
break;
case STATE_HIDDEN << STATE_EXTENDED:
appearAnimation(() -> extendAnimation(changeState));
break;
case STATE_DOT << STATE_HIDDEN:
hideAnimation(changeState);
break;
case STATE_EXTENDED << STATE_HIDDEN:
final Runnable collapsedToHiddenRunnable = () -> {
mValueText = "";
displayedDrawable = null;
changeState.run();
};
//first switch from extended to collapsed, then switch from collapsed --> hidden
retractAnimation(collapsedToHiddenRunnable);
break;
case STATE_DOT << STATE_EXTENDED:
extendAnimation(changeState);
break;
case STATE_DOT << STATE_DOT:
//NO OP
changeState.run();
break;
case STATE_EXTENDED << STATE_EXTENDED:
retractAnimation(() -> {
//the next updateOutlineColors (after the animation, see the animlistener class default action) will commit to dot type
mCurrentState = STATE_DOT;
extendAnimation(changeState);
}
);
break;
default:
Log.d(TAG, "Unknown transition requested. current:" + current + " next:" + next);
}
}
private void updateOutlineColors() {
if (displayingDrawable) {
mPaintDot.setColor(mColorYellow);
mPaintDotOutline.setColor((mColorLightYellow));
mPaintLarge.setColor(mColorGray);
mPaintLargeOutline.setColor(mColorLightGray);
} else {
mPaintDot.setColor(mColorBlue);
mPaintDotOutline.setColor((mColorLightBlue));
mPaintLarge.setColor(mColorBlue);
mPaintLargeOutline.setColor(mColorLightBlue);
}
}
// ===========================================================================================================================
private int measureElements() {
//put down the cursor then move it to the right
float centerY = (int) (mHeight / 2f);
int cursor;
//text inside the bubble in the left of the score view
if (displayBubble) {
//if we don't display the multiplier bubble, there's no need to compute the score multiplier & prefix related stuff
mMultiplierText = Integer.toString(mMultiplier);
Rect xBounds = new Rect();
mPaintTextSmall.getTextBounds(mMultiplierPrefix, 0, mMultiplierPrefix.length(), xBounds);
Rect mulBounds = new Rect();
mPaintTextLarge.getTextBounds(mMultiplierText, 0, mMultiplierText.length(), mulBounds);
cursor = (int) (mHeight / 2f - (xBounds.width() + mulBounds.width()) / 2f - oneDip * 3f / 2f);
mPrefixY = (int) (centerY + xBounds.height() / 2f);
mPrefixX = (int) (cursor + xBounds.width() / 2f);
cursor = cursor + xBounds.width() + (int) (oneDip * 3f);
mMultiplierY = (int) (centerY + mulBounds.height() / 2f);
mMultiplierX = (int) (cursor + mulBounds.width() / 2f);
}
//text outside of the bubble
Rect valueTextBounds = new Rect();
mPaintTextLarge.getTextBounds(mValueText, 0, mValueText.length(), valueTextBounds);
Rect valueSuffixTextBounds = new Rect();
mPaintTextSmall.getTextBounds(mValueSuffix, 0, mValueSuffix.length(), valueSuffixTextBounds);
boolean displayOnlyDrawable = valueTextBounds.width() == 0 && displayingDrawable;
if (displayBubble || displayingDrawable) {
// the height acts the role of the bubble diameter here...
cursor = (int) (mHeight + (displayOnlyDrawable ? 0 : oneDip * 5f));
} else {
cursor = (int) (mOutlineWidth + oneDip * 10f);
}
mScoreY = (int) (centerY + valueTextBounds.height() / 2f);
mScoreX = (int) (cursor + valueTextBounds.width() / 2f);
cursor = (int) (cursor + valueTextBounds.width() + (displayOnlyDrawable ? 0 : oneDip * 5f));
if (!displayingDrawable) {
mScoreSuffixY = (int) (centerY + valueSuffixTextBounds.height() / 2f);
mScoreSuffixX = (int) (cursor + valueSuffixTextBounds.width() / 2f);
cursor = (int) (cursor + valueSuffixTextBounds.width() + oneDip * 10);
} else {
cursor = (int) (cursor + (displayOnlyDrawable ? 0 : oneDip * 10));
}
return Math.max(cursor, (int) mHeight);
}
private void extendAnimation(final Runnable runnable) {
// Log.d(TAG, "extendAnimation: ");
ResizeAnimation extend =
new ResizeAnimation(this, getWidthForState(STATE_DOT), getHeightForState(STATE_DOT), getWidthForState(STATE_EXTENDED),
getHeightForState(STATE_EXTENDED));
// extend.setFillAfter(true);
extend.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
if (runnable != null) {
runnable.run();
}
super.onAnimationEnd(animation);
}
});
extend.setDuration(300);
startAnimation(extend);
}
private void retractAnimation(final Runnable endAction) {
// Log.d(TAG, "retractAnimation: ");
ResizeAnimation retract =
new ResizeAnimation(this, getWidthForState(STATE_EXTENDED), getHeightForState(STATE_EXTENDED), getWidthForState(STATE_DOT),
getHeightForState(STATE_DOT));
// retract.setFillAfter(true);
retract.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
if (endAction != null) {
endAction.run();
}
super.onAnimationEnd(animation);
}
});
retract.setDuration(300);
startAnimation(retract);
}
private void appearAnimation(final Runnable endAction) {
// Log.d(TAG, "appearAnimation: to " + mHeight + "x" + mHeight);
ResizeAnimation animation = new ResizeAnimation(this, 0, 0, getWidthForState(STATE_DOT), getHeightForState(STATE_DOT));
animation.setDuration(300);
// animation.setFillAfter(true);
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
if (endAction != null) {
endAction.run();
}
super.onAnimationEnd(animation);
}
});
startAnimation(animation);
}
private void hideAnimation(final Runnable endAction) {
// Log.d(TAG, "appearAnimation: to " + mHeight + "x" + mHeight);
float widthForDot = getWidthForState(STATE_DOT);
ResizeAnimation animation = new ResizeAnimation(this, widthForDot, widthForDot, 0, 0);
animation.setDuration(300);
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
if (endAction != null) {
endAction.run();
}
super.onAnimationEnd(animation);
}
});
startAnimation(animation);
}
@StringDef
public @interface ScoreSuffix {
String POINTS = "pts",
PER_KM = "/km";
}
private abstract class AnimationListener implements Animation.AnimationListener {
public static final String TAG = "AnimationListener";
@Override
public void onAnimationStart(Animation animation) {
mDrawTexts = false;
}
@Override
public void onAnimationEnd(Animation animation) {
mDrawTexts = true;
ViewGroup.LayoutParams lp = getLayoutParams();
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;
setLayoutParams(lp);
measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
requestLayout();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
} |
import { Document } from 'mongoose';
export interface StorageInfo extends Document{
operation: string;
quantity: number;
unitCost: number;
type: string;
existence: number;
balance: Balance;
}
interface Balance {
quantity: number | null;
unitCost: number | null;
total: number | null;
} |
<reponame>emagana/clouddriver<filename>clouddriver-kubernetes/src/main/java/com/netflix/spinnaker/clouddriver/kubernetes/caching/view/provider/KubernetesManifestContainerBuilder.java
/*
* Copyright 2018 Google, 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.
*
*/
package com.netflix.spinnaker.clouddriver.kubernetes.caching.view.provider;
import com.netflix.spinnaker.clouddriver.kubernetes.caching.view.model.KubernetesManifestContainer;
import com.netflix.spinnaker.clouddriver.kubernetes.description.KubernetesPodMetric;
import com.netflix.spinnaker.clouddriver.kubernetes.description.KubernetesResourceProperties;
import com.netflix.spinnaker.clouddriver.kubernetes.description.manifest.KubernetesKind;
import com.netflix.spinnaker.clouddriver.kubernetes.description.manifest.KubernetesManifest;
import com.netflix.spinnaker.clouddriver.kubernetes.description.manifest.KubernetesManifestAnnotater;
import com.netflix.spinnaker.clouddriver.kubernetes.op.handler.KubernetesHandler;
import com.netflix.spinnaker.clouddriver.kubernetes.security.KubernetesCredentials;
import com.netflix.spinnaker.kork.annotations.NonnullByDefault;
import com.netflix.spinnaker.moniker.Moniker;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
@NonnullByDefault
final class KubernetesManifestContainerBuilder {
static KubernetesManifestContainer buildManifest(
KubernetesCredentials credentials,
KubernetesManifest manifest,
List<KubernetesManifest> events,
List<KubernetesPodMetric.ContainerMetric> metrics) {
String namespace = manifest.getNamespace();
KubernetesKind kind = manifest.getKind();
KubernetesResourceProperties properties = credentials.getResourcePropertyRegistry().get(kind);
Function<KubernetesManifest, String> lastEventTimestamp =
(m) -> (String) m.getOrDefault("lastTimestamp", m.getOrDefault("firstTimestamp", "n/a"));
events =
events.stream()
.sorted(Comparator.comparing(lastEventTimestamp))
.collect(Collectors.toList());
Moniker moniker = KubernetesManifestAnnotater.getMoniker(manifest);
KubernetesHandler handler = properties.getHandler();
return KubernetesManifestContainer.builder()
.account(credentials.getAccountName())
.name(manifest.getFullResourceName())
.location(namespace)
.manifest(manifest)
.moniker(moniker)
.status(handler.status(manifest))
.artifacts(handler.listArtifacts(manifest))
.events(events)
.warnings(handler.listWarnings(manifest))
.metrics(metrics)
.build();
}
}
|
<filename>batching-core/src/test/java/com/flipkart/batching_core/data/DataTest.java
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Flipkart Internet Pvt. Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.flipkart.batching.core.data;
import com.flipkart.batching.core.Data;
import junit.framework.Assert;
import org.junit.Test;
public class DataTest {
/**
* Test to verify {@link Data#equals(Object)}
*/
@Test
public void testEqualsData() {
Data data = new EventData();
Assert.assertTrue(!data.equals("e"));
}
/**
* Test to verify {@link TagData}
*/
@Test
public void testTagData() {
Tag AD_TAG = new Tag("ADS");
TagData tagData = new TagData(AD_TAG);
Assert.assertTrue(tagData.getTag() == AD_TAG);
}
/**
* Test to verify the equals method in {@link TagData}
*/
@Test
public void testTagEqualsData() {
Tag AD_TAG = new Tag("ADS");
Tag DEBUG_TAG = new Tag("DEBUG");
TagData adsTagData = new TagData(AD_TAG);
TagData debugTagData = new TagData(DEBUG_TAG);
Assert.assertTrue(!adsTagData.equals(debugTagData));
Assert.assertTrue(!adsTagData.equals(""));
}
}
|
<reponame>rim-wood/dandelion
package cn.icepear.dandelion.job;
import cn.icepear.dandelion.common.security.annotation.EnableDandelionResourceServer;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
/**
* @author rimwood
* @date 2019-04-15
* DAAS平台定时任务服务
*/
@EnableDubbo
@ImportResource({"classpath:dubbo/dandelion_schedulejob_dubbo.xml","${spring.dubbo.profile}"})
@SpringBootApplication(scanBasePackages = "cn.icepear.dandelion")
@EnableDandelionResourceServer
public class ScheduleJobApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleJobApplication.class, args);
}
}
|
"""Project: Eskapade - A python-based package for data analysis.
Class: KernelDensityEstimation
Created: 2018-07-18
Description:
Algorithm to execute kernel density estimation (kernel bandwith fitting) on a data set with mixed data types
(unordered categorical, ordered categorical and continuous).
Authors:
KPMG Advanced Analytics & Big Data team, Amstelveen, The Netherlands
Redistribution and use in source and binary forms, with or without
modification, are permitted according to the terms listed in the file
LICENSE.
"""
import numpy as np
from statsmodels.nonparametric import kernel_density
from eskapade.data_mimic import data_mimic_util as ut
from eskapade import process_manager, DataStore, Link, StatusCode
class KernelDensityEstimation(Link):
"""
Executes kernel density estimation (kernel bandwith fitting) on a data set with mixed data types (unordered
categorical, ordered categorical and continuous).
Data flow:
5. concatenation of data_no_nans (unordered categorical and ordered categorical) and data_normalized (only
continuous) -> d
+ 5b KDEMultivariate() on d -> bw (bandwiths)
"""
def __init__(self, **kwargs):
"""Initialize an instance.
:param str name: name of link
:param str data_no_nans_read_key: key of data_no_nans to read from data store
:param str data_normalized_read_key: key of data_normalized to read from data store
:param str data_normalized_pca_read_key:
:param bool do_pca: flag indicting whether to apply a pca transformation
:param str store_key: key of output data to store in data store
"""
# initialize Link, pass name from kwargs
Link.__init__(self, kwargs.pop('name', 'KernelDensityEstimation'))
# Process and register keyword arguments. If the arguments are not given, all arguments are popped from
# kwargs and added as attributes of the link. Otherwise, only the provided arguments are processed.
self._process_kwargs(kwargs, data_no_nans_read_key=None, data_normalized_read_key=None,
data_normalized_pca_read_key=None, do_pca=False, store_key=None)
# check residual kwargs; exit if any present
self.check_extra_kwargs(kwargs)
# Turn off the line above, and on the line below if you wish to keep these extra kwargs.
# self._process_kwargs(kwargs)
def initialize(self):
"""Initialize the link.
:returns: status code of initialization
:rtype: StatusCode
"""
return StatusCode.Success
def execute(self):
"""Execute the link.
:returns: status code of execution
:rtype: StatusCode
"""
# --- your algorithm code goes here
self.logger.debug('Now executing link: {link}.', link=self.name)
ds = process_manager.service(DataStore)
unordered_categorical_i = ds['unordered_categorical_i']
ordered_categorical_i = ds['ordered_categorical_i']
continuous_i = ds['continuous_i']
data_no_nans = ds[self.data_no_nans_read_key]
# Concatenate normalized data with original categorical data
# if one of unordered_categorical_i, ordered_categorical_i, data_normalized is empty, then concatenating will
# not work (see next line). We thus make them of the correct length
data_unordered_categorical = data_no_nans[:, unordered_categorical_i]
data_ordered_categorical = data_no_nans[:, ordered_categorical_i]
n_obs = len(data_no_nans)
if data_unordered_categorical.size == 0:
data_unordered_categorical = np.empty(shape=(n_obs,0))
if data_ordered_categorical.size == 0:
data_ordered_categorical = np.empty(shape=(n_obs,0))
if self.do_pca:
data_normalized_pca = ds[self.data_normalized_pca_read_key]
d = np.concatenate((data_unordered_categorical,
data_ordered_categorical, data_normalized_pca), axis=1)
else:
data_normalized = ds[self.data_normalized_read_key]
if data_normalized.size == 0:
data_normalized = np.empty(shape=(n_obs, 0))
d = np.concatenate((data_unordered_categorical,
data_ordered_categorical, data_normalized), axis=1)
var_type = 'u' * len(unordered_categorical_i) + 'o' * len(ordered_categorical_i) + \
'c' * len(continuous_i)
# NB: statsmodels uses normal reference for unordered categorical variables as well!
# NB: the bandwiths are determined on the normalized continuous data and on the original categorical data
if (len(continuous_i) == 0) & (len(ordered_categorical_i)==0):
kde_weights = ut.kde_only_unordered_categorical(d)
ds[self.store_key] = kde_weights
else:
kde = kernel_density.KDEMultivariate(d, var_type=var_type, bw='normal_reference')
ds[self.store_key] = kde.bw
return StatusCode.Success
def finalize(self):
"""Finalize the link.
:returns: status code of finalization
:rtype: StatusCode
"""
# --- any code to finalize the link follows here
return StatusCode.Success
|
#!/bin/bash
# master build script
SELFDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export TOPDIR=$SELFDIR
sudo apt-get install libfuse-dev
cd $TOPDIR/cache/unionfs-fuse && make
cd $TOPDIR/cache/unionfs-fuse && sudo make install
|
package com.vxml.tag;
import org.w3c.dom.Node;
import com.vxml.audio.NativeCommand;
import com.vxml.core.browser.VxmlBrowser;
public class ValueTag extends AbstractTag {
public ValueTag(Node node) {
super(node);
}
@Override
public void execute() {
if (getNode().getParentNode().getNodeName().equals("prompt")) {
String expr = getAttribute("expr");
Object value = VxmlBrowser.getContext().executeScript(expr);
try {
new NativeCommand().speak(value.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
<gh_stars>0
import { NotImplementedError } from '../extensions/index.js';
/**
* Given an array with heights, sort them except if the value is -1.
*
* @param {Array} arr
* @return {Array}
*
* @example
* arr = [-1, 150, 190, 170, -1, -1, 160, 180]
*
* The result should be [-1, 150, 160, 170, -1, -1, 180, 190]
*/
export default function sortByHeight(arr) {
let a = [];
for(let i = 0; i < arr.length; i ++)
if (arr[i] != -1)
a.push(arr[i]);
a.sort(function(a, b){
return a - b;
});
let j = 0;
for(let i = 0; i < arr.length; i ++)
if (arr[i] != -1){
arr[i] = a[j];
j ++;
}
return arr;
}
console.log(sortByHeight( [ 11, 16, 2, 2, 4, 9 ])); |
package main
import (
"fmt"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/brotherlogic/executor/proto"
)
func (s *Server) runExecute(req *pb.ExecuteRequest) (string, error) {
return s.scheduler.schedule(req.Command, req.GetKey())
}
// Execute executes a command
func (s *Server) Execute(ctx context.Context, req *pb.ExecuteRequest) (*pb.ExecuteResponse, error) {
sTime := time.Now()
output, err := s.scheduler.schedule(req.Command, req.GetKey())
return &pb.ExecuteResponse{
TimeTakenInMillis: time.Now().Sub(sTime).Nanoseconds() / 100000,
CommandOutput: output,
}, err
}
func mini(a, b int) int {
if a > b {
return b
}
return a
}
// QueueExecute executes a command
func (s *Server) QueueExecute(ctx context.Context, req *pb.ExecuteRequest) (*pb.ExecuteResponse, error) {
// Pre clean the queue
nq := []*queueEntry{}
for _, q := range s.archive {
if !q.req.GetReadyForDeletion() {
nq = append(nq, q)
}
}
s.archive = nq
archive.Set(float64(len(s.archive)))
Backlog.Set(float64(len(s.queue)))
for _, q := range s.archive {
match := q.req.Command.Binary == req.Command.Binary && len(q.req.Command.Parameters) == len(req.Command.Parameters)
for i := 0; i < mini(len(q.req.Command.Parameters), len(req.Command.Parameters)); i++ {
match = match && q.req.Command.Parameters[i] == req.Command.Parameters[i]
}
if match {
s.Log(fmt.Sprintf("Found in queue"))
q.req.ReadyForDeletion = q.req.GetCommand().GetDeleteOnComplete() || q.resp.GetExitCode() != 0
return q.resp, nil
}
}
if len(s.queue) > 90000 {
return nil, status.Errorf(codes.ResourceExhausted, "Execute queue is full")
}
r := &pb.ExecuteResponse{Status: pb.CommandStatus_IN_QUEUE}
entry := &queueEntry{req: req, resp: r, ack: make(chan bool, 100)}
s.archive = append(s.archive, entry)
archive.Set(float64(len(s.archive)))
s.Log(fmt.Sprintf("Adding to queue: %v", len(s.queue)))
s.queue <- entry
s.Log(fmt.Sprintf("Added to queue"))
return r, nil
}
|
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import * as d3 from 'd3';
@Component({
selector: 'app-stackedarea',
templateUrl: '../../common/common.html',
styleUrls: ['../../common/common.css', './stackedarea.component.css'],
encapsulation: ViewEncapsulation.None
})
export class StackedareaComponent implements OnInit {
private code: string;
constructor() { }
ngOnInit() {
const w = 500;
const h = 400;
const padding = 20;
let xScale, yScale, xAxis, yAxis, area;
const parseTime = d3.timeParse('%Y-%m');
const formatTime = d3.timeFormat('%b %Y');
const rowConverter = function (d, i, cols) {
const row = {
date: parseTime(d.Date),
};
for (let j = 1; j < cols.length; j++) {
const col = cols[j];
if (d[cols[j]]) {
row[cols[j]] = +d[cols[j]];
} else {
row[cols[j]] = 0;
}
}
return row;
};
const stack = d3.stack()
.order(d3.stackOrderDescending);
d3.csv('assets/ev_sales_data.csv', rowConverter, function (data) {
const dataset = data;
const keys = dataset.columns;
keys.shift();
stack.keys(keys);
const series = stack(dataset);
xScale = d3.scaleTime()
.domain([
d3.min(dataset, function (d) { return d.date; }),
d3.max(dataset, function (d) { return d.date; })
])
.range([padding, w - padding * 2]);
yScale = d3.scaleLinear()
.domain([
0,
d3.max(dataset, function (d) {
let sum = 0;
for (let i = 0; i < keys.length; i++) {
sum += d[keys[i]];
}
return sum;
})
])
.range([h - padding, padding / 2])
.nice();
xAxis = d3.axisBottom()
.scale(xScale)
.ticks(10)
.tickFormat(formatTime);
yAxis = d3.axisRight()
.scale(yScale)
.ticks(5);
area = d3.area()
.x(function (d) { return xScale(d.data.date); })
.y0(function (d) { return yScale(d[0]); })
.y1(function (d) { return yScale(d[1]); });
const svg = d3.select('.result')
.append('svg')
.attr('width', w)
.attr('height', h);
svg.selectAll('path')
.data(series)
.enter()
.append('path')
.attr('class', 'area')
.attr('d', area)
.attr('fill', function (d, i) {
return d3.schemeCategory20[i];
})
.append('title')
.text(function (d) {
return d.key;
});
svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0,' + (h - padding) + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(' + (w - padding * 2) + ',0)')
.call(yAxis);
});
this.code = `const w = 500;
const h = 400;
const padding = 20;
let xScale, yScale, xAxis, yAxis, area;
const parseTime = d3.timeParse('%Y-%m');
const formatTime = d3.timeFormat('%b %Y');
const rowConverter = function (d, i, cols) {
const row = {
date: parseTime(d.Date),
};
for (let j = 1; j < cols.length; j++) {
const col = cols[j];
if (d[cols[j]]) {
row[cols[j]] = +d[cols[j]];
} else {
row[cols[j]] = 0;
}
}
return row;
};
const stack = d3.stack()
.order(d3.stackOrderDescending);
d3.csv('assets/ev_sales_data.csv', rowConverter, function (data) {
const dataset = data;
const keys = dataset.columns;
keys.shift();
stack.keys(keys);
const series = stack(dataset);
xScale = d3.scaleTime()
.domain([
d3.min(dataset, function (d) { return d.date; }),
d3.max(dataset, function (d) { return d.date; })
])
.range([padding, w - padding * 2]);
yScale = d3.scaleLinear()
.domain([
0,
d3.max(dataset, function (d) {
let sum = 0;
for (let i = 0; i < keys.length; i++) {
sum += d[keys[i]];
}
return sum;
})
])
.range([h - padding, padding / 2])
.nice();
xAxis = d3.axisBottom()
.scale(xScale)
.ticks(10)
.tickFormat(formatTime);
yAxis = d3.axisRight()
.scale(yScale)
.ticks(5);
area = d3.area()
.x(function (d) { return xScale(d.data.date); })
.y0(function (d) { return yScale(d[0]); })
.y1(function (d) { return yScale(d[1]); });
const svg = d3.select('.result')
.append('svg')
.attr('width', w)
.attr('height', h);
svg.selectAll('path')
.data(series)
.enter()
.append('path')
.attr('class', 'area')
.attr('d', area)
.attr('fill', function (d, i) {
return d3.schemeCategory20[i];
})
.append('title')
.text(function (d) {
return d.key;
});
svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0,' + (h - padding) + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(' + (w - padding * 2) + ',0)')
.call(yAxis);
});`;
}
}
|
import { createApp } from 'vue3';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
// App.vue
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
// router.js
import { createRouter, createWebHashHistory } from 'vue3-router';
import Lobby from './views/Lobby.vue';
import Game from './views/Game.vue';
export default createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
component: Lobby
},
{
path: '/game/:id',
component: Game
}
]
}); |
<filename>src/index.js
// Importing node-modules we need
import { default as Web3 } from "web3";
import { default as contract } from "truffle-contract";
import TakaABI from "../build/contracts/TakaToken.json";
// Importing compiled contracts here
// Importing styles
import styles from "./styles/index.scss";
// Making usable abstraction from our artifacts, so we can use it in code.
var TakaToken = contract(TakaABI);
let currAddr;
let currAmnt;
window.App = {
/**
* Initializing Web3 provider for our app
*/
initWeb3: () => {
if (typeof web3 !== "undefined") web3 = new Web3(web3.currentProvider);
else
web3 = new Web3(
new Web3.providers.HttpProvider("http://localhost:9545")
);
},
/**
* Initializing our App
*/
init: () => {
App.initWeb3();
// Init your contract here and set web3provider to it.
TakaToken.setProvider(web3.currentProvider);
//currAddr = web3.eth.defaultAccount;
web3.eth.getAccounts(function (erro, result) {
web3.eth.defaultAccount = result[0];
currAddr = web3.eth.defaultAccount;
console.log("Sender's Account: " + web3.eth.defaultAccount);
document.getElementById("currAddr").innerHTML = web3.eth.defaultAccount;
});
App.getBalance();
},
getBalance: () => {
currAmnt = document.getElementById("currAmnt");
TakaToken.deployed().then((instance) => {
return instance.balanceOf(web3.eth.defaultAccount)
}).then(res => {
console.log('Current balance: ' + res.toNumber());
currAmnt.innerHTML = res.toNumber();
})
},
transferTaka: () => {
let receiver = document.getElementById("receiver");
let amount = document.getElementById("amountToBeSent");
let status = document.getElementById("status");
TakaToken.deployed().then(instance => {
console.log( "receiver.value: " + receiver.value);
console.log('Amount to be sent: ' + amount.value);
instance.transfer(receiver.value, amount.value, { from: currAddr }).then (res => {
instance.Transfer().watch( (err, result) => {
console.log( err, result);
instance.balanceOf(currAddr).then( res => {
currAmnt.innerHTML = res.toNumber();
status.innerHTML = "Last completed event: " + result.event;
receiver.value = "";
amount.value = "";
});
});
})
.catch ( (err) => {
console.log(err)
})
})
}
};
/**
* Initializing our App on window load
* 'load' Happens when browser window loads
*/
window.addEventListener("load", () => {
App.init();
});
|
#!/bin/sh
#
#-----------------------BEGIN NOTICE -- DO NOT EDIT-----------------------
# NASA Goddard Space Flight Center Land Information System (LIS) v7.2
#
# Copyright (c) 2015 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#-------------------------END NOTICE -- DO NOT EDIT-----------------------
#
# Script: wget_native_srtm30.sh
#
# Description:
# Downloads all required 2-D tiled-based 30arcsec SRTM v2.1 elevation files
# When all files are fully downloaded/unzipped, the target directory
# containing the files should be about ~2.8 GB.
#
# Sources:
# http://dds.cr.usgs.gov/srtm/version2_1/SRTM30/
# File Date: 8/23/2010
#
# Script Written by: K. Arsenault; Aug 30, 2013
# 07.04.2014 -- David Mocko: v1.1: Public testcase for LIS-7.0
#
################################################################
rundir=$PWD
targetdir=./PARAMETERS/topo_parms/SRTM
echo "== Downloading the SRTM-30sec Elevation Tile Files == "
# Change directory to target directory where files are to be downloaded to:
mkdir -p $targetdir
cd $targetdir
echo "- Change to target directory: "$targetdir
# Loop over each gridded tile and download *zip file:
for nstile in n90 n40 s10; do
for wetile in w180 w140 w100 w060 w020 e020 e060 e100 e140; do
wget http://dds.cr.usgs.gov/srtm/version2_1/SRTM30/${wetile}${nstile}/${wetile}${nstile}.dem.zip -nv -a ${rundir}/download_srtm30native.log
unzip ${wetile}${nstile}.dem.zip >> ${rundir}/download_srtm30native.log
done
done
# Obtain SRTM30 documentation and version release info:
wget http://dds.cr.usgs.gov/srtm/version2_1/SRTM30/srtm30_documentation.pdf -nv -a ${rundir}/download_srtm30native.log
wget http://dds.cr.usgs.gov/srtm/version2_1/SRTM30/srtm30_version_history.pdf -nv -a ${rundir}/download_srtm30native.log
echo "== Done downloading SRTM30 tile fields."
|
#!/usr/bin/env bash
VERSION_BASE=$(janus version -format='v%M.%m.x')
echo "Deploy to http://builds.etcdevteam.com/emerald-wallet/$VERSION_BASE/"
mkdir deploy
mv ./packages/desktop/dist/*.dmg ./packages/desktop/dist/*.tar.gz ./packages/desktop/dist/*.deb ./packages/desktop/dist/*.zip ./packages/desktop/dist/*.AppImage ./deploy/
janus deploy -to="builds.etcdevteam.com/emerald-wallet/$VERSION_BASE/" -files="./deploy/*" -key="./gcloud-travis.json.enc"
echo "Deployed" |
def print_some(a, b):
print(a, b)
list_of_numbers = [1, 2]
print_some(*list_of_numbers)
# a = {'a': "one", 'b': "two", 'c': "three" }]
# print_some(*a) key
# print_some(**a) value
|
<gh_stars>0
package io.hnfmr.chapter1
object PrintableTut extends App {
// the type class: a generic trait
trait Printable[A] {
def format(a: A): String
}
// instances for each type we care about
object PrintableInstances {
implicit val intPrintable = new Printable[Int] {
def format(a: Int): String = {
a.toString
}
}
implicit val stringPrintable = new Printable[String] {
def format(a: String): String = a
}
implicit val catPrintable = new Printable[Cat] {
def format(cat: Cat): String = s"${cat.name} is a ${cat.age} year-old ${cat.color} cat."
}
}
// one or more generic interface methods
// method 1: interface object
object Printable {
def format[A](a: A)(implicit p: Printable[A]): String = p.format(a)
def print[A](a: A)(implicit p: Printable[A]): Unit = println(p.format(a))
}
final case class Cat ( name: String, age: Int, color: String )
val cat = Cat("Dudu", 1, "Lilac")
import PrintableInstances._
Printable.print(cat)
// method 2: interface syntax (the most common way: implicit classes)
object PrintableSyntax {
implicit class PrintOps[A](value: A) {
def format(implicit p: Printable[A]): String = p.format(value)
def print(implicit p: Printable[A]): Unit = println(format)
}
}
import PrintableSyntax._
cat.print
} |
import { extract } from '../store'
const log = input => {
if (input instanceof Promise) {
return input.then(log)
}
console.log(extract(input))
return input
}
export default log
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.arrowObliqueContract = void 0;
var arrowObliqueContract = {
"viewBox": "0 0 512 512",
"children": [{
"name": "g",
"attribs": {},
"children": [{
"name": "path",
"attribs": {
"fill-rule": "evenodd",
"clip-rule": "evenodd",
"d": "M256,0C114.609,0,0,114.609,0,256s114.609,256,256,256s256-114.609,256-256\r\n\t\tS397.391,0,256,0z M256,472c-119.297,0-216-96.703-216-216S136.703,40,256,40s216,96.703,216,216S375.297,472,256,472z"
},
"children": [{
"name": "path",
"attribs": {
"fill-rule": "evenodd",
"clip-rule": "evenodd",
"d": "M256,0C114.609,0,0,114.609,0,256s114.609,256,256,256s256-114.609,256-256\r\n\t\tS397.391,0,256,0z M256,472c-119.297,0-216-96.703-216-216S136.703,40,256,40s216,96.703,216,216S375.297,472,256,472z"
},
"children": []
}]
}, {
"name": "polygon",
"attribs": {
"fill-rule": "evenodd",
"clip-rule": "evenodd",
"points": "176,144 144,176 184,216 160,240 240,240 240,160 216,184 \t"
},
"children": [{
"name": "polygon",
"attribs": {
"fill-rule": "evenodd",
"clip-rule": "evenodd",
"points": "176,144 144,176 184,216 160,240 240,240 240,160 216,184 \t"
},
"children": []
}]
}, {
"name": "polygon",
"attribs": {
"fill-rule": "evenodd",
"clip-rule": "evenodd",
"points": "352.031,272 272,272 272,351.984 296.016,327.984 336.031,367.984 \r\n\t\t368.031,335.984 328.031,296 \t"
},
"children": [{
"name": "polygon",
"attribs": {
"fill-rule": "evenodd",
"clip-rule": "evenodd",
"points": "352.031,272 272,272 272,351.984 296.016,327.984 336.031,367.984 \r\n\t\t368.031,335.984 328.031,296 \t"
},
"children": []
}]
}]
}]
};
exports.arrowObliqueContract = arrowObliqueContract; |
import java.util.Scanner;
public class ChatBot {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hi, What's your name?");
String name = input.nextLine();
System.out.println("Nice to meet you, " + name + "!");
}
} |
package version
import (
"context"
"net/http"
"net/url"
"time"
"github.com/google/go-github/v28/github"
"github.com/gorilla/mux"
goversion "github.com/hashicorp/go-version"
"github.com/traefik/traefik/v2/pkg/log"
"github.com/unrolled/render"
)
var (
// Version holds the current version of traefik.
Version = "dev"
// Codename holds the current version codename of traefik.
Codename = "cheddar" // beta cheese
// BuildDate holds the build date of traefik.
BuildDate = "I don't remember exactly"
// StartDate holds the start date of traefik.
StartDate = time.Now()
// UUID instance uuid.
UUID string
// PilotEnabled activate integration of pilot into the dashboard.
PilotEnabled bool
)
// Handler expose version routes.
type Handler struct{}
var templatesRenderer = render.New(render.Options{
Directory: "nowhere",
})
// Append adds version routes on a router.
func (v Handler) Append(router *mux.Router) {
router.Methods(http.MethodGet).Path("/api/version").
HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
v := struct {
Version string
Codename string
StartDate time.Time `json:"startDate"`
UUID string `json:"uuid,omitempty"`
PilotEnabled bool `json:"pilotEnabled"`
}{
Version: Version,
Codename: Codename,
StartDate: StartDate,
UUID: UUID,
PilotEnabled: PilotEnabled,
}
if err := templatesRenderer.JSON(response, http.StatusOK, v); err != nil {
log.WithoutContext().Error(err)
}
})
}
// CheckNewVersion checks if a new version is available.
func CheckNewVersion() {
if Version == "dev" {
return
}
logger := log.WithoutContext()
client := github.NewClient(nil)
updateURL, err := url.Parse("https://update.traefik.io/")
if err != nil {
logger.Warnf("Error checking new version: %s", err)
return
}
client.BaseURL = updateURL
releases, resp, err := client.Repositories.ListReleases(context.Background(), "traefik", "traefik", nil)
if err != nil {
logger.Warnf("Error checking new version: %s", err)
return
}
if resp.StatusCode != http.StatusOK {
logger.Warnf("Error checking new version: status=%s", resp.Status)
return
}
currentVersion, err := goversion.NewVersion(Version)
if err != nil {
logger.Warnf("Error checking new version: %s", err)
return
}
for _, release := range releases {
releaseVersion, err := goversion.NewVersion(*release.TagName)
if err != nil {
logger.Warnf("Error checking new version: %s", err)
return
}
if len(currentVersion.Prerelease()) == 0 && len(releaseVersion.Prerelease()) > 0 {
continue
}
if releaseVersion.GreaterThan(currentVersion) {
logger.Warnf("A new release has been found: %s. Please consider updating.", releaseVersion.String())
return
}
}
}
|
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for item in soup.find_all('p'):
print(item.text) |
import os
import time
import numpy as np
import pandas as pd
import tensorflow as tf
import tqdm
from autoencoder_model import CVAE
def data_generator(data_folderpath, index):
name_list = os.listdir(data_folderpath)
for name in [name_list[i] for i in index]:
data_filepath = os.path.join(data_folderpath, name)
tile = np.load(data_filepath)
yield (tile,)
if __name__ == '__main__':
# paths
data_folderpath = '/n/scratch2/hungyiwu/project_deeptile/data/tile_15x15'
# model params
latent_dim = 5
batch_size = 16
num_epoch = 5
learning_rate = 1e-5
train_fraction = 0.8
verbosity = 0
# derived params
example_filepath = os.path.join(data_folderpath, os.listdir(data_folderpath)[0])
tile_shape = np.load(example_filepath).shape
num_cell = len(os.listdir(data_folderpath))
all_index = np.arange(num_cell, dtype=int)
np.random.shuffle(all_index)
num_train = int(num_cell * train_fraction)
train_index = all_index[0:num_train]
test_index = all_index[num_train:]
# build dataset, model, optimizer
tile_dtype = np.float32
train_data = tf.data.Dataset.from_generator(
generator=lambda: data_generator(data_folderpath, train_index),
output_types=(tile_dtype,),
output_shapes=(tile_shape,),
).batch(batch_size)
test_data = tf.data.Dataset.from_generator(
generator=lambda: data_generator(data_folderpath, test_index),
output_types=(tile_dtype,),
output_shapes=(tile_shape,),
).batch(batch_size)
optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
model = CVAE(latent_dim=latent_dim, input_shape=tile_shape, optimizer=optimizer)
# utility function
batch_count_dict = dict(train=None, test=None)
def train():
ts_start = time.time()
epoch_loss = 0
batch_count = 0
for (X,) in tqdm.tqdm(iterable=train_data, desc='train',
total=batch_count_dict['train'], disable=not verbosity):
batch_loss = model.compute_apply_gradients(X)
epoch_loss += tf.reduce_mean(batch_loss).numpy()
batch_count += 1
if batch_count_dict['train'] is None:
batch_count_dict['train'] = batch_count
ts_end = time.time()
return dict(loss=epoch_loss/batch_count, runtime=ts_end-ts_start)
def test():
ts_start = time.time()
epoch_loss = 0
batch_count = 0
for (X,) in tqdm.tqdm(iterable=test_data, desc='test',
total=batch_count_dict['test'], disable=not verbosity):
batch_loss = model.compute_loss(X)
epoch_loss += tf.reduce_mean(batch_loss).numpy()
batch_count += 1
if batch_count_dict['test'] is None:
batch_count_dict['test'] = batch_count
ts_end = time.time()
return dict(loss=epoch_loss/batch_count, runtime=ts_end-ts_start)
# main loop
test_output = test()
print('before training', flush=True)
print('test loss: {:.3f}, runtime {:.0f} sec,'.format(
test_output['loss'], test_output['runtime']), flush=True)
for epoch_index in range(num_epoch):
train_output = train()
test_output = test()
print('epoch: {}/{}'.format(epoch_index+1, num_epoch), flush=True)
print('train loss: {:.3f}, runtime {:.0f} sec,'.format(
train_output['loss'], train_output['runtime']), flush=True)
print('test loss: {:.3f}, runtime {:.0f} sec,'.format(
test_output['loss'], test_output['runtime']), flush=True)
|
set -e
applicationHost="http://localhost:8098"
applicationId="XXXXXXXX-YYYY-AAA-BBBB-CCCCCCCCCCC"
applicationSecret="XXXXXXXX-YYYY-AAAA-BBBB-CCCCCCCCCCC"
password="Your Password"
# Receive SMS
/usr/local/bin/huawei-hilink messages --url=192.168.8.1 --exportFile='/opt/modem/messages.json' --exportFormat=json --deleteAfter=true --password="${password}"
if [ -f "/opt/modem/messages.json" ]; then
/usr/local/bin/huawei-phevctl.sh readFileAndSendMessage --applicationId="${applicationId}" --applicationSecret="${applicationSecret}" --messagesFile='/opt/modem/messages.json'
mkdir -p /opt/modem/logs
cp -rf /opt/modem/messages.json /opt/modem/logs/`date +"%d-%m-%y"`_messages.json
rm -rf /opt/modem/messages.json
fi
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.barChartO = void 0;
var barChartO = {
"viewBox": "0 0 2048 1792",
"children": [{
"name": "path",
"attribs": {
"d": "M640 896v512h-256v-512h256zM1024 384v1024h-256v-1024h256zM2048 1536v128h-2048v-1536h128v1408h1920zM1408 640v768h-256v-768h256zM1792 256v1152h-256v-1152h256z"
}
}]
};
exports.barChartO = barChartO; |
#!/bin/bash
#
#
# Release a branch. APP_BUILD_DIR should be updated at the Travis configuration level.
release()
{
local DEPLOY_BRANCH=$1
local BUILD_DIR=$APP_BUILD_DIR
printf "${YELLOW}PUSHING ${DEPLOY_BRANCH}${NOCOLOR}\n"
rm -rf "./${BUILD_DIR}/.git"
.travis/release.sh "${DEPLOY_BRANCH}"
printf "${GREEN}COMPLETED ${DEPLOY_BRANCH}${NOCOLOR}\n"
}
#
#
# CI/Dev beta release for "ci" and "qa" "beta" and "stable" branches, based on deploy stage name
#
releaseDev()
{
if [[ "${TRAVIS_BRANCH}" = "ci-beta" || "${TRAVIS_BRANCH}" = "dev" || "${TRAVIS_BRANCH}" = "ci" ]] && [[ $TRAVIS_BUILD_STAGE_NAME == *"Beta"* ]]; then
release "ci-beta"
release "qa-beta"
fi
if [[ "${TRAVIS_BRANCH}" = "ci-stable" || "${TRAVIS_BRANCH}" = "test" || "${TRAVIS_BRANCH}" = "qa" ]] && [[ $TRAVIS_BUILD_STAGE_NAME != *"Beta"* ]]; then
release "ci-stable"
release "qa-stable"
fi
}
#
#
# Prod release for "master" and "stage" branches based on deploy stage name.
#
releaseProd()
{
if [[ "${TRAVIS_BRANCH}" = "prod-beta" || "${TRAVIS_BRANCH}" = "stage" ]] && [[ $TRAVIS_BUILD_STAGE_NAME == *"Beta"* ]]; then
release "prod-beta"
fi
if [[ "${TRAVIS_BRANCH}" = "prod-stable" || "${TRAVIS_BRANCH}" = "prod" || "${TRAVIS_BRANCH}" = "main" || "${TRAVIS_BRANCH}" = "master" ]] && [[ $TRAVIS_BUILD_STAGE_NAME != *"Beta"* ]]; then
if [[ "${TRAVIS_COMMIT_MESSAGE}" = *"chore(release):"* ]]; then
release "prod-stable"
fi
fi
}
#
#
# main()
#
{
set -e
set -x
BLUE="\e[34m"
RED="\e[31m"
GREEN="\e[32m"
YELLOW="\e[33m"
NOCOLOR="\e[39m"
releaseDev
releaseProd
}
|
export default [
{ key: 'layout', label: 'Introduction', to: '/layout' },
{
key: 'tutorials',
label: 'Tutorials',
subMenus: [
{
key: 'dashboard-layout',
label: 'Dashboard Layout',
to: '/layout/tutorials/dashboard-layout/',
},
{
key: 'blog-layout',
label: 'Blog Layout',
to: '/layout/tutorials/blog-layout/',
},
],
},
{ key: 'builder', label: 'Builder', to: '/layout/builder' },
{
key: 'presets',
label: 'Presets',
subMenus: [
{
key: 'default',
label: 'Default',
to: '/layout/presets/default',
},
{
key: 'standard',
label: 'Standard',
to: '/layout/presets/standard',
},
{
key: 'content-based',
label: 'Content Based',
to: '/layout/presets/content-based',
},
{
key: 'cozy',
label: 'Cozy',
to: '/layout/presets/cozy',
},
{
key: 'fixed',
label: 'Fixed',
to: '/layout/presets/fixed',
},
{
key: 'mui-treasury',
label: 'MUI Treasury',
to: '/layout/presets/mui-treasury',
},
],
},
{
key: 'basic-examples',
label: 'Basic Examples',
subMenus: [
{
key: 'custom-theme',
label: 'Custom theme',
to: '/layout/basic-examples/custom-theme?bgColor=d4b397',
},
{
key: 'custom-styles',
label: 'Custom styles',
to:
'/layout/basic-examples/custom-styles?bgColor=213E9B&accent=rgb(17, 254, 220)&dark=true',
},
{
key: 'control-sidebar',
label: 'Control Sidebar',
to:
'/layout/basic-examples/control-sidebar?bgColor=e9e9e9&primary=36338E&accent=ff9600',
},
{
key: 'secondary-sidebar',
label: '2nd Sidebar',
to: '/layout/basic-examples/secondary-sidebar',
},
{
key: 'inset-sidebar',
label: 'Inset Sidebar',
to: '/layout/basic-examples/inset-sidebar',
},
],
},
{
key: 'clones',
label: 'Clones',
subMenus: [
{
key: 'reactjs',
label: 'React Doc',
to: '/layout/clones/reactjs?bgColor=b6c0d4',
},
{
key: 'messenger',
label: 'Messenger',
to: '/layout/clones/messenger?bgColor=rgb(0,153,255)&dark=true',
},
{
key: 'shopping-cart',
label: 'Shopping Cart',
to: '/layout/clones/shopping-cart?bgColor=EAEEF1',
},
],
},
];
|
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for RHSA-2013:0730
#
# Security announcement date: 2013-04-10 09:09:35 UTC
# Script generation date: 2017-01-11 21:24:34 UTC
#
# Operating System: Red Hat 6
# Architecture: x86_64
#
# Vulnerable packages fix on version:
# - flash-plugin.i686:11.2.202.280-2.el6
#
# Last versions recommanded by security team:
# - flash-plugin.i686:24.0.0.194-1.el6_8
#
# CVE List:
# - CVE-2013-1378
# - CVE-2013-1379
# - CVE-2013-1380
# - CVE-2013-2555
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo yum install flash-plugin.i686-24.0.0.194 -y
|
package com.report.application.service;
import com.report.application.port.driven.PlanetCrawler;
import com.report.application.port.driven.PlanetRepository;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class PlanetCrawlerTaskFactory {
private final PlanetCrawler planetCrawler;
private final PlanetRepository planetRepository;
PlanetCrawlerTask build() {
return new PlanetCrawlerTask(planetCrawler, planetRepository);
}
}
|
<reponame>rchaser53/fontIconPlayground
import * as fs from 'graceful-fs'
export interface Options {
encoding: string | null,
flag?: string
}
export const readFile = <T>(fileName: string, options: Options = {
encoding: 'utf8'
}): Promise<T> => {
return new Promise<T>((resolve, reject) => {
fs.readFile(fileName, options, (err, data: any) => {
if (err) reject(err)
resolve(data)
})
})
}
export const writeFile = <T>(fileName: string, data: any): Promise<T> => {
return new Promise((resolve, reject) => {
fs.writeFile(fileName, data, { encoding: 'utf8'}, (err) => {
if (err) reject(err)
resolve(data)
})
})
} |
#!/bin/sh
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# use filter instead of exclude so missing patterns dont' throw errors
echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
echo "/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements \"$1\""
/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements "$1"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "$BUILT_PRODUCTS_DIR/SwiftyOnboard/SwiftyOnboard.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "$BUILT_PRODUCTS_DIR/SwiftyOnboard/SwiftyOnboard.framework"
fi
|
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
menu_value_prompt() {
local SET_VAR=${1:-}
local CURRENT_VAL
CURRENT_VAL=$(run_script 'env_get' "${SET_VAR}")
local APPNAME=${SET_VAR%%_*}
local FILENAME=${APPNAME,,}
local VAR_LABEL=${SET_VAR,,}
local DEFAULT_VAL
if grep -q -Po "^${SET_VAR}=\K.*" "${SCRIPTPATH}/compose/.env.example"; then
DEFAULT_VAL=$(grep --color=never -Po "^${SET_VAR}=\K.*" "${SCRIPTPATH}/compose/.env.example" || true)
else
DEFAULT_VAL=$(grep --color=never -Po "\scom\.dockstarter\.appvars\.${VAR_LABEL}: \K.*" "${SCRIPTPATH}/compose/.apps/${FILENAME}/${FILENAME}.labels.yml" | sed -E 's/^([^"].*[^"])$/"\1"/' | xargs || true)
fi
local HOME_VAL
local SYSTEM_VAL
local VALUEDESCRIPTION
local VALUEOPTIONS=()
VALUEOPTIONS+=("Keep Current " "${CURRENT_VAL}")
case "${SET_VAR}" in
DOCKERCONFDIR)
HOME_VAL="${DETECTED_HOMEDIR}/.config/appdata"
VALUEOPTIONS+=("Use Home " "${HOME_VAL}")
;;
DOCKERGID)
SYSTEM_VAL=$(cut -d: -f3 < <(getent group docker))
VALUEOPTIONS+=("Use System " "${SYSTEM_VAL}")
;;
DOCKERHOSTNAME)
SYSTEM_VAL=${HOSTNAME}
VALUEOPTIONS+=("Use System " "${SYSTEM_VAL}")
;;
DOCKERSTORAGEDIR)
HOME_VAL="${DETECTED_HOMEDIR}/storage"
VALUEOPTIONS+=("Use Home " "${HOME_VAL}")
;;
LAN_NETWORK)
SYSTEM_VAL=$(run_script 'detect_lan_network')
VALUEOPTIONS+=("Use System " "${SYSTEM_VAL}")
;;
PGID)
SYSTEM_VAL=${DETECTED_PGID}
VALUEOPTIONS+=("Use System " "${SYSTEM_VAL}")
;;
PUID)
SYSTEM_VAL=${DETECTED_PUID}
VALUEOPTIONS+=("Use System " "${SYSTEM_VAL}")
;;
TZ)
SYSTEM_VAL=$(cat /etc/timezone)
VALUEOPTIONS+=("Use System " "${SYSTEM_VAL}")
;;
*)
VALUEOPTIONS+=("Use Default " "${DEFAULT_VAL}")
;;
esac
VALUEOPTIONS+=("Enter New " "")
case "${SET_VAR}" in
*_ENABLED)
VALUEDESCRIPTION='\n\n Must be true or false.'
;;
*_NETWORK_MODE)
VALUEDESCRIPTION='\n\n Network Mode is usually left blank but can also be bridge, host, none, service: <APPNAME>, or container: <APPNAME>.'
;;
*_PORT_*)
VALUEDESCRIPTION='\n\n Must be an unused port between 0 and 65535.'
;;
*_RESTART)
VALUEDESCRIPTION='\n\n Restart is usually unless-stopped but can also be no, always, or on-failure.'
;;
*DIR | *DIR_*)
VALUEDESCRIPTION='\n\n If the directory selected does not exist we will attempt to create it.'
;;
LAN_NETWORK)
VALUEDESCRIPTION='\n\n This is used to define your home LAN network, do NOT confuse this with the IP address of your router or your server, the value for this key defines your network NOT a single host. Please Google CIDR Notation to learn more.'
;;
PGID)
VALUEDESCRIPTION='\n\n This should be your user group ID. If you are unsure, select Use System.'
;;
PUID)
VALUEDESCRIPTION='\n\n This should be your user account ID. If you are unsure, select Use System.'
;;
TZ)
VALUEDESCRIPTION='\n\n If this is not the correct timezone please exit and set your system timezone.'
;;
VPN_ENABLE)
VALUEDESCRIPTION='\n\n Must be yes or no.'
;;
VPN_OPTIONS)
VALUEDESCRIPTION='\n\n Additional openvpn cli options.'
;;
VPN_PROV)
VALUEDESCRIPTION='\n\n VPN Provider, usually pia, airvpn or custom.'
;;
*)
VALUEDESCRIPTION=""
;;
esac
if [[ -n ${SYSTEM_VAL:-} ]]; then
VALUEDESCRIPTION="\n\n System detected values are recommended.${VALUEDESCRIPTION}"
fi
local SELECTEDVALUE
if [[ ${CI:-} == true ]]; then
SELECTEDVALUE="Keep Current "
else
SELECTEDVALUE=$(whiptail --fb --clear --title "DockSTARTer" --menu "What would you like set for ${SET_VAR}?${VALUEDESCRIPTION}" 0 0 0 "${VALUEOPTIONS[@]}" 3>&1 1>&2 2>&3 || echo "Cancel")
fi
local INPUT
case "${SELECTEDVALUE}" in
"Keep Current ")
INPUT=${CURRENT_VAL}
;;
"Use Home ")
INPUT=${HOME_VAL}
;;
"Use Default ")
INPUT=${DEFAULT_VAL}
;;
"Use System ")
INPUT=${SYSTEM_VAL}
;;
"Enter New ")
INPUT=$(whiptail --fb --clear --title "DockSTARTer" --inputbox "What would you like set for ${SET_VAR}?${VALUEDESCRIPTION}" 0 0 "${CURRENT_VAL}" 3>&1 1>&2 2>&3 || echo "CancelNewEntry")
;;
"Cancel")
warn "Selection of ${SET_VAR} was canceled."
return 1
;;
*)
fatal "Invalid Option."
;;
esac
if [[ ${INPUT} == "CancelNewEntry" ]]; then
menu_value_prompt "${SET_VAR}"
else
case "${SET_VAR}" in
*_ENABLED)
if [[ ${INPUT} == true ]] || [[ ${INPUT} == false ]]; then
run_script 'env_set' "${SET_VAR}" "${INPUT}"
else
whiptail --fb --clear --title "DockSTARTer" --msgbox "${INPUT} is not true or false. Please try setting ${SET_VAR} again." 0 0
menu_value_prompt "${SET_VAR}"
fi
;;
*_NETWORK_MODE)
case "${INPUT}" in
"" | "bridge" | "host" | "none" | "service:"* | "container:"*)
run_script 'env_set' "${SET_VAR}" "${INPUT}"
;;
*)
whiptail --fb --clear --title "DockSTARTer" --msgbox "${INPUT} is not a valid network mode. Please try setting ${SET_VAR} again." 0 0
menu_value_prompt "${SET_VAR}"
;;
esac
;;
*_PORT_*)
if [[ ${INPUT} =~ ^[0-9]+$ ]] || [[ ${INPUT} -ge 0 ]] || [[ ${INPUT} -le 65535 ]]; then
run_script 'env_set' "${SET_VAR}" "${INPUT}"
else
whiptail --fb --clear --title "DockSTARTer" --msgbox "${INPUT} is not a valid port. Please try setting ${SET_VAR} again." 0 0
menu_value_prompt "${SET_VAR}"
fi
;;
*_RESTART)
case "${INPUT}" in
"no" | "always" | "on-failure" | "unless-stopped")
run_script 'env_set' "${SET_VAR}" "${INPUT}"
;;
*)
whiptail --fb --clear --title "DockSTARTer" --msgbox "${INPUT} is not a valid restart value. Please try setting ${SET_VAR} again." 0 0
menu_value_prompt "${SET_VAR}"
;;
esac
;;
*DIR | *DIR_*)
if [[ ${INPUT} == "/" ]]; then
whiptail --fb --clear --title "DockSTARTer" --msgbox "Cannot use / for ${SET_VAR}. Please select another folder." 0 0
menu_value_prompt "${SET_VAR}"
elif [[ ${INPUT} == ~* ]]; then
local CORRECTED_DIR="${DETECTED_HOMEDIR}${INPUT#*~}"
if run_script 'question_prompt' "${PROMPT:-}" Y "Cannot use the ~ shortcut in ${SET_VAR}. Would you like to use ${CORRECTED_DIR} instead?"; then
run_script 'env_set' "${SET_VAR}" "${CORRECTED_DIR}"
whiptail --fb --clear --title "DockSTARTer" --msgbox "Returning to the previous menu to confirm selection." 0 0
else
whiptail --fb --clear --title "DockSTARTer" --msgbox "Cannot use the ~ shortcut in ${SET_VAR}. Please select another folder." 0 0
fi
menu_value_prompt "${SET_VAR}"
elif [[ -d ${INPUT} ]]; then
run_script 'env_set' "${SET_VAR}" "${INPUT}"
if run_script 'question_prompt' "${PROMPT:-}" Y "Would you like to set permissions on ${INPUT} ?"; then
run_script 'set_permissions' "${INPUT}"
fi
else
if run_script 'question_prompt' "${PROMPT:-}" Y "${INPUT} is not a valid path. Would you like to attempt to create it?"; then
mkdir -p "${INPUT}" || fatal "Failed to make directory.\nFailing command: ${F[C]}mkdir -p \"${INPUT}\""
run_script 'set_permissions' "${INPUT}"
run_script 'env_set' "${SET_VAR}" "${INPUT}"
whiptail --fb --clear --title "DockSTARTer" --msgbox "${INPUT} folder was created successfully." 0 0
else
whiptail --fb --clear --title "DockSTARTer" --msgbox "${INPUT} is not a valid path. Please try setting ${SET_VAR} again." 0 0
menu_value_prompt "${SET_VAR}"
fi
fi
;;
P[GU]ID)
if [[ ${INPUT} == "0" ]]; then
if run_script 'question_prompt' "${PROMPT:-}" Y "Running as root is not recommended. Would you like to select a different ID?"; then
menu_value_prompt "${SET_VAR}"
else
run_script 'env_set' "${SET_VAR}" "${INPUT}"
fi
elif [[ ${INPUT} =~ ^[0-9]+$ ]]; then
run_script 'env_set' "${SET_VAR}" "${INPUT}"
else
whiptail --fb --clear --title "DockSTARTer" --msgbox "${INPUT} is not a valid ${SET_VAR}. Please try setting ${SET_VAR} again." 0 0
menu_value_prompt "${SET_VAR}"
fi
;;
*)
run_script 'env_set' "${SET_VAR}" "${INPUT}"
;;
esac
fi
}
test_menu_value_prompt() {
# run_script 'menu_value_prompt'
warn "CI does not test menu_value_prompt."
}
|
<filename>src/com/g4mesoft/net/NetworkSide.java
package com.g4mesoft.net;
public enum NetworkSide {
SERVER(0, "server"),
CLIENT(1, "client");
private int id;
private String name;
NetworkSide(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
|
<filename>src/intersection/index.ts<gh_stars>1-10
import Intersection from './Intersection';
import './index.less';
export * from './Intersection';
export default Intersection;
|
#!/bin/bash
username="admin"
pass="password"
cred="${username}:${pass}"
encoded_cred=`echo -n ${cred} | base64`
service="demo_registry"
if [ "$(uname)" == "Darwin" ]; then
docker_ip="$(docker-machine ip default)"
else
docker_ip="0.0.0.0"
fi
echo
echo "curl https://${docker_ip}:5000/v2/_catalog"
echo
curl -skv "https://${docker_ip}:5000/v2/_catalog"
read input
clear
echo
echo "curl http://${docker_ip}:8080/tokens?service=${service}&scope=registry:catalog:*"
echo
curl -sv -H "Authorization: Basic ${encoded_cred}" "http://${docker_ip}:8080/tokens?service=${service}&scope=registry:catalog:*"
token=`curl -s -H "Authorization: Basic ${encoded_cred}" "http://${docker_ip}:8080/tokens?service=${service}&scope=registry:catalog:*" | jq .token | tr -d '"'`
read input
clear
echo
echo "curl \"https://${docker_ip}:5000/v2/_catalog\""
curl -skv -H "Authorization: Bearer ${token}" "https://${docker_ip}:5000/v2/_catalog"
echo
|
<reponame>JonnyBeoulve/Marketing-Analysis-Mockup
import React, { Component } from 'react';
import { Container, Row, Col } from 'reactstrap';
import HeaderContainer from '../../../containers/HeaderContainer/HeaderContainer';
import Title from '../../../components/Layout/Title/Title';
import Footer from '../../../components/Layout/Footer/Footer';
import '../../../css/style.css';
/*======================================================================
// This is the container for Digital Marketing Campaign, which allows
// a user to act upon selected trends from the Results container.
======================================================================*/
class DigitalMarketingCampaignContainer extends Component {
/*======================================================================
// Scroll to top of page upon container being mounted.
======================================================================*/
componentDidMount() {
window.scrollTo(0, 0);
}
render () {
return (
<div className="main-container">
<HeaderContainer />
<div className="main-body">
<Container>
<Row>
<Col>
<Title currentPageTitle="DIGITAL MARKETING CREATE CAMPAIGN" />
</Col>
</Row>
<Row className="show-grid">
<Col lg="6">
<h3 className="sub-header">New Campaign</h3>
<p>Campaign Name</p>
<input className="standard-input" type="text" name="create-campaign-campaign-name" placeholder="HotelJune2018" />
<p>Trend</p>
<input className="standard-input" type="text" name="create-campaign-trend" placeholder="Hospitality" />
<p>Quantity</p>
<input className="standard-input" type="text" name="create-campaign-trend" placeholder="???" />
<p>Demographics</p>
<input className="standard-input" type="text" name="create-campaign-trend" placeholder="???" />
<p>Geographics</p>
<input className="standard-input" type="text" name="create-campaign-trend" placeholder="???" />
<p>Interest</p>
<input className="standard-input" type="text" name="create-campaign-trend" placeholder="???" />
<p>Education</p>
<input className="standard-input" type="text" name="create-campaign-trend" placeholder="???" />
<p>Employment</p>
<input className="standard-input" type="text" name="create-campaign-trend" placeholder="???" />
<p>Daily Expenditure</p>
<input className="standard-input" type="text" name="create-campaign-trend" placeholder="$500" />
<p>Content</p>
<textarea className="standard-input-long" cols="10" rows="5" name="create-campaign-trend" placeholder="Can you almost feel the Pacific Ocean breeze drift through the tree-lined beach at @FSCostaRica? That's what we call pura vida. Begin your adventure at HotelCompany.com"></textarea>
<button className="standard-button-left" onClick={ this.props.startCampaign }>Start Campaign</button>
</Col>
<Col lg="6">
</Col>
</Row>
</Container>
</div>
<Footer />
</div>
)
}
}
export default DigitalMarketingCampaignContainer; |
<reponame>huangfuhui/jpush<gh_stars>1-10
package jpush
type CidResult struct {
CidList []string `json:"cidlist"`
}
|
#ifndef _COLORER_STYLEDREGION_H_
#define _COLORER_STYLEDREGION_H_
#include "colorer/handlers/RegionDefine.h"
/**
* Contains information about region mapping into real colors.
* These mappings are stored in HRD files and processed
* by StyledHRDMapper class.
* @ingroup colorer_handlers
*/
class StyledRegion : public RegionDefine
{
public:
enum Style { RD_NONE = 0, RD_BOLD = 1, RD_ITALIC = 2, RD_UNDERLINE = 4, RD_STRIKEOUT = 8 };
/** Is foreground value assigned? */
bool isForeSet;
/** Is background value assigned? */
bool isBackSet;
/** Foreground color of region */
unsigned int fore;
/** Background color of region */
unsigned int back;
/** Bit mask of region's style (bold, italic, underline) */
unsigned int style;
/** Common constructor */
StyledRegion(bool _isForeSet, bool _isBackSet, unsigned int _fore, unsigned int _back, unsigned int _style);
/** Empty constructor */
StyledRegion();
/** Copy constructor.
Clones all values including region reference. */
StyledRegion(const StyledRegion& rd);
StyledRegion& operator=(const StyledRegion& rd);
~StyledRegion() override = default;
/** Static method, used to cast RegionDefine class into
StyledRegion class.
@throw Exception If casing is not available.
*/
static const StyledRegion* cast(const RegionDefine* rd);
/** Completes region define with it's parent values.
The values only replaced, are these, which are empty
in this region define. Style is replaced using OR operation.
*/
void assignParent(const RegionDefine* _parent) override;
void setValues(const RegionDefine* _rd) override;
[[nodiscard]] RegionDefine* clone() const override;
};
#endif
|
import { BeanStub } from "../context/beanStub";
import { PostConstruct, Bean, Autowired, PreDestroy } from "../context/context";
import { Column } from "../entities/column";
import { ColumnApi } from "../columnController/columnApi";
import { GridApi } from "../gridApi";
import { DragService, DragListenerParams } from "./dragService";
import { Environment } from "../environment";
import { RowDropZoneParams } from "../gridPanel/rowDragFeature";
import { RowNode } from "../entities/rowNode";
import { escapeString } from "../utils/string";
import { createIcon } from "../utils/icon";
import { removeFromArray } from "../utils/array";
import { find } from "../utils/generic";
import { getBodyHeight, getBodyWidth } from "../utils/browser";
import { loadTemplate, addCssClass, clearElement, addOrRemoveCssClass } from "../utils/dom";
import { isFunction } from "../utils/function";
export interface DragItem {
/**
* When dragging a row, this contains the row node being dragged
* When dragging multiple rows, this contains the row that started the drag.
*/
rowNode?: RowNode;
/** When dragging multiple rows, this contains all rows being dragged */
rowNodes?: RowNode[];
/** When dragging columns, this contains the columns being dragged */
columns?: Column[];
/** When dragging columns, this contains the visible state of the columns */
visibleState?: { [key: string]: boolean };
}
export enum DragSourceType { ToolPanel, HeaderCell, RowDrag, ChartPanel }
export interface DragSource {
/**
* The type of the drag source, used by the drop target to know where the
* drag originated from.
*/
type: DragSourceType;
/**
* Element which, when dragged, will kick off the DnD process
*/
eElement: HTMLElement;
/**
* If eElement is dragged, then the dragItem is the object that gets passed around.
*/
getDragItem: () => DragItem;
/**
* This name appears in the ghost icon when dragging.
*/
dragItemName: string | (() => string) | null;
/**
* Icon to show when not over a drop zone
*/
defaultIconName?: string;
/**
* The drop target associated with this dragSource. When dragging starts, this
* target does not get an onDragEnter event.
*/
dragSourceDropTarget?: DropTarget;
/**
* The drag source DOM Data Key, this is useful to detect if the origin grid is the same
* as the target grid.
*/
dragSourceDomDataKey?: string;
/**
* After how many pixels of dragging should the drag operation start. Default is 4.
*/
dragStartPixels?: number;
/**
* Callback for drag started
*/
onDragStarted?: () => void;
/**
* Callback for drag stopped
*/
onDragStopped?: () => void;
}
export interface DropTarget {
/** The main container that will get the drop. */
getContainer(): HTMLElement;
/** If any secondary containers. For example when moving columns in ag-Grid, we listen for drops
* in the header as well as the body (main rows and pinned rows) of the grid. */
getSecondaryContainers?(): HTMLElement[];
/** Icon to show when drag is over */
getIconName?(): string;
isInterestedIn(type: DragSourceType): boolean;
/** Callback for when drag enters */
onDragEnter?(params: DraggingEvent): void;
/** Callback for when drag leaves */
onDragLeave?(params: DraggingEvent): void;
/** Callback for when dragging */
onDragging?(params: DraggingEvent): void;
/** Callback for when drag stops */
onDragStop?(params: DraggingEvent): void;
external?: boolean;
}
export enum VerticalDirection { Up, Down }
export enum HorizontalDirection { Left, Right }
export interface DraggingEvent {
event: MouseEvent;
x: number;
y: number;
vDirection: VerticalDirection;
hDirection: HorizontalDirection;
dragSource: DragSource;
dragItem: DragItem;
fromNudge: boolean;
api: GridApi;
columnApi: ColumnApi;
dropZoneTarget: HTMLElement;
}
@Bean('dragAndDropService')
export class DragAndDropService extends BeanStub {
@Autowired('dragService') private dragService: DragService;
@Autowired('environment') private environment: Environment;
@Autowired('columnApi') private columnApi: ColumnApi;
@Autowired('gridApi') private gridApi: GridApi;
public static ICON_PINNED = 'pinned';
public static ICON_MOVE = 'move';
public static ICON_LEFT = 'left';
public static ICON_RIGHT = 'right';
public static ICON_GROUP = 'group';
public static ICON_AGGREGATE = 'aggregate';
public static ICON_PIVOT = 'pivot';
public static ICON_NOT_ALLOWED = 'notAllowed';
public static ICON_HIDE = 'hide';
public static GHOST_TEMPLATE =
`<div class="ag-dnd-ghost ag-unselectable">
<span class="ag-dnd-ghost-icon ag-shake-left-to-right"></span>
<div class="ag-dnd-ghost-label"></div>
</div>`;
private dragSourceAndParamsList: { params: DragListenerParams, dragSource: DragSource }[] = [];
private dragItem: DragItem;
private eventLastTime: MouseEvent;
private dragSource: DragSource;
private dragging: boolean;
private eGhost: HTMLElement;
private eGhostParent: HTMLElement;
private eGhostIcon: HTMLElement;
private dropTargets: DropTarget[] = [];
private lastDropTarget: DropTarget;
private ePinnedIcon: HTMLElement;
private eHideIcon: HTMLElement;
private eMoveIcon: HTMLElement;
private eLeftIcon: HTMLElement;
private eRightIcon: HTMLElement;
private eGroupIcon: HTMLElement;
private eAggregateIcon: HTMLElement;
private ePivotIcon: HTMLElement;
private eDropNotAllowedIcon: HTMLElement;
@PostConstruct
private init(): void {
this.ePinnedIcon = createIcon('columnMovePin', this.gridOptionsWrapper, null);
this.eHideIcon = createIcon('columnMoveHide', this.gridOptionsWrapper, null);
this.eMoveIcon = createIcon('columnMoveMove', this.gridOptionsWrapper, null);
this.eLeftIcon = createIcon('columnMoveLeft', this.gridOptionsWrapper, null);
this.eRightIcon = createIcon('columnMoveRight', this.gridOptionsWrapper, null);
this.eGroupIcon = createIcon('columnMoveGroup', this.gridOptionsWrapper, null);
this.eAggregateIcon = createIcon('columnMoveValue', this.gridOptionsWrapper, null);
this.ePivotIcon = createIcon('columnMovePivot', this.gridOptionsWrapper, null);
this.eDropNotAllowedIcon = createIcon('dropNotAllowed', this.gridOptionsWrapper, null);
}
public addDragSource(dragSource: DragSource, allowTouch = false): void {
const params: DragListenerParams = {
eElement: dragSource.eElement,
dragStartPixels: dragSource.dragStartPixels,
onDragStart: this.onDragStart.bind(this, dragSource),
onDragStop: this.onDragStop.bind(this),
onDragging: this.onDragging.bind(this)
};
this.dragSourceAndParamsList.push({ params: params, dragSource: dragSource });
this.dragService.addDragSource(params, allowTouch);
}
public removeDragSource(dragSource: DragSource): void {
const sourceAndParams = find(this.dragSourceAndParamsList, item => item.dragSource === dragSource);
if (sourceAndParams) {
this.dragService.removeDragSource(sourceAndParams.params);
removeFromArray(this.dragSourceAndParamsList, sourceAndParams);
}
}
@PreDestroy
private clearDragSourceParamsList(): void {
this.dragSourceAndParamsList.forEach(sourceAndParams => this.dragService.removeDragSource(sourceAndParams.params));
this.dragSourceAndParamsList.length = 0;
}
public nudge(): void {
if (this.dragging) {
this.onDragging(this.eventLastTime, true);
}
}
private onDragStart(dragSource: DragSource, mouseEvent: MouseEvent): void {
this.dragging = true;
this.dragSource = dragSource;
this.eventLastTime = mouseEvent;
this.dragItem = this.dragSource.getDragItem();
this.lastDropTarget = this.dragSource.dragSourceDropTarget;
if (this.dragSource.onDragStarted) {
this.dragSource.onDragStarted();
}
this.createGhost();
}
private onDragStop(mouseEvent: MouseEvent): void {
this.eventLastTime = null;
this.dragging = false;
if (this.dragSource.onDragStopped) {
this.dragSource.onDragStopped();
}
if (this.lastDropTarget && this.lastDropTarget.onDragStop) {
const draggingEvent = this.createDropTargetEvent(this.lastDropTarget, mouseEvent, null, null, false);
this.lastDropTarget.onDragStop(draggingEvent);
}
this.lastDropTarget = null;
this.dragItem = null;
this.removeGhost();
}
private onDragging(mouseEvent: MouseEvent, fromNudge: boolean): void {
const hDirection = this.getHorizontalDirection(mouseEvent);
const vDirection = this.getVerticalDirection(mouseEvent);
this.eventLastTime = mouseEvent;
this.positionGhost(mouseEvent);
// check if mouseEvent intersects with any of the drop targets
const validDropTargets = this.dropTargets.filter(dropTarget => this.isMouseOnDropTarget(mouseEvent, dropTarget));
const len = validDropTargets.length;
if (len === 0) { return; }
const dropTarget: DropTarget = len === 1
? validDropTargets[0]
// the current mouse position could intersect with more than 1 element
// if they are nested. In that case we need to get the most specific
// container, which is the one that does not contain any other targets.
: validDropTargets.reduce((prevTarget, currTarget) => {
if (!prevTarget) { return currTarget; }
const prevContainer = prevTarget.getContainer();
const currContainer = currTarget.getContainer();
if (prevContainer.contains(currContainer)) { return currTarget; }
return prevTarget;
});
if (dropTarget !== this.lastDropTarget) {
this.leaveLastTargetIfExists(mouseEvent, hDirection, vDirection, fromNudge);
this.enterDragTargetIfExists(dropTarget, mouseEvent, hDirection, vDirection, fromNudge);
this.lastDropTarget = dropTarget;
} else if (dropTarget && dropTarget.onDragging) {
const draggingEvent = this.createDropTargetEvent(dropTarget, mouseEvent, hDirection, vDirection, fromNudge);
dropTarget.onDragging(draggingEvent);
}
}
private enterDragTargetIfExists(dropTarget: DropTarget, mouseEvent: MouseEvent, hDirection: HorizontalDirection, vDirection: VerticalDirection, fromNudge: boolean): void {
if (!dropTarget) { return; }
if (dropTarget.onDragEnter) {
const dragEnterEvent = this.createDropTargetEvent(dropTarget, mouseEvent, hDirection, vDirection, fromNudge);
dropTarget.onDragEnter(dragEnterEvent);
}
this.setGhostIcon(dropTarget.getIconName ? dropTarget.getIconName() : null);
}
private leaveLastTargetIfExists(mouseEvent: MouseEvent, hDirection: HorizontalDirection, vDirection: VerticalDirection, fromNudge: boolean): void {
if (!this.lastDropTarget) { return; }
if (this.lastDropTarget.onDragLeave) {
const dragLeaveEvent = this.createDropTargetEvent(this.lastDropTarget, mouseEvent, hDirection, vDirection, fromNudge);
this.lastDropTarget.onDragLeave(dragLeaveEvent);
}
this.setGhostIcon(null);
}
private getAllContainersFromDropTarget(dropTarget: DropTarget): HTMLElement[] {
let containers = [dropTarget.getContainer()];
const secondaryContainers = dropTarget.getSecondaryContainers ? dropTarget.getSecondaryContainers() : null;
if (secondaryContainers) {
containers = containers.concat(secondaryContainers);
}
return containers;
}
// checks if the mouse is on the drop target. it checks eContainer and eSecondaryContainers
private isMouseOnDropTarget(mouseEvent: MouseEvent, dropTarget: DropTarget): boolean {
let mouseOverTarget = false;
this.getAllContainersFromDropTarget(dropTarget)
.filter(eContainer => eContainer) // secondary can be missing
.forEach(eContainer => {
const rect = eContainer.getBoundingClientRect();
// if element is not visible, then width and height are zero
if (rect.width === 0 || rect.height === 0) { return; }
const horizontalFit = mouseEvent.clientX >= rect.left && mouseEvent.clientX <= rect.right;
const verticalFit = mouseEvent.clientY >= rect.top && mouseEvent.clientY <= rect.bottom;
if (horizontalFit && verticalFit) {
mouseOverTarget = true;
}
});
return mouseOverTarget && dropTarget.isInterestedIn(this.dragSource.type);
}
public addDropTarget(dropTarget: DropTarget) {
this.dropTargets.push(dropTarget);
}
public removeDropTarget(dropTarget: DropTarget) {
this.dropTargets = this.dropTargets.filter(target => target.getContainer() !== dropTarget.getContainer());
}
public hasExternalDropZones(): boolean {
return this.dropTargets.some(zones => zones.external);
}
public findExternalZone(params: RowDropZoneParams): DropTarget {
const externalTargets = this.dropTargets.filter(target => target.external);
return find(externalTargets, zone => zone.getContainer() === params.getContainer());
}
public getHorizontalDirection(event: MouseEvent): HorizontalDirection {
const clientX = this.eventLastTime.clientX;
const eClientX = event.clientX;
if (clientX === eClientX) { return null; }
return clientX > eClientX ? HorizontalDirection.Left : HorizontalDirection.Right;
}
public getVerticalDirection(event: MouseEvent): VerticalDirection {
const clientY = this.eventLastTime.clientY;
const eClientY = event.clientY;
if (clientY === eClientY) { return null; }
return clientY > eClientY ? VerticalDirection.Up : VerticalDirection.Down;
}
public createDropTargetEvent(dropTarget: DropTarget, event: MouseEvent, hDirection: HorizontalDirection, vDirection: VerticalDirection, fromNudge: boolean): DraggingEvent {
// localise x and y to the target
const dropZoneTarget = dropTarget.getContainer();
const rect = dropZoneTarget.getBoundingClientRect();
const { gridApi: api, columnApi, dragItem, dragSource } = this;
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
return { event, x, y, vDirection, hDirection, dragSource, fromNudge, dragItem, api, columnApi, dropZoneTarget };
}
private positionGhost(event: MouseEvent): void {
const ghost = this.eGhost;
const ghostRect = ghost.getBoundingClientRect();
const ghostHeight = ghostRect.height;
// for some reason, without the '-2', it still overlapped by 1 or 2 pixels, which
// then brought in scrollbars to the browser. no idea why, but putting in -2 here
// works around it which is good enough for me.
const browserWidth = getBodyWidth() - 2;
const browserHeight = getBodyHeight() - 2;
let top = event.pageY - (ghostHeight / 2);
let left = event.pageX - 10;
const usrDocument = this.gridOptionsWrapper.getDocument();
const windowScrollY = window.pageYOffset || usrDocument.documentElement.scrollTop;
const windowScrollX = window.pageXOffset || usrDocument.documentElement.scrollLeft;
// check ghost is not positioned outside of the browser
if (browserWidth > 0 && ((left + ghost.clientWidth) > (browserWidth + windowScrollX))) {
left = browserWidth + windowScrollX - ghost.clientWidth;
}
if (left < 0) {
left = 0;
}
if (browserHeight > 0 && ((top + ghost.clientHeight) > (browserHeight + windowScrollY))) {
top = browserHeight + windowScrollY - ghost.clientHeight;
}
if (top < 0) {
top = 0;
}
ghost.style.left = `${left}px`;
ghost.style.top = `${top}px`;
}
private removeGhost(): void {
if (this.eGhost && this.eGhostParent) {
this.eGhostParent.removeChild(this.eGhost);
}
this.eGhost = null;
}
private createGhost(): void {
this.eGhost = loadTemplate(DragAndDropService.GHOST_TEMPLATE);
const { theme } = this.environment.getTheme();
if (theme) {
addCssClass(this.eGhost, theme);
}
this.eGhostIcon = this.eGhost.querySelector('.ag-dnd-ghost-icon') as HTMLElement;
this.setGhostIcon(null);
const eText = this.eGhost.querySelector('.ag-dnd-ghost-label') as HTMLElement;
let dragItemName = this.dragSource.dragItemName;
if (isFunction(dragItemName)) {
dragItemName = (dragItemName as () => string)();
}
eText.innerHTML = escapeString(dragItemName as string);
this.eGhost.style.height = '25px';
this.eGhost.style.top = '20px';
this.eGhost.style.left = '20px';
const usrDocument = this.gridOptionsWrapper.getDocument();
this.eGhostParent = usrDocument.querySelector('body') as HTMLElement;
if (!this.eGhostParent) {
console.warn('ag-Grid: could not find document body, it is needed for dragging columns');
} else {
this.eGhostParent.appendChild(this.eGhost);
}
}
public setGhostIcon(iconName: string, shake = false): void {
clearElement(this.eGhostIcon);
let eIcon: HTMLElement;
if (!iconName) {
iconName = this.dragSource.defaultIconName || DragAndDropService.ICON_NOT_ALLOWED;
}
switch (iconName) {
case DragAndDropService.ICON_PINNED: eIcon = this.ePinnedIcon; break;
case DragAndDropService.ICON_MOVE: eIcon = this.eMoveIcon; break;
case DragAndDropService.ICON_LEFT: eIcon = this.eLeftIcon; break;
case DragAndDropService.ICON_RIGHT: eIcon = this.eRightIcon; break;
case DragAndDropService.ICON_GROUP: eIcon = this.eGroupIcon; break;
case DragAndDropService.ICON_AGGREGATE: eIcon = this.eAggregateIcon; break;
case DragAndDropService.ICON_PIVOT: eIcon = this.ePivotIcon; break;
case DragAndDropService.ICON_NOT_ALLOWED: eIcon = this.eDropNotAllowedIcon; break;
case DragAndDropService.ICON_HIDE: eIcon = this.eHideIcon; break;
}
addOrRemoveCssClass(this.eGhostIcon, 'ag-shake-left-to-right', shake);
if (eIcon === this.eHideIcon && this.gridOptionsWrapper.isSuppressDragLeaveHidesColumns()) {
return;
}
if (eIcon) {
this.eGhostIcon.appendChild(eIcon);
}
}
}
|
CREATE TABLE jobOpenings (
id INT PRIMARY KEY AUTO_INCREMENT,
jobTitle VARCHAR(50) NOT NULL,
description TEXT NOT NULL,
datePosted DATETIME NOT NULL
);
CREATE TABLE jobApplications (
id INT PRIMARY KEY AUTO_INCREMENT,
jobOpeningId INT NOT NULL REFERENCES jobOpenings(id) ON DELETE CASCADE,
applicantId INT NOT NULL REFERENCES applicants(id) ON DELETE CASCADE,
coverLetter TEXT,
resume VARCHAR(255),
dateApplied DATETIME NOT NULL
);
CREATE TABLE applicants (
id INT PRIMARY KEY AUTO_INCREMENT,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(50) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
); |
package com.donfyy.serializabledemo.gson;
import com.google.gson.Gson;
public class GsonTest {
static class GsonBean{
public int i;
public String str;
}
public static void main(String ... args){
//TODO:
Gson gson = new Gson();
System.out.println( gson.toJson(1));
System.out.println( gson.toJson("zero"));
int[] values = {1,2,3};
System.out.println( gson.toJson(values));
//
int i = gson.fromJson("1",int.class);
System.out.println("i: " + i);
GsonBean gsonBean = new GsonBean();
gsonBean.i= 2;
gsonBean.str = "str";
String json = gson.toJson(gsonBean);
System.out.println("json: " + json);
GsonBean gsonBean1 = gson.fromJson(json,GsonBean.class);
}
}
|
#!/bin/bash -f
#*********************************************************************************************************
# Vivado (TM) v2018.3 (64-bit)
#
# Filename : udp_checksum_fifo.sh
# Simulator : Mentor Graphics Questa Advanced Simulator
# Description : Simulation script for compiling, elaborating and verifying the project source files.
# The script will automatically create the design libraries sub-directories in the run
# directory, add the library logical mappings in the simulator setup file, create default
# 'do/prj' file, execute compilation, elaboration and simulation steps.
#
# Generated by Vivado on Mon Oct 21 13:34:10 +0800 2019
# SW Build 2405991 on Thu Dec 6 23:38:27 MST 2018
#
# Copyright 1986-2018 Xilinx, Inc. All Rights Reserved.
#
# usage: udp_checksum_fifo.sh [-help]
# usage: udp_checksum_fifo.sh [-lib_map_path]
# usage: udp_checksum_fifo.sh [-noclean_files]
# usage: udp_checksum_fifo.sh [-reset_run]
#
# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the
# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the
# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch
# that points to these libraries and rerun export_simulation. For more information about this switch please
# type 'export_simulation -help' in the Tcl shell.
#
# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this
# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when
# executing this script. Please type 'udp_checksum_fifo.sh -help' for more information.
#
# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'
#
#*********************************************************************************************************
# Script info
echo -e "udp_checksum_fifo.sh - Script generated by export_simulation (Vivado v2018.3 (64-bit)-id)\n"
# Main steps
run()
{
check_args $# $1
setup $1 $2
compile
elaborate
simulate
}
# RUN_STEP: <compile>
compile()
{
# Compile design files
source compile.do 2>&1 | tee -a compile.log
}
# RUN_STEP: <elaborate>
elaborate()
{
source elaborate.do 2>&1 | tee -a elaborate.log
}
# RUN_STEP: <simulate>
simulate()
{
vsim -64 -c -do "do {simulate.do}" -l simulate.log
}
# STEP: setup
setup()
{
case $1 in
"-lib_map_path" )
if [[ ($2 == "") ]]; then
echo -e "ERROR: Simulation library directory path not specified (type \"./udp_checksum_fifo.sh -help\" for more information)\n"
exit 1
fi
copy_setup_file $2
;;
"-reset_run" )
reset_run
echo -e "INFO: Simulation run files deleted.\n"
exit 0
;;
"-noclean_files" )
# do not remove previous data
;;
* )
copy_setup_file $2
esac
create_lib_dir
# Add any setup/initialization commands here:-
# <user specific commands>
}
# Copy modelsim.ini file
copy_setup_file()
{
file="modelsim.ini"
if [[ ($1 != "") ]]; then
lib_map_path="$1"
else
lib_map_path="C:/AI/AIFPGA/sv/sv.cache/compile_simlib/questa"
fi
if [[ ($lib_map_path != "") ]]; then
src_file="$lib_map_path/$file"
cp $src_file .
fi
}
# Create design library directory
create_lib_dir()
{
lib_dir="questa_lib"
if [[ -e $lib_dir ]]; then
rm -rf $lib_dir
fi
mkdir $lib_dir
}
# Delete generated data from the previous run
reset_run()
{
files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)
for (( i=0; i<${#files_to_remove[*]}; i++ )); do
file="${files_to_remove[i]}"
if [[ -e $file ]]; then
rm -rf $file
fi
done
create_lib_dir
}
# Check command line arguments
check_args()
{
if [[ ($1 == 1 ) && ($2 != "-lib_map_path" && $2 != "-noclean_files" && $2 != "-reset_run" && $2 != "-help" && $2 != "-h") ]]; then
echo -e "ERROR: Unknown option specified '$2' (type \"./udp_checksum_fifo.sh -help\" for more information)\n"
exit 1
fi
if [[ ($2 == "-help" || $2 == "-h") ]]; then
usage
fi
}
# Script usage
usage()
{
msg="Usage: udp_checksum_fifo.sh [-help]\n\
Usage: udp_checksum_fifo.sh [-lib_map_path]\n\
Usage: udp_checksum_fifo.sh [-reset_run]\n\
Usage: udp_checksum_fifo.sh [-noclean_files]\n\n\
[-help] -- Print help information for this script\n\n\
[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\
using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\
[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\
from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\
-noclean_files switch.\n\n\
[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n"
echo -e $msg
exit 1
}
# Launch script
run $1 $2
|
<reponame>kdparkinson/pioneer-childrens-memorial
import React from "react";
import ScrollableAnchor from "react-scrollable-anchor";
import { configureAnchors } from "react-scrollable-anchor";
import Img from "gatsby-image";
import HugeText from "./HugeText";
import Fade from "react-reveal/Fade";
import ReactAudioPlayer from "react-audio-player";
configureAnchors({ scrollDuration: 750 });
const TourStop = ({ section, index }) => (
<ScrollableAnchor id={`section-${index}`}>
<section className="py-8 lg:py-24">
<HugeText
text={section.heading}
start="-20"
finish="-100"
textalign={index % 2 ? "text-right" : "text-left"}
/>
<div>
<div
className={`flex flex-wrap items-center ${
index % 2 ? "md:flex-row-reverse" : ""
}`}
>
<div className="w-full md:w-1/2 lg:w-7/12">
<Img fluid={section.image.childImageSharp.fluid} />
</div>
<div className="w-full md:w-1/2 lg:w-5/12 p-8 lg:p-12">
<Fade
left={index % 2 ? true : false}
right={index % 2 ? false : true}
distance="100px"
>
<h2 className="text-3xl lg:text-4xl mb-6">
0{index + 1}. {section.heading}
</h2>
<div
dangerouslySetInnerHTML={{
__html: section.description
}}
></div>
</Fade>
<ReactAudioPlayer src={section.audio} controls />
</div>
</div>
</div>
</section>
</ScrollableAnchor>
);
export default TourStop;
|
#!/bin/bash
while true; do
python /home/pi/projects/python/ws_lcd/ws_lcd/irq_mqtt_a.py
sleep 10
done
exit
|
<reponame>neilsh/puppeteer<gh_stars>1-10
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const CC = Components.Constructor;
ChromeUtils.import("resource://gre/modules/EventEmitter.jsm");
ChromeUtils.import("resource://gre/modules/Services.jsm");
const IOUtil = Cc["@mozilla.org/io-util;1"].getService(Ci.nsIIOUtil);
const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1",
"nsIScriptableInputStream", "init");
this.EXPORTED_SYMBOLS = ["StreamUtils"];
const BUFFER_SIZE = 0x8000;
/**
* This helper function (and its companion object) are used by bulk
* senders and receivers to read and write data in and out of other streams.
* Functions that make use of this tool are passed to callers when it is
* time to read or write bulk data. It is highly recommended to use these
* copier functions instead of the stream directly because the copier
* enforces the agreed upon length. Since bulk mode reuses an existing
* stream, the sender and receiver must write and read exactly the agreed
* upon amount of data, or else the entire transport will be left in a
* invalid state. Additionally, other methods of stream copying (such as
* NetUtil.asyncCopy) close the streams involved, which would terminate
* the debugging transport, and so it is avoided here.
*
* Overall, this *works*, but clearly the optimal solution would be
* able to just use the streams directly. If it were possible to fully
* implement nsIInputStream/nsIOutputStream in JS, wrapper streams could
* be created to enforce the length and avoid closing, and consumers could
* use familiar stream utilities like NetUtil.asyncCopy.
*
* The function takes two async streams and copies a precise number
* of bytes from one to the other. Copying begins immediately, but may
* complete at some future time depending on data size. Use the returned
* promise to know when it's complete.
*
* @param {nsIAsyncInputStream} input
* Stream to copy from.
* @param {nsIAsyncOutputStream} output
* Stream to copy to.
* @param {number} length
* Amount of data that needs to be copied.
*
* @return {Promise}
* Promise is resolved when copying completes or rejected if any
* (unexpected) errors occur.
*/
function copyStream(input, output, length) {
let copier = new StreamCopier(input, output, length);
return copier.copy();
}
/** @class */
function StreamCopier(input, output, length) {
EventEmitter.decorate(this);
this._id = StreamCopier._nextId++;
this.input = input;
// Save off the base output stream, since we know it's async as we've
// required
this.baseAsyncOutput = output;
if (IOUtil.outputStreamIsBuffered(output)) {
this.output = output;
} else {
this.output = Cc["@mozilla.org/network/buffered-output-stream;1"]
.createInstance(Ci.nsIBufferedOutputStream);
this.output.init(output, BUFFER_SIZE);
}
this._length = length;
this._amountLeft = length;
this._deferred = {
promise: new Promise((resolve, reject) => {
this._deferred.resolve = resolve;
this._deferred.reject = reject;
}),
};
this._copy = this._copy.bind(this);
this._flush = this._flush.bind(this);
this._destroy = this._destroy.bind(this);
// Copy promise's then method up to this object.
//
// Allows the copier to offer a promise interface for the simple succeed
// or fail scenarios, but also emit events (due to the EventEmitter)
// for other states, like progress.
this.then = this._deferred.promise.then.bind(this._deferred.promise);
this.then(this._destroy, this._destroy);
// Stream ready callback starts as |_copy|, but may switch to |_flush|
// at end if flushing would block the output stream.
this._streamReadyCallback = this._copy;
}
StreamCopier._nextId = 0;
StreamCopier.prototype = {
copy() {
// Dispatch to the next tick so that it's possible to attach a progress
// event listener, even for extremely fast copies (like when testing).
Services.tm.currentThread.dispatch(() => {
try {
this._copy();
} catch (e) {
this._deferred.reject(e);
}
}, 0);
return this;
},
_copy() {
let bytesAvailable = this.input.available();
let amountToCopy = Math.min(bytesAvailable, this._amountLeft);
this._debug("Trying to copy: " + amountToCopy);
let bytesCopied;
try {
bytesCopied = this.output.writeFrom(this.input, amountToCopy);
} catch (e) {
if (e.result == Cr.NS_BASE_STREAM_WOULD_BLOCK) {
this._debug("Base stream would block, will retry");
this._debug("Waiting for output stream");
this.baseAsyncOutput.asyncWait(this, 0, 0, Services.tm.currentThread);
return;
}
throw e;
}
this._amountLeft -= bytesCopied;
this._debug("Copied: " + bytesCopied +
", Left: " + this._amountLeft);
this._emitProgress();
if (this._amountLeft === 0) {
this._debug("Copy done!");
this._flush();
return;
}
this._debug("Waiting for input stream");
this.input.asyncWait(this, 0, 0, Services.tm.currentThread);
},
_emitProgress() {
this.emit("progress", {
bytesSent: this._length - this._amountLeft,
totalBytes: this._length,
});
},
_flush() {
try {
this.output.flush();
} catch (e) {
if (e.result == Cr.NS_BASE_STREAM_WOULD_BLOCK ||
e.result == Cr.NS_ERROR_FAILURE) {
this._debug("Flush would block, will retry");
this._streamReadyCallback = this._flush;
this._debug("Waiting for output stream");
this.baseAsyncOutput.asyncWait(this, 0, 0, Services.tm.currentThread);
return;
}
throw e;
}
this._deferred.resolve();
},
_destroy() {
this._destroy = null;
this._copy = null;
this._flush = null;
this.input = null;
this.output = null;
},
// nsIInputStreamCallback
onInputStreamReady() {
this._streamReadyCallback();
},
// nsIOutputStreamCallback
onOutputStreamReady() {
this._streamReadyCallback();
},
_debug() {
},
};
/**
* Read from a stream, one byte at a time, up to the next
* <var>delimiter</var> character, but stopping if we've read |count|
* without finding it. Reading also terminates early if there are less
* than <var>count</var> bytes available on the stream. In that case,
* we only read as many bytes as the stream currently has to offer.
*
* @param {nsIInputStream} stream
* Input stream to read from.
* @param {string} delimiter
* Character we're trying to find.
* @param {number} count
* Max number of characters to read while searching.
*
* @return {string}
* Collected data. If the delimiter was found, this string will
* end with it.
*/
// TODO: This implementation could be removed if bug 984651 is fixed,
// which provides a native version of the same idea.
function delimitedRead(stream, delimiter, count) {
let scriptableStream;
if (stream instanceof Ci.nsIScriptableInputStream) {
scriptableStream = stream;
} else {
scriptableStream = new ScriptableInputStream(stream);
}
let data = "";
// Don't exceed what's available on the stream
count = Math.min(count, stream.available());
if (count <= 0) {
return data;
}
let char;
while (char !== delimiter && count > 0) {
char = scriptableStream.readBytes(1);
count--;
data += char;
}
return data;
}
this.StreamUtils = {
copyStream,
delimitedRead,
};
|
# https://github.com/BBC-News/wraith#installation
curl -fsSL https://raw.github.com/bbc-news/wraith/go/install | bash
|
package de.ids_mannheim.korap.web.controller;
import static org.junit.Assert.assertEquals;
import org.apache.http.entity.ContentType;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.api.client.UniformInterfaceException;
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.constant.ResourceType;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.exceptions.StatusCodes;
import de.ids_mannheim.korap.user.User.CorpusAccess;
import de.ids_mannheim.korap.utils.JsonUtils;
public class QueryReferenceControllerTest extends SpringJerseyTest {
private String testUser = "qRefControllerTest";
private String adminUser = "admin";
private String system = "system";
private void testRetrieveQueryByName (String qName, String query,
String queryCreator, String username, ResourceType resourceType,
CorpusAccess access) throws KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~" + queryCreator).path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "pass"))
.get(ClientResponse.class);
String entity = response.getEntity(String.class);
// System.out.println(entity);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(qName, node.at("/name").asText());
assertEquals(resourceType.displayName(), node.at("/type").asText());
assertEquals(queryCreator, node.at("/createdBy").asText());
assertEquals(query, node.at("/query").asText());
assertEquals("poliqarp", node.at("/queryLanguage").asText());
assertEquals(access.name(), node.at("/requiredAccess").asText());
}
private void testUpdateQuery (String qName, String qCreator,
String username, ResourceType type)
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
String json = "{\"query\": \"Sonne\""
+ ",\"queryLanguage\": \"poliqarp\"}";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~"+qCreator).path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "pass"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.entity(json).put(ClientResponse.class);
assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
testRetrieveQueryByName(qName, "Sonne", qCreator, username, type, CorpusAccess.PUB);
}
@Test
public void testCreatePrivateQuery () throws KustvaktException {
String json = "{\"type\": \"PRIVATE\""
+ ",\"queryType\": \"QUERY\""
+ ",\"queryLanguage\": \"poliqarp\""
+ ",\"query\": \"der\"}";
String qName = "new_query";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~" + testUser).path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(testUser, "pass"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.put(ClientResponse.class, json);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
testRetrieveQueryByName(qName, "der", testUser, testUser, ResourceType.PRIVATE,
CorpusAccess.PUB);
testUpdateQuery(qName, testUser, testUser,ResourceType.PRIVATE);
testDeleteQueryByName(qName, testUser, testUser);
}
@Test
public void testCreatePublishQuery () throws KustvaktException {
String json = "{\"type\": \"PUBLISHED\""
+ ",\"queryType\": \"QUERY\""
+ ",\"queryLanguage\": \"poliqarp\""
+ ",\"query\": \"Regen\"}";
String qName = "publish_query";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~" + testUser).path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(testUser, "pass"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.put(ClientResponse.class, json);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
testRetrieveQueryByName(qName, "Regen", testUser, testUser, ResourceType.PUBLISHED,
CorpusAccess.PUB);
testDeleteQueryByName(qName, testUser, testUser);
// check if hidden group has been created
}
@Test
public void testCreateUserQueryByAdmin () throws KustvaktException {
String json = "{\"type\": \"PRIVATE\""
+ ",\"queryType\": \"QUERY\""
+ ",\"queryLanguage\": \"poliqarp\""
+ ",\"query\": \"Sommer\"}";
String qName = "marlin-query";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~marlin").path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(adminUser, "pass"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.entity(json).put(ClientResponse.class);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
testRetrieveQueryByName(qName, "Sommer", "marlin", adminUser, ResourceType.PRIVATE, CorpusAccess.PUB);
testUpdateQuery(qName, "marlin", adminUser, ResourceType.PRIVATE);
testDeleteQueryByName(qName, "marlin", adminUser);
}
@Test
public void testCreateSystemQuery () throws KustvaktException {
String json = "{\"type\": \"SYSTEM\""
+ ",\"queryType\": \"QUERY\""
+ ",\"queryLanguage\": \"poliqarp\""
+ ",\"query\": \"Sommer\"}";
String qName = "system-query";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~system").path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(adminUser, "<PASSWORD>"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.entity(json).put(ClientResponse.class);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
testRetrieveQueryByName(qName, "Sommer", system, adminUser, ResourceType.SYSTEM, CorpusAccess.PUB);
testUpdateQuery(qName, system, adminUser, ResourceType.SYSTEM);
testDeleteSystemQueryUnauthorized(qName);
testDeleteQueryByName(qName, system, adminUser);
}
@Test
public void testCreateSystemQueryUnauthorized () throws KustvaktException {
String json = "{\"type\": \"SYSTEM\""
+ ",\"queryType\": \"QUERY\""
+ ",\"queryLanguage\": \"poliqarp\""
+ ",\"query\": \"Sommer\"}";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~"+testUser).path("system-query")
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(testUser, "<PASSWORD>"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.entity(json).put(ClientResponse.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.AUTHORIZATION_FAILED,
node.at("/errors/0/0").asInt());
assertEquals("Unauthorized operation for user: " + testUser,
node.at("/errors/0/1").asText());
}
@Test
public void testCreateQueryMissingQueryType () throws KustvaktException {
String json = "{\"type\": \"PRIVATE\""
+ ",\"queryLanguage\": \"poliqarp\""
+ ",\"query\": \"Sohn\"}";
String qName = "new_query";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~" + testUser).path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(testUser, "<PASSWORD>"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.put(ClientResponse.class, json);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
testRetrieveQueryByName(qName, "Sohn", testUser, testUser, ResourceType.PRIVATE,
CorpusAccess.PUB);
testDeleteQueryByName(qName, testUser, testUser);
}
@Test
public void testCreateQueryMissingQueryLanguage () throws KustvaktException {
String json = "{\"type\": \"PRIVATE\""
+ ",\"queryType\": \"QUERY\""
+ ",\"query\": \"Sohn\"}";
String qName = "new_query";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~" + testUser).path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(testUser, "pass"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.put(ClientResponse.class, json);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
assertEquals("queryLanguage is null", node.at("/errors/0/1").asText());
assertEquals("queryLanguage", node.at("/errors/0/2").asText());
}
@Test
public void testCreateQueryMissingQuery () throws KustvaktException {
String json = "{\"type\": \"PRIVATE\""
+ ",\"queryType\": \"QUERY\""
+ ",\"queryLanguage\": \"poliqarp\"}";
String qName = "new_query";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~" + testUser).path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(testUser, "pass"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.put(ClientResponse.class, json);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
assertEquals("query is null", node.at("/errors/0/1").asText());
assertEquals("query", node.at("/errors/0/2").asText());
}
@Test
public void testCreateQueryMissingResourceType () throws KustvaktException {
String json = "{\"query\": \"Wind\""
+ ",\"queryLanguage\": \"poliqarp\"}";
String qName = "new_query";
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~" + testUser).path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(testUser, "pass"))
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.put(ClientResponse.class, json);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
assertEquals("type is null", node.at("/errors/0/1").asText());
assertEquals("type", node.at("/errors/0/2").asText());
}
private void testDeleteQueryByName (String qName, String qCreator, String username)
throws KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~" + qCreator).path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "pass"))
.delete(ClientResponse.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
@Test
public void testDeleteQueryUnauthorized () throws KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~dory").path("dory-q")
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(testUser, "pass"))
.delete(ClientResponse.class);
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
assertEquals(StatusCodes.AUTHORIZATION_FAILED,
node.at("/errors/0/0").asInt());
assertEquals("Unauthorized operation for user: " + testUser,
node.at("/errors/0/1").asText());
}
private void testDeleteSystemQueryUnauthorized (String qName) throws KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~system").path(qName)
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(testUser, "pass"))
.delete(ClientResponse.class);
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
assertEquals(StatusCodes.AUTHORIZATION_FAILED,
node.at("/errors/0/0").asInt());
assertEquals("Unauthorized operation for user: " + testUser,
node.at("/errors/0/1").asText());
}
@Test
public void testDeleteNonExistingQuery () throws KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("query")
.path("~dory").path("non-existing-query")
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue("dory", "pass"))
.delete(ClientResponse.class);
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.NO_RESOURCE_FOUND,
node.at("/errors/0/0").asInt());
assertEquals("Query dory/non-existing-query is not found.",
node.at("/errors/0/1").asText());
assertEquals("dory/non-existing-query",
node.at("/errors/0/2").asText());
}
@Test
public void testListAvailableQueryForDory () throws UniformInterfaceException,
ClientHandlerException, KustvaktException {
JsonNode node = testListAvailableQuery("dory");
assertEquals(2, node.size());
}
@Test
public void testListAvailableQueryForPearl ()
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
JsonNode node = testListAvailableQuery("pearl");
assertEquals(1, node.size());
assertEquals("system-q", node.at("/0/name").asText());
assertEquals(ResourceType.SYSTEM.displayName(),
node.at("/0/type").asText());
assertEquals("\"system\" query", node.at("/0/description").asText());
assertEquals("[]", node.at("/0/query").asText());
assertEquals(CorpusAccess.FREE.name(), node.at("/0/requiredAccess").asText());
// assertEquals("koral:token", node.at("/0/koralQuery/@type").asText());
}
private JsonNode testListAvailableQuery (String username)
throws UniformInterfaceException, ClientHandlerException,
KustvaktException {
ClientResponse response = resource().path(API_VERSION).path("query")
.header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
.createBasicAuthorizationHeaderValue(username, "pass"))
.header(HttpHeaders.X_FORWARDED_FOR, "192.168.3.11")
.get(ClientResponse.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.getEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
return node;
}
}
|
<filename>app/services/askde/AskDESkillService.java
package services.askde;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.*;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import javax.inject.Inject;
import org.apache.commons.lang3.math.NumberUtils;
import io.ebean.Ebean;
import com.amazon.speech.json.SpeechletRequestEnvelope;
import com.amazon.speech.slu.Slot;
import com.amazon.speech.slu.entityresolution.Resolution;
import com.amazon.speech.slu.entityresolution.Value;
import com.amazon.speech.slu.entityresolution.ValueWrapper;
import com.amazon.speech.speechlet.IntentRequest;
import com.amazon.speech.speechlet.LaunchRequest;
import com.amazon.speech.speechlet.Permissions;
import com.amazon.speech.speechlet.SpeechletResponse;
import com.amazon.speech.speechlet.User;
import com.fasterxml.jackson.databind.JsonNode;
import models.askde.Adjective;
import models.askde.Appender;
import models.askde.Byline;
import models.askde.OpenHouse;
import models.askde.SkillInvocation;
import com.typesafe.config.Config;
import play.Environment;
import play.Logger;
import play.inject.ApplicationLifecycle;
import play.libs.ws.WSClient;
import play.libs.ws.WSResponse;
import raven.services.BaseAlexaService;
import raven.alexa.Address;
import raven.alexa.AlexaDeviceAddressClient;
import raven.exceptions.alexa.*;
import com.amazon.speech.ui.PlainTextOutputSpeech;
import com.amazon.speech.ui.Reprompt;
import com.amazon.speech.ui.SimpleCard;
import com.amazon.speech.ui.SsmlOutputSpeech;
import com.amazon.speech.ui.AskForPermissionsConsentCard;
import com.amazon.speech.ui.Card;
import com.amazon.speech.ui.OutputSpeech;
import com.amazon.speech.speechlet.Session;
import com.amazon.speech.speechlet.Context;
import com.amazon.speech.speechlet.interfaces.system.SystemInterface;
import com.amazon.speech.speechlet.interfaces.system.SystemState;
public class AskDESkillService extends BaseAlexaService {
private ListingsService ts;
@Inject
public AskDESkillService(Environment env, Config conf, ApplicationLifecycle al, ListingsService ts, WSClient ws) {
super(env, conf, al, ws);
this.ts = ts;
this.CARD_TITLE = "Ask Douglas Elliman";
}
public SpeechletResponse getWelcomeMessage(SpeechletRequestEnvelope<LaunchRequest> requestEnvelope) {
String speechText = "Hi and welcome to <NAME>. For more information on us, visit us at Elliman.com. I've just sent you a card to your Alexa app detailing how to use the Ask Douglas Elliman Service. Thank you and see you soon";
String cardText = "To use the Ask Douglas Elliman service, simply choose one of the 3 ways to ask: Ask <NAME> when is the next open house in Chelsea OR Alexa, ask <NAME> when is the next open house in zip code 10012 OR Alexa, ask <NAME> when is the next open house near me (Zip code permissions need to be enabled in your Alexa app for the Ask Douglas Elliman skill. Enjoy!";
SimpleCard card = getSimpleCard(cardText);
PlainTextOutputSpeech speech = getPlainTextOutputSpeech(speechText);
return SpeechletResponse.newTellResponse(speech,card);
}
public SpeechletResponse invoke(SpeechletRequestEnvelope<IntentRequest> requestEnvelope) {
if(ts == null || ts.getOpenHouses()==null || requestEnvelope==null)
return errorResponse(generateErrorListingsDown());
if(requestEnvelope.getRequest().getIntent() == null)
return errorResponse(generateErrorIntentBlank());
String intent = requestEnvelope.getRequest().getIntent().getName();
SpeechletResponse responseMessage = null;
switch(intent.toLowerCase()) {
case "getnextopenhousebyzipcode":
responseMessage = intentOpenHouseByZipCode(requestEnvelope);
break;
case "getnextopenhousebyneighborhood":
responseMessage = intentOpenHouseByNeighborhood(requestEnvelope);
break;
case "getnextopenhousenearme":
responseMessage = intentOpenHouseNearMe(requestEnvelope);
break;
default:
responseMessage = errorResponse(generateErrorIntentBlank());
}
SkillInvocation si = new SkillInvocation();
si.setSkill(intent);
if(requestEnvelope.getRequest().getIntent().getSlot("ZipCode")!=null)
si.setSourceZipCode(requestEnvelope.getRequest().getIntent().getSlot("ZipCode").getValue());
Map<String,Slot> slots = requestEnvelope.getRequest().getIntent().getSlots();
StringBuffer requestData = new StringBuffer();
for(String s : slots.keySet()) {
requestData.append(slots.get(s).getName());
requestData.append(":");
requestData.append(slots.get(s).getValue());
requestData.append(" ");
}
si.setRequest(requestData.toString());
if(responseMessage.getCard() instanceof SimpleCard) {
SimpleCard card = (SimpleCard) responseMessage.getCard();
si.setResponse(card.getContent());
}else if (responseMessage.getCard() instanceof AskForPermissionsConsentCard) {
AskForPermissionsConsentCard card = (AskForPermissionsConsentCard) responseMessage.getCard();
StringBuffer permissions = new StringBuffer();
for(String s : card.getPermissions())
permissions.append(s);
permissions.append(" ");
si.setResponse("Permissions requested: " + permissions.toString());
}
SystemState systemState = getSystemState(requestEnvelope.getContext());
String deviceID = systemState.getDevice().getDeviceId();
si.setDeviceID(deviceID);
Ebean.save(si);
return responseMessage;
}
// Intents
public SpeechletResponse intentOpenHouseNearMe(SpeechletRequestEnvelope<IntentRequest> requestEnvelope) {
Session session = requestEnvelope.getSession();
if(session==null) return errorResponse("I wasn't clear on what you said, can you please try again");
User u = session.getUser();
if(u==null) return errorResponse("I wasn't clear on what you said, can you please try again");
Permissions ps = u.getPermissions();
if(ps==null) return getPermissionsResponse();
String consentToken = ps.getConsentToken();
if(consentToken==null || consentToken.isEmpty()) return getPermissionsResponse();
String postalCode = null;
try {
SystemState systemState = getSystemState(requestEnvelope.getContext());
String deviceID = systemState.getDevice().getDeviceId();
String apiEndpoint = systemState.getApiEndpoint();
AlexaDeviceAddressClient alexaDeviceAddressClient = new AlexaDeviceAddressClient(deviceID, consentToken, apiEndpoint);
Address addressObject = alexaDeviceAddressClient.getFullAddress();
if (addressObject == null)
return getAskResponse("Ask <NAME>", "Address information missing, please try again");
postalCode = addressObject.getPostalCode();
if(postalCode==null)
return getAskResponse("Ask <NAME>", "Address information missing, please try again");
} catch (UnauthorizedException e) {
Logger.error("Unauthorized exception",e);
return getPermissionsResponse();
} catch (DeviceAddressClientException e) {
Logger.error("Device Address Client failed to successfully return the address.", e);
return errorResponse("<NAME> could not locate your zip code from Amazon, please make sure your address settings in your Alexa app are set properly");
}
Map<String,String> speechText = intentOpenHouseByZipCode(postalCode);
Map<String,String> marketingText = addMarketing();
SimpleCard card = getSimpleCard(speechText.get("plainText") + marketingText.get("plainText"));
SsmlOutputSpeech speech = getSsmlOutputSpeech(speechText.get("ssmlText") + marketingText.get("ssmlText"));
return SpeechletResponse.newTellResponse(speech,card);
}
public SpeechletResponse intentOpenHouseByZipCode(SpeechletRequestEnvelope<IntentRequest> requestEnvelope) {
Slot zipCodeSlot = requestEnvelope.getRequest().getIntent().getSlot("ZipCode");
if(zipCodeSlot==null)
return errorResponse("No zip code was identified, can you please try again?");
String zipCode = zipCodeSlot.getValue();
if(zipCode==null || zipCode.isEmpty() || !NumberUtils.isCreatable(zipCode))
return errorResponse("No zip code was identified, can you please try again?");
Map<String,String> speechText = intentOpenHouseByZipCode(zipCode);
Map<String,String> marketingText = addMarketing();
SimpleCard card = getSimpleCard(speechText.get("plainText") + marketingText.get("plainText"));
SsmlOutputSpeech speech = getSsmlOutputSpeech(speechText.get("ssmlText") + marketingText.get("ssmlText"));
return SpeechletResponse.newTellResponse(speech,card);
}
public SpeechletResponse intentOpenHouseByNeighborhood(SpeechletRequestEnvelope<IntentRequest> requestEnvelope) {
Slot neighborhoodSlot = requestEnvelope.getRequest().getIntent().getSlot("Neighborhood");
if(neighborhoodSlot==null)
return errorResponse("A neighborhood was not identified, please restate the neighborhood or try an alternative neighborhood");
String neighborhood = null;
if(neighborhoodSlot.getResolutions()!=null && neighborhoodSlot.getResolutions().getResolutionAtIndex(0) !=null && neighborhoodSlot.getResolutions().getResolutionAtIndex(0).getValueWrappers().size()>0) {
Resolution r = neighborhoodSlot.getResolutions().getResolutionAtIndex(0);
ValueWrapper vw = r.getValueWrapperAtIndex(0);
if(vw==null) {
neighborhood = neighborhoodSlot.getValue();
} else {
Value v = vw.getValue();
if(v == null) {
neighborhood = neighborhoodSlot.getValue();
} else {
neighborhood = v.getName();
}
}
} else {
Logger.info("Resolution doesn't exist");
neighborhood = neighborhoodSlot.getValue();
}
if(neighborhood==null || neighborhood.isEmpty())
return errorResponse("No valid neighborhood was specified. Try giving it another shot.");
Logger.info("Neighborhood retrieved is " + neighborhood);
OpenHouse oh = ts.getRandomizedOpenHouseByNeighborhood(neighborhood);
String plainText = null;
if(oh==null) {
plainText = "There are currently no open houses in the " + neighborhood + " neigbhorhood";
SimpleCard card = getSimpleCard(plainText);
PlainTextOutputSpeech speech = getPlainTextOutputSpeech(plainText);
return SpeechletResponse.newTellResponse(speech,card);
}
plainText = "The next open house in " + neighborhood + " is at " + oh.getAddress() + " starting " + convertDateTimeToSpeech(oh.getStartDateTime()) + " until " + convertTimeToSpeech(oh.getEndDateTime()) + ". ";
String ssmlText = "The next open house in " + neighborhood + " is at <say-as interpret-as='address'>" + oh.getAddress() + "</say-as> starting " + convertDateTimeToSpeech(oh.getStartDateTime()) + " until " + convertTimeToSpeech(oh.getEndDateTime()) + ". ";
Map<String,String> propertyDescriptionText = convertPropertyDescriptionToSpeech(oh, false);
plainText += propertyDescriptionText.get("plainText");
ssmlText += propertyDescriptionText.get("ssmlText");
Map<String,String> marketingText = addMarketing();
SimpleCard card = getSimpleCard(plainText + marketingText.get("plainText"));
SsmlOutputSpeech speech = getSsmlOutputSpeech(ssmlText + marketingText.get("ssmlText"));
return SpeechletResponse.newTellResponse(speech, card);
}
private SimpleCard getSimpleCard(String speechText) {
return super.getSimpleCard(CARD_TITLE, speechText);
}
private SpeechletResponse getPermissionsResponse() {
String speechText = "Ask <NAME> does not have permission to access your zip code " +
"Please give us permission by going into your Alexa app and following the instructions on the card we just sent you. See you soon.";
return super.getPermissionCountryAndPostalCodeResponse(speechText);
}
public Map<String,String> addMarketing() {
String plainText = generateMarketing();
String ssmlText = " <break time='1s'/>" + plainText;
Map<String,String> marketingText = putIntoMap(plainText,ssmlText);
return marketingText;
}
public String generateMarketing() {
List<Appender> appenders = Appender.getAllCurrent();
List<Byline> bylines = Byline.getAllCurrent();
if(bylines.size()>0 && appenders.size()>0) {
Appender appender = appenders.get(ThreadLocalRandom.current().nextInt(0, appenders.size()));
Byline byline = bylines.get(ThreadLocalRandom.current().nextInt(0, bylines.size()));
String message = " " + appender.getMessage() + ", " + byline.getMessage() + "!";
return message;
} else
return "";
}
public String getAdjective() {
List<Adjective> adjectives = Adjective.getAllCurrent();
if(adjectives.size()>0)
return adjectives.get(ThreadLocalRandom.current().nextInt(0, adjectives.size())).getMessage();
else
return "";
}
public Map<String,String> convertPropertyDescriptionToSpeech(OpenHouse oh, boolean sayNeighborhood) {
String adjective = getAdjective();
String plainText = "This " + adjective + " ";
String ssmlText = null;
if(oh.isRental())
plainText += "rental is a ";
else
plainText += oh.getPropertyType() + " for sale is a ";
String bedrooms = null;
if(oh.getBaths().intValue()>0)
bedrooms = oh.getBeds() + " bedroom ";
else
bedrooms = " studio ";
plainText+= bedrooms + " and " + oh.getBaths() + " bathroom ";
ssmlText = plainText.toString();
if(sayNeighborhood=true)
plainText+= "located in " + oh.getNeighborhood() + " ";
else {
plainText += "located in the " + oh.getZipCode() + " zip code ";
ssmlText+= "located in the <say-as interpret-as='spell-out'>" + oh.getZipCode() + "</say-as> zip code ";
}
plainText+= " and a current ask of $" + oh.getPrice() + ".";
ssmlText+= " and a current ask of $" + oh.getPrice() + ".";
ssmlText+= " <break time='1s'/> The listing ID is <say-as interpret-as='spell-out'>" + oh.getListingID().replace("*", "") + "</say-as> and the listing agent is " + oh.getAgentName();
plainText+= " The listing ID is " + oh.getListingID().replace("*", "") + ". You can contact " + oh.getAgentName() + " via email at " + oh.getAgentEmail() + " or call them direct at " + oh.getAgentPhoneNumber();
Map<String,String> speechText = putIntoMap(plainText,ssmlText);
return speechText;
}
public Map<String,String> intentOpenHouseByZipCode (String zipCode) {
OpenHouse oh = ts.getRandomizedOpenHouseByZipCode(Integer.valueOf(zipCode));
Map<String,String> speechText = new HashMap<String,String>(2);
String plainText = null;
String ssmlText = null;
if(oh==null) {
plainText ="There are no open houses in the " + zipCode + " zip code";
ssmlText="There are no open houses in the <say-as interpret-as='spell-out'>" + zipCode + "</say-as> zip code";
} else {
ssmlText = "The next open house in <say-as interpret-as='spell-out'>" + zipCode+ "</say-as> is at <say-as interpret-as='address'>" + oh.getAddress() + "</say-as> starting " + convertDateTimeToSpeech(oh.getStartDateTime()) + " until " + convertTimeToSpeech(oh.getEndDateTime()) + ". ";
plainText = "The next open house in " + zipCode+ " is at " + oh.getAddress() + " starting " + convertDateTimeToSpeech(oh.getStartDateTime()) + " until " + convertTimeToSpeech(oh.getEndDateTime()) + ". ";
Map<String,String> propertyDescriptionText = convertPropertyDescriptionToSpeech(oh, true);
ssmlText += propertyDescriptionText.get("ssmlText");
plainText += propertyDescriptionText.get("plainText");
}
speechText = putIntoMap(plainText,ssmlText);
Logger.info("Response: " + plainText);
return speechText;
}
private SpeechletResponse errorResponse() {
return errorResponse("Looks like there's a problem with the request, please try again");
}
private SpeechletResponse errorResponse(String errorMessage) {
Logger.info("default error called");
SimpleCard card = getSimpleCard(errorMessage);
PlainTextOutputSpeech speech = getPlainTextOutputSpeech(errorMessage);
return SpeechletResponse.newTellResponse(speech,card);
}
public String generateErrorListingsDown() {
String messageIfListingsDown = conf.getString("askde.messageIfListingsDown");
Logger.info("Listings unavailable - Response is: " + messageIfListingsDown);
return messageIfListingsDown;
}
public String generateErrorIntentBlank() {
String messageIfListingsDown = conf.getString("askde.messageIfListingsDown");
Logger.info("Listings unavailable - Response is: " + messageIfListingsDown);
return messageIfListingsDown;
}
/*
public String defaultResponse() {
String responseMessage = conf.getString("askde.messageIfListingsDown");
if(responseMessage==null)
responseMessage="Hi, I couldn't get what you said, please repeat that!";
return packageResponse(addMarketing(responseMessage));
}*/
/* public String invoke(JsonNode incomingJsonRequest) {
Logger.info("Invoked");
if(ts == null || ts.getOpenHouses()==null || incomingJsonRequest==null) {
return packageResponse(generateErrorListingsDown());
}
SkillRequest sr = new SkillRequest(incomingJsonRequest);
String intent = sr.getIntent();
if(intent==null || intent.isEmpty())
return packageResponse(generateErrorIntentBlank());
Logger.info("Intent invoked: " + intent);
String responseMessage = null;
switch(sr.getIntent().toLowerCase()) {
case "getnextopenhousebyzipcode":
responseMessage = intentOpenHouseByZipCode(sr);
break;
case "getnextopenhousebyneighborhood":
sr.setIntent("GetNextOpenHouseByNeighborhood");
responseMessage = intentOpenHouseByNeighborhood(sr);
break;
case "getnextopenhousenearme":
sr.setIntent("GetNextOpenHouseNearMe");
responseMessage = intentOpenHouseNearMe(sr);
break;
default:
sr.setIntent("Default");
responseMessage = defaultResponse(); // TODO: Change to a better message
}
SkillInvocation si = new SkillInvocation();
si.setSkill(sr.getIntent());
si.setSourceZipCode(sr.getUserZipCode());
si.setRequest(sr.getJson().toString());
si.setResponse(responseMessage);
si.setDeviceID(sr.getDeviceId());
Ebean.save(si);
return responseMessage;
}*/
/* public String intentOpenHouseByZipCode(SkillRequest sr) {
String zipCode = sr.getJson().findPath("ZipCode").findPath("value").asText();
if(!NumberUtils.isCreatable(zipCode)) {
return packageResponse("The zip code was not found or came across as incomplete, please try again");
}
return packageResponse(addMarketing(intentOpenHouseByZipCode(zipCode)));
}*/
/* public String intentOpenHouseNearMe(SkillRequest sr) {
if(sr.getUserZipCode()==null || sr.getDeviceId()==null)
return "{ \"version\": \"1.0\", \"response\": { \"card\": { \"type\": \"AskForPermissionsConsent\", \"permissions\": [ \"read::alexa:device:all:country_and_postal_code\" ]}}}";
String zipCode = sr.getUserZipCode();
if(zipCode==null)
return defaultResponse();
Logger.info("Consent token: " + sr.getConsentToken());
Logger.info("Pulling up an open house listing");
return packageResponse(addMarketing(intentOpenHouseByZipCode(sr.getUserZipCode())));
}*/
/* public String intentOpenHouseByNeighborhood(SkillRequest sr) {
String neighborhood = null;
JsonNode i = sr.getJson().findPath("Neighborhood");
if(i==null)
return packageResponse(generateErrorIntentBlank());
JsonNode n = i.findPath("value");
if(n==null)
return packageResponse(generateErrorIntentBlank());
neighborhood = n.textValue();
if(neighborhood==null)
return packageResponse(generateErrorIntentBlank());
Logger.info("Neighborhood retrieved is " + neighborhood);
OpenHouse oh = ts.getRandomizedOpenHouseByNeighborhood(neighborhood);
if(oh==null)
return packageResponse ("There are no open houses in the " + neighborhood + " neigbhorhood");
String message = "The next open house in " + neighborhood + " is at <say-as interpret-as='address'>" + oh.getAddress() + "</say-as> starting " + convertDateTimeToSpeech(oh.getStartDateTime()) + " until " + convertTimeToSpeech(oh.getEndDateTime()) + ". ";
message += convertPropertyDescriptionToSpeech(oh,false);
return packageResponse(addMarketing(message));
}*/
/* public String invoke(SpeechletRequestEnvelope<IntentRequest> requestEnvelope) {
if(ts == null || ts.getOpenHouses()==null || requestEnvelope==null) {
return packageResponse(generateErrorListingsDown());
}
String intent = requestEnvelope.getRequest().getIntent().getName().toLowerCase();
String responseMessage = null;
switch(intent) {
case "getnextopenhousebyzipcode":
responseMessage = intentOpenHouseByZipCode(requestEnvelope);
break;
case "getnextopenhousebyneighborhood":
responseMessage = intentOpenHouseByNeighborhood(sr);
break;
case "getnextopenhousenearme":
responseMessage = intentOpenHouseNearMe(sr);
break;
default:
responseMessage = defaultResponse(); // TODO: Change to a better message
}
SkillInvocation si = new SkillInvocation();
si.setSkill(requestEnvelope.getRequest().getIntent().getName());
if(requestEnvelope.getRequest().getIntent().getSlot("ZipCode")!=null)
si.setSourceZipCode(requestEnvelope.getRequest().getIntent().getSlot("ZipCode").getValue());
si.setRequest(requestEnvelope.getRequest().toString());
si.setResponse(responseMessage);
si.setDeviceID("Fix this");
Ebean.save(si);
}*/
}
|
package com.it.zzb.niceweibo.util;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
public class BasePopupWindow extends PopupWindow {
private Activity mActivity;
private long mAnimatorDuration;
public BasePopupWindow(Context context, Activity activity, long animatorduration) {
super(context);
mActivity = activity;
mAnimatorDuration = animatorduration;
}
/**
* 调整窗口的透明度
*
* @param from
* @param to
*/
private void setOutBackground(float from, float to) {
final WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
ValueAnimator valueAnimator = ValueAnimator.ofFloat(from, to);
valueAnimator.setDuration(mAnimatorDuration);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
lp.alpha = (float) animation.getAnimatedValue();
mActivity.getWindow().setAttributes(lp);
}
});
valueAnimator.start();
}
@Override
public void showAtLocation(View parent, int gravity, int x, int y) {
super.showAtLocation(parent, gravity, x, y);
setOutBackground(1.0f, 0.5f);
}
@Override
public void dismiss() {
super.dismiss();
setOutBackground(0.5f, 1.0f);
}
}
|
#!/bin/bash
##############################################################################
## Copyright (c) 2018-2020, Lawrence Livermore National Security, LLC.
##
## Produced at the Lawrence Livermore National Laboratory
##
## LLNL-CODE-758885
##
## All rights reserved.
##
## This file is part of Comb.
##
## For details, see https://github.com/LLNL/Comb
## Please also see the LICENSE file for MIT license.
##############################################################################
BUILD_SUFFIX=lc_blueos_nvcc_9_2_xl_2018_09_13
rm -rf build_${BUILD_SUFFIX} 2>/dev/null
mkdir build_${BUILD_SUFFIX} && cd build_${BUILD_SUFFIX}
module load cmake/3.9.2
cmake \
-DCMAKE_BUILD_TYPE=Release \
-DENABLE_OPENMP=ON \
-DENABLE_CUDA=ON \
-DCUDA_ARCH=sm_60 \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/tce/packages/cuda/cuda-9.2.148 \
-C ../host-configs/lc-builds/blueos/nvcc_xl_2018_09_13.cmake \
-DCMAKE_INSTALL_PREFIX=../install_${BUILD_SUFFIX} \
"$@" \
..
|
def main():
a = int(input("Please enter the first number: "))
b = int(input("Please enter the second number: "))
sequence_range = int(input("Please enter the range: "))
print(a)
print(b)
count = 2 # Count initialized to 2 as the first two numbers are already printed
while count < sequence_range:
next_number = a + b
print(next_number)
a = b
b = next_number
count += 1
# Example usage
main() |
switch (renderType) {
case ERT_RENDERER_SM2:
// Existing implementation for Shader Model 2.0
break;
case ERT_RENDERER_SM3:
// New implementation for Shader Model 3.0
// Implement rendering techniques specific to Shader Model 3.0 (SM3)
break;
// Other rendering types and their respective cases
} |
#! /usr/bin/env python
# -*- coding:UTF-8 -*-
import sys
print "Welcome."
print "Please enter a string:"
sys.stdout.flush() # 必要,无缓冲
line = sys.stdin.readline().strip()
print "You entered %d characters." % len(line)
|
export EDITOR='nano'
|
#!/bin/sh
# *******************************************************************************
# * Copyright 2013, by the California Institute of Technology.
# * ALL RIGHTS RESERVED. United States Government Sponsorship
# * acknowledged.
# *
# * regulations. By accepting this document, the user agrees to comply
# * with all applicable U.S. export laws and regulations. User has the
# * responsibility to obtain export licenses,
# * or other export authority as may be required before exporting such
# * information to foreign countries or providing access to foreign
# * persons.
# *
DIRNAME="$(dirname "$0")"
"${DIRNAME}/run_tool.sh" TlmPacketEditor "$@"
|
// 11048. 이동하기
// 2020.06.25
// 다이나믹 프로그래밍
#include<iostream>
#include<algorithm>
using namespace std;
int a[1001][1001];
int d[1001][1001]; // d[i][j] : i,j로 이동했을 때 가져올 수 있는 사탕 개수
int main()
{
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> a[i][j];
}
}
d[0][0] = a[0][0];
for (int i = 1; i < m; i++)
{
d[0][i] = d[0][i - 1] + a[0][i];
}
for (int i = 1; i < n; i++)
{
d[i][0] = d[i - 1][0] + a[i][0];
}
for (int i = 1; i < n; i++)
{
for (int j = 1; j < m; j++)
{
// (i-1,j)칸, (i,j-1)칸, (i-1,j-1)칸으로 이동했을 때 최댓값과 현재 칸의 사탕개수를 더함
d[i][j] = max(max(d[i - 1][j], d[i][j - 1]), d[i - 1][j - 1]) + a[i][j];
}
}
cout << d[n - 1][m - 1] << endl;
return 0;
}
|
<filename>UIKit/include/UIKit/UIDevice.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKitDefines.h>
typedef enum {
UIDeviceOrientationUnknown,
UIDeviceOrientationPortrait,
UIDeviceOrientationPortraitUpsideDown,
UIDeviceOrientationLandscapeLeft,
UIDeviceOrientationLandscapeRight,
UIDeviceOrientationFaceUp,
UIDeviceOrientationFaceDown
} UIDeviceOrientation;
typedef enum {
UIDeviceBatteryStateUnknown,
UIDeviceBatteryStateUnplugged,
UIDeviceBatteryStateCharging,
UIDeviceBatteryStateFull,
} UIDeviceBatteryState;
#define UIDeviceOrientationIsPortrait(orientation) ((orientation) == UIDeviceOrientationPortrait || (orientation) == UIDeviceOrientationPortraitUpsideDown)
#define UIDeviceOrientationIsLandscape(orientation) ((orientation) == UIDeviceOrientationLandscapeLeft || (orientation) == UIDeviceOrientationLandscapeRight)
UIKIT_EXTERN_CLASS @interface UIDevice : NSObject {
struct {
} _uideviceFlags;
}
+ (UIDevice *)currentDevice;
- (void)beginGeneratingDeviceOrientationNotifications;
- (void)endGeneratingDeviceOrientationNotifications;
#ifdef OBJC2
@property(nonatomic,readonly,retain) NSString *name;
@property(nonatomic,readonly,retain) NSString *model;
@property(nonatomic,readonly,retain) NSString *localizedModel;
@property(nonatomic,readonly,retain) NSString *systemName;
@property(nonatomic,readonly,retain) NSString *systemVersion;
@property(nonatomic,readonly) UIDeviceOrientation orientation;
@property(nonatomic,readonly,retain) NSString *uniqueIdentifier;
@property(nonatomic,readonly,getter=isGeneratingDeviceOrientationNotifications) BOOL generatesDeviceOrientationNotifications;
@property(nonatomic,getter=isBatteryMonitoringEnabled) BOOL batteryMonitoringEnabled;
@property(nonatomic,readonly) UIDeviceBatteryState batteryState;
@property(nonatomic,readonly) float batteryLevel;
@property(nonatomic,getter=isProximityMonitoringEnabled) BOOL proximityMonitoringEnabled;
@property(nonatomic,readonly) BOOL proximityState ;
#else /* OBJC2 */
- (NSString *)name;
- (NSString *)model;
- (NSString *)localizedModel;
- (NSString *)systemName;
- (NSString *)systemVersion;
- (UIDeviceOrientation)orientation;
- (NSString *)uniqueIdentifier;
- (BOOL)generatesDeviceOrientationNotifications;
- (BOOL)isGeneratingDeviceOrientationNotifications;
- (BOOL)batteryMonitoringEnabled;
- (BOOL)isBatteryMonitoringEnabled;
- (UIDeviceBatteryState)batteryState;
- (float)batteryLevel;
- (BOOL)proximityMonitoringEnabled;
- (BOOL)proximityState;
#endif /* OBJC2 */
@end
UIKIT_EXTERN NSString *const UIDeviceOrientationDidChangeNotification;
UIKIT_EXTERN NSString *const UIDeviceBatteryStateDidChangeNotification;
UIKIT_EXTERN NSString *const UIDeviceBatteryLevelDidChangeNotification;
UIKIT_EXTERN NSString *const UIDeviceProximityStateDidChangeNotification;
|
unsigned GetCameraOwnerLayerID(const Camera& camera) {
const Entity* ownerEntity = camera.GetOwner();
if (ownerEntity) {
const Layer* parentLayer = ownerEntity->GetParentLayer();
if (parentLayer) {
return parentLayer->GetId();
}
}
// Return a default value or handle error as per the application's requirements
return 0; // Default value assuming 0 is not a valid layer ID
} |
#!/usr/bin/env bash
#
# Travis build for raspbian part 2
#
# bailout on errors and echo commands.
set -xe
DOCKER_CONTAINER_ID=$(sudo docker ps | grep $BUILD_ENV | awk '{print $1}')
echo $TRAVIS_BRANCH
echo $OCPN_TARGET
docker exec -ti $DOCKER_CONTAINER_ID /bin/bash -xec \
"export TRAVIS=$TRAVIS; export TRAVIS_REPO_SLUG=$TRAVIS_REPO_SLUG; export TRAVIS_BRANCH=$TRAVIS_BRANCH; export TRAVIS_TAG=$TRAVIS_TAG; export OCPN_TARGET=$OCPN_TARGET; export BUILD_FLAGS=$BUILD_FLAGS; rm -rf ci-source/build; mkdir ci-source/build; cd ci-source/build; cmake ..; make $BUILD_FLAGS; make package; chmod -R a+rw ../build;"
echo "Stopping"
docker ps -a
docker stop $DOCKER_CONTAINER_ID
docker rm -v $DOCKER_CONTAINER_ID
|
#!/bin/bash
remake -XD run diagnose_orog_mask.py plot_direct_precip_partition.py direct_precip_partition.py plot_dem.py plot_raw_data.py plot_diag_precip_mask.py
|
<gh_stars>0
package ru.job4j.accidents;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* @author Sir-Hedgehog (mailto:<EMAIL>)
* @version 6.0
* @since 17.06.2020
*/
@SpringBootApplication
public class AccidentsApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AccidentsApplication.class);
}
/**
* Метод запуска программы
*/
public static void main(String[] args) {
SpringApplication.run(AccidentsApplication.class, args);
}
}
|
<filename>packages/react-core/src/components/Tooltip/__tests__/Tooltip.test.tsx
import * as React from 'react';
import { render } from '@testing-library/react';
import { Tooltip } from '../Tooltip';
test('tooltip renders', () => {
const { asFragment } = render(
<Tooltip
position="top"
content={
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam id feugiat augue, nec fringilla turpis.
</div>
}
>
<div>Toggle tooltip</div>
</Tooltip>
);
expect(asFragment()).toMatchSnapshot();
});
|
import { deleteAllBills } from '../../utils/bills-utils';
describe('bill creation', () => {
beforeEach(() => {
cy.visit('http://localhost:3000');
});
it('displays bill creation fields', () => {
cy.get('.account-form').should('exist');
cy.get('.account-form .fields').should('exist');
cy.get('.account-form div:nth-child(1) div:nth-child(1) label').should(
'contain.text',
'Name'
);
cy.get('.account-form div:nth-child(1) div:nth-child(2) label').should(
'contain.text',
'Group'
);
cy.get('.account-form div:nth-child(3) button').should(
'contain.text',
'Save Account'
);
});
it('can create new account with default options', () => {
cy.get('.account-widget').should('not.exist');
const newAccName = 'My new account with default options';
cy.get('.account-form input[placeholder="Account name"]').type(newAccName);
cy.get('button')
.contains('Save Account')
.click();
cy.get('button')
.contains('Finish')
.click();
cy.get('.account-widget').should('exist');
cy.get('.account-widget-account__name a').should(
'contain.text',
newAccName
);
cy.wait(1000);
deleteAllBills();
});
it('can create new account with additional currencies', () => {
cy.get('.account-widget').should('not.exist');
const newAccName = 'My new account with additional currencies';
cy.get('.account-form input[placeholder="Account name"]').type(newAccName);
cy.get('div')
.contains('Select additional currencies')
.first()
.click();
cy.get('div')
.contains('Select additional currencies')
.parent()
.children('div')
.last()
.contains('PLN, Polish złoty')
.click();
cy.get('div')
.contains('Select additional currencies')
.first()
.parent()
.click();
cy.get('div')
.contains('Select additional currencies')
.parent()
.children('div')
.last()
.contains('EUR, Euro')
.click();
cy.get('button')
.contains('Save Account')
.click();
cy.get('.account-widget').should('exist');
cy.get('.account-widget-account__name a').should(
'contain.text',
newAccName
);
cy.get('button')
.contains('Finish')
.click();
cy.wait(1000);
deleteAllBills();
});
it('can create new account with additional currencies and balance', () => {
cy.get('.account-widget').should('not.exist');
const newAccName =
'My new account with additional currencies and non default group';
cy.get('.account-form input[placeholder="Account name"]').type(newAccName);
cy.get('div')
.contains('Select additional currencies')
.first()
.click();
cy.get('div')
.contains('Select additional currencies')
.parent()
.children('div')
.last()
.contains('PLN, Polish złoty')
.click();
cy.get('div')
.contains('Select additional currencies')
.first()
.parent()
.click();
cy.get('div')
.contains('Select additional currencies')
.parent()
.children('div')
.last()
.contains('EUR, Euro')
.click();
cy.get('div.exchange-rate-table').should('exist');
cy.get('.account-form div:nth-child(2) div:nth-child(2) input').type(
'999.99'
);
cy.get('button')
.contains('Save Account')
.click();
cy.get('.account-widget').should('exist');
cy.get('.account-widget-account__name a').should(
'contain.text',
newAccName
);
cy.get('button')
.contains('Finish')
.click();
cy.wait(1000);
deleteAllBills();
});
});
|
<reponame>brahici/WBO
from .models import Article
def article_last(request):
return {'last_article': Article.get_last_published()}
|
<gh_stars>100-1000
/*
Copyright 2013-present Barefoot Networks, 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.
*/
#include <ctype.h>
#include "bitvec.h"
#include "hex.h"
std::ostream &operator<<(std::ostream &os, const bitvec &bv) {
if (bv.size == 1) {
os << hex(bv.data);
} else {
bool first = true;
for (int i = bv.size-1; i >= 0; i--) {
if (first) {
if (!bv.ptr[i]) continue;
os << hex(bv.ptr[i]);
first = false;
} else {
os << hex(bv.ptr[i], sizeof(bv.data)*2, '0'); } }
if (first)
os << '0';
}
return os;
}
std::istream &operator>>(std::istream &is, bitvec &bv) {
char ch;
while (is && isspace((ch = is.get()))) {}
if (!is) return is;
if (!isxdigit(ch)) {
is.unget();
is.setstate(std::ios_base::failbit);
} else {
bv.clear();
do {
bv <<= 4;
if (isdigit(ch)) bv |= ch - '0';
if (islower(ch)) bv |= ch - 'a' + 10;
if (isupper(ch)) bv |= ch - 'A' + 10;
ch = is.get();
} while (is && isxdigit(ch));
if (is) is.unget(); }
return is;
}
bool operator>>(const char *s, bitvec &bv) {
bv.clear();
while (*s) {
if (!isxdigit(*s)) return false;
bv <<= 4;
if (isdigit(*s)) bv |= *s - '0';
if (islower(*s)) bv |= *s - 'a' + 10;
if (isupper(*s)) bv |= *s - 'A' + 10;
s++; }
return true;
}
bitvec &bitvec::operator>>=(size_t count) {
if (size == 1) {
if (count >= bits_per_unit)
data = 0;
else
data >>= count;
return *this; }
int off = count / bits_per_unit;
count %= bits_per_unit;
for (size_t i = 0; i < size; i++)
if (i + off < size) {
ptr[i] = ptr[i+off] >> count;
if (count && i + off + 1 < size)
ptr[i] |= ptr[i+off+1] << (bits_per_unit - count);
} else {
ptr[i] = 0; }
while (size > 1 && !ptr[size-1]) size--;
if (size == 1) {
auto tmp = ptr[0];
delete [] ptr;
data = tmp; }
return *this;
}
bitvec &bitvec::operator<<=(size_t count) {
size_t needsize = (max().index() + count + bits_per_unit)/bits_per_unit;
if (needsize > size) expand(needsize);
if (size == 1) {
data <<= count;
return *this; }
int off = count / bits_per_unit;
count %= bits_per_unit;
for (int i = size-1; i >= 0; i--)
if (i >= off) {
ptr[i] = ptr[i-off] << count;
if (count && i > off)
ptr[i] |= ptr[i-off-1] >> (bits_per_unit - count);
} else {
ptr[i] = 0; }
return *this;
}
bitvec bitvec::getslice(size_t idx, size_t sz) const {
if (sz == 0) return bitvec();
if (idx >= size * bits_per_unit) return bitvec();
if (idx + sz > size * bits_per_unit)
sz = size * bits_per_unit - idx;
if (size > 1) {
bitvec rv;
unsigned shift = idx % bits_per_unit;
idx /= bits_per_unit;
if (sz > bits_per_unit) {
rv.expand((sz-1)/bits_per_unit + 1);
for (size_t i = 0; i < rv.size; i++) {
if (shift != 0 && i != 0)
rv.ptr[i-1] |= ptr[idx + i] << (bits_per_unit - shift);
rv.ptr[i] = ptr[idx + i] >> shift; }
if ((sz %= bits_per_unit))
rv.ptr[rv.size-1] &= ~(~static_cast<uintptr_t>(1) << (sz-1));
} else {
rv.data = ptr[idx] >> shift;
if (shift != 0 && idx + 1 < size)
rv.data |= ptr[idx + 1] << (bits_per_unit - shift);
rv.data &= ~(~static_cast<uintptr_t>(1) << (sz-1)); }
return rv;
} else {
return bitvec((data >> idx) & ~(~static_cast<uintptr_t>(1) << (sz-1))); }
}
int bitvec::ffs(unsigned start) const {
uintptr_t val = ~static_cast<uintptr_t>(0);
unsigned idx = start / bits_per_unit;
val <<= (start % bits_per_unit);
while (idx < size && !(val &= word(idx))) {
++idx;
val = ~static_cast<uintptr_t>(0); }
if (idx >= size) return -1;
unsigned rv = idx * bits_per_unit;
#if defined(__GNUC__) || defined(__clang__)
rv += builtin_ctz(val);
#else
while ((val & 0xff) == 0) { rv += 8; val >>= 8; }
while ((val & 1) == 0) { rv++; val >>= 1; }
#endif
return rv;
}
unsigned bitvec::ffz(unsigned start) const {
uintptr_t val = static_cast<uintptr_t>(0);
unsigned idx = start / bits_per_unit;
val = ~(~val << (start % bits_per_unit));
while (!~(val |= word(idx))) {
++idx;
val = 0; }
unsigned rv = idx * bits_per_unit;
#if defined(__GNUC__) || defined(__clang__)
rv += builtin_ctz(~val);
#else
while ((val & 0xff) == 0xff) { rv += 8; val >>= 8; }
while (val & 1) { rv++; val >>= 1; }
#endif
return rv;
}
bool bitvec::is_contiguous() const {
// Empty bitvec is not contiguous
if (empty())
return false;
return max().index() - min().index() + 1 == popcount();
}
bitvec bitvec::rotate_right_helper(size_t start_bit, size_t rotation_idx, size_t end_bit) const {
assert(start_bit <= rotation_idx && rotation_idx < end_bit);
bitvec rot_mask(start_bit, end_bit - start_bit);
bitvec rotation_section = *this & rot_mask;
int down_shift = rotation_idx - start_bit;
int up_shift = (end_bit - start_bit) - down_shift;
bitvec rv;
rv = (rotation_section >> down_shift) | (rotation_section << up_shift);
return rv & rot_mask;
}
/**
* Designed to imitate the std::rotate/std::rotate_copy function for vectors. Return a bitvec
* which has the bit at rotation_idx appear at start_bit, and the corresponding data
* between start_bit and end_bit rotated. Similar to std::rotate/std::rotate_copy, end_bit is
* exclusive
*/
void bitvec::rotate_right(size_t start_bit, size_t rotation_idx, size_t end_bit) {
bitvec rot_section = rotate_right_helper(start_bit, rotation_idx, end_bit);
clrrange(start_bit, end_bit - start_bit);
*this |= rot_section;
}
bitvec bitvec::rotate_right_copy(size_t start_bit, size_t rotation_idx, size_t end_bit) const {
bitvec rot_section = rotate_right_helper(start_bit, rotation_idx, end_bit);
bitvec rot_mask(start_bit, end_bit - start_bit);
bitvec rv = rot_section | (*this - rot_mask);
return rv;
}
|
#!/bin/bash
##########################################################################
# This is the roxe automated install script for Linux and Mac OS.
# This file was downloaded from https://github.com/roxe/roxe
#
# Copyright (c) 2017, Respective Authors all rights reserved.
#
# After June 1, 2018 this software is available under the following terms:
#
# The MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# https://github.com/roxe/roxe/blob/master/LICENSE
##########################################################################
SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
function usage()
{
printf "\\tUsage: %s \\n\\t[Build Option -o <Debug|Release|RelWithDebInfo|MinSizeRel>] \\n\\t[CodeCoverage -c] \\n\\t[Doxygen -d] \\n\\t[CoreSymbolName -s <1-7 characters>] \\n\\t[Avoid Compiling -a]\\n\\n" "$0" 1>&2
exit 1
}
ARCH=$( uname )
if [ "${SOURCE_DIR}" == "${PWD}" ]; then
BUILD_DIR="${PWD}/build"
else
BUILD_DIR="${PWD}"
fi
CMAKE_BUILD_TYPE=Release
DISK_MIN=20
DOXYGEN=false
ENABLE_COVERAGE_TESTING=false
CORE_SYMBOL_NAME="ROC"
# Use current directory's tmp directory if noexec is enabled for /tmp
if (mount | grep "/tmp " | grep --quiet noexec); then
mkdir -p $SOURCE_DIR/tmp
TEMP_DIR="${SOURCE_DIR}/tmp"
rm -rf $SOURCE_DIR/tmp/*
else # noexec wasn't found
TEMP_DIR="/tmp"
fi
START_MAKE=true
TIME_BEGIN=$( date -u +%s )
VERSION=1.2
txtbld=$(tput bold)
bldred=${txtbld}$(tput setaf 1)
txtrst=$(tput sgr0)
if [ $# -ne 0 ]; then
while getopts ":cdo:s:ah" opt; do
case "${opt}" in
o )
options=( "Debug" "Release" "RelWithDebInfo" "MinSizeRel" )
if [[ "${options[*]}" =~ "${OPTARG}" ]]; then
CMAKE_BUILD_TYPE="${OPTARG}"
else
printf "\\n\\tInvalid argument: %s\\n" "${OPTARG}" 1>&2
usage
exit 1
fi
;;
c )
ENABLE_COVERAGE_TESTING=true
;;
d )
DOXYGEN=true
;;
s)
if [ "${#OPTARG}" -gt 7 ] || [ -z "${#OPTARG}" ]; then
printf "\\n\\tInvalid argument: %s\\n" "${OPTARG}" 1>&2
usage
exit 1
else
CORE_SYMBOL_NAME="${OPTARG}"
fi
;;
a)
START_MAKE=false
;;
h)
usage
exit 1
;;
\? )
printf "\\n\\tInvalid Option: %s\\n" "-${OPTARG}" 1>&2
usage
exit 1
;;
: )
printf "\\n\\tInvalid Option: %s requires an argument.\\n" "-${OPTARG}" 1>&2
usage
exit 1
;;
* )
usage
exit 1
;;
esac
done
fi
if [ ! -d "${SOURCE_DIR}/.git" ]; then
printf "\\n\\tThis build script only works with sources cloned from git\\n"
printf "\\tPlease clone a new roxe directory with 'git clone https://github.com/roxe/roxe --recursive'\\n"
printf "\\tSee the wiki for instructions: https://github.com/roxe/roxe/wiki\\n"
exit 1
fi
pushd "${SOURCE_DIR}" &> /dev/null
STALE_SUBMODS=$(( $(git submodule status --recursive | grep -c "^[+\-]") ))
if [ $STALE_SUBMODS -gt 0 ]; then
printf "\\n\\tgit submodules are not up to date.\\n"
printf "\\tPlease run the command 'git submodule update --init --recursive'.\\n"
exit 1
fi
printf "\\n\\tBeginning build version: %s\\n" "${VERSION}"
printf "\\t%s\\n" "$( date -u )"
printf "\\tUser: %s\\n" "$( whoami )"
printf "\\tgit head id: %s\\n" "$( cat .git/refs/heads/master )"
printf "\\tCurrent branch: %s\\n" "$( git rev-parse --abbrev-ref HEAD )"
printf "\\n\\tARCHITECTURE: %s\\n" "${ARCH}"
popd &> /dev/null
if [ "$ARCH" == "Linux" ]; then
if [ ! -e /etc/os-release ]; then
printf "\\n\\troxe currently supports Amazon, Centos, Fedora, Mint & Ubuntu Linux only.\\n"
printf "\\tPlease install on the latest version of one of these Linux distributions.\\n"
printf "\\thttps://aws.amazon.com/amazon-linux-ami/\\n"
printf "\\thttps://www.centos.org/\\n"
printf "\\thttps://start.fedoraproject.org/\\n"
printf "\\thttps://linuxmint.com/\\n"
printf "\\thttps://www.ubuntu.com/\\n"
printf "\\tExiting now.\\n"
exit 1
fi
OS_NAME=$( cat /etc/os-release | grep ^NAME | cut -d'=' -f2 | sed 's/\"//gI' )
case "$OS_NAME" in
"Amazon Linux AMI"|"Amazon Linux")
FILE="${SOURCE_DIR}/scripts/roxe_build_amazon.sh"
CXX_COMPILER=g++
C_COMPILER=gcc
MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf
export LLVM_DIR=${HOME}/opt/wasm/lib/cmake/llvm
export CMAKE=${HOME}/opt/cmake/bin/cmake
export PATH=${HOME}/opt/mongodb/bin:$PATH
;;
"CentOS Linux")
FILE="${SOURCE_DIR}/scripts/roxe_build_centos.sh"
CXX_COMPILER=g++
C_COMPILER=gcc
MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf
export LLVM_DIR=${HOME}/opt/wasm/lib/cmake/llvm
export CMAKE=${HOME}/opt/cmake/bin/cmake
export PATH=${HOME}/opt/mongodb/bin:$PATH
;;
"elementary OS")
FILE="${SOURCE_DIR}/scripts/roxe_build_ubuntu.sh"
CXX_COMPILER=clang++-4.0
C_COMPILER=clang-4.0
MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf
export PATH=${HOME}/opt/mongodb/bin:$PATH
;;
"Fedora")
FILE="${SOURCE_DIR}/scripts/roxe_build_fedora.sh"
CXX_COMPILER=g++
C_COMPILER=gcc
MONGOD_CONF=/etc/mongod.conf
export LLVM_DIR=${HOME}/opt/wasm/lib/cmake/llvm
;;
"Linux Mint")
FILE="${SOURCE_DIR}/scripts/roxe_build_ubuntu.sh"
CXX_COMPILER=clang++-4.0
C_COMPILER=clang-4.0
MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf
export PATH=${HOME}/opt/mongodb/bin:$PATH
;;
"Ubuntu")
FILE="${SOURCE_DIR}/scripts/roxe_build_ubuntu.sh"
CXX_COMPILER=clang++-4.0
C_COMPILER=clang-4.0
MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf
export PATH=${HOME}/opt/mongodb/bin:$PATH
;;
"Debian GNU/Linux")
FILE=${SOURCE_DIR}/scripts/roxe_build_ubuntu.sh
CXX_COMPILER=clang++-4.0
C_COMPILER=clang-4.0
MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf
export PATH=${HOME}/opt/mongodb/bin:$PATH
;;
*)
printf "\\n\\tUnsupported Linux Distribution. Exiting now.\\n\\n"
exit 1
esac
export BOOST_ROOT="${HOME}/opt/boost"
OPENSSL_ROOT_DIR=/usr/include/openssl
fi
if [ "$ARCH" == "Darwin" ]; then
FILE="${SOURCE_DIR}/scripts/roxe_build_darwin.sh"
CXX_COMPILER=clang++
C_COMPILER=clang
MONGOD_CONF=/usr/local/etc/mongod.conf
OPENSSL_ROOT_DIR=/usr/local/opt/openssl
fi
${SOURCE_DIR}/scripts/clean_old_install.sh
if [ $? -ne 0 ]; then
printf "\\n\\tError occurred while trying to remove old installation!\\n\\n"
exit -1
fi
. "$FILE"
printf "\\n\\n>>>>>>>> ALL dependencies sucessfully found or installed . Installing roxe\\n\\n"
printf ">>>>>>>> CMAKE_BUILD_TYPE=%s\\n" "${CMAKE_BUILD_TYPE}"
printf ">>>>>>>> ENABLE_COVERAGE_TESTING=%s\\n" "${ENABLE_COVERAGE_TESTING}"
printf ">>>>>>>> DOXYGEN=%s\\n\\n" "${DOXYGEN}"
if [ ! -d "${BUILD_DIR}" ]; then
if ! mkdir -p "${BUILD_DIR}"
then
printf "Unable to create build directory %s.\\n Exiting now.\\n" "${BUILD_DIR}"
exit 1;
fi
fi
if ! cd "${BUILD_DIR}"
then
printf "Unable to enter build directory %s.\\n Exiting now.\\n" "${BUILD_DIR}"
exit 1;
fi
if [ -z "$CMAKE" ]; then
CMAKE=$( command -v cmake )
fi
if ! "${CMAKE}" -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}" -DCMAKE_CXX_COMPILER="${CXX_COMPILER}" \
-DCMAKE_C_COMPILER="${C_COMPILER}" -DWASM_ROOT="${WASM_ROOT}" -DCORE_SYMBOL_NAME="${CORE_SYMBOL_NAME}" \
-DOPENSSL_ROOT_DIR="${OPENSSL_ROOT_DIR}" -DBUILD_MONGO_DB_PLUGIN=true \
-DENABLE_COVERAGE_TESTING="${ENABLE_COVERAGE_TESTING}" -DBUILD_DOXYGEN="${DOXYGEN}" \
-DCMAKE_INSTALL_PREFIX="/usr/local/roxe" ${LOCAL_CMAKE_FLAGS} "${SOURCE_DIR}"
then
printf "\\n\\t>>>>>>>>>>>>>>>>>>>> CMAKE building roxe has exited with the above error.\\n\\n"
exit -1
fi
if [ "${START_MAKE}" == "false" ]; then
printf "\\n\\t>>>>>>>>>>>>>>>>>>>> roxe has been successfully configured but not yet built.\\n\\n"
exit 0
fi
if [ -z ${JOBS} ]; then JOBS=$CPU_CORE; fi # Future proofing: Ensure $JOBS is set (usually set in scripts/roxe_build_*.sh scripts)
if ! make -j"${JOBS}"
then
printf "\\n\\t>>>>>>>>>>>>>>>>>>>> MAKE building roxe has exited with the above error.\\n\\n"
exit -1
fi
TIME_END=$(( $(date -u +%s) - ${TIME_BEGIN} ))
printf "\\n\\troxe has been successfully built. %02d:%02d:%02d\\n\\n" $(($TIME_END/3600)) $(($TIME_END%3600/60)) $(($TIME_END%60))
printf "\\tTo verify your installation run the following commands:\\n"
print_instructions
printf "\\tFor more information:\\n"
printf "\\troxe website: https://roxe.tech\\n"
printf "\\troxe resources: https://github.com/RoxeTech/RoxeChain\\n"
printf "\\troxe wiki: https://github.com/RoxeTech/RoxeChain/wiki\\n\\n\\n"
|
def is_palindrome(s):
s = s.lower()
return s == s[::-1] |
// Copyright (c) 2022 <NAME>. All Rights Reserved.
// https://github.com/cinar/indicatorts
import { deepStrictEqual } from 'assert';
import { roundDigitsAll } from '../../helper/numArray';
import { chandeForecastOscillator } from './chandeForecastOscillator';
describe('Chande Forecast Oscillator (CFO)', () => {
it('should be able to compute CFO', () => {
const closings = [1, 5, 12, 20];
const expected = [110, -26, -5.8333, 4.5];
const actual = chandeForecastOscillator(closings);
deepStrictEqual(roundDigitsAll(4, actual), expected);
});
});
|
<filename>Plugins/LiDAR/Source/LiDAR/Public/LidarActor.h<gh_stars>1-10
// Copyright 2018 <NAME>. All rights reserved.
#pragma once
#include "sensor_msgs/LaserScan.h"
#include "CoreMinimal.h"
#include "LidarActor.generated.h"
class AActor;
class FROSBridgeHandler;
class FROSBridgePublisher;
class SceneCaptureComponent2D;
/**
* A LidarActor simmulates a LIght Detection and Ranging device (commonly known as laser scanner) by using the
* SceneCaptureComponent2D together with the SCS_SceneDepth scene capturing source of Unreal Engine 4. After capturing
* the depth data, it is send to a ROS instance using ROS' rosbridge_suite, as well as Unreals the URosBridge plugin
*/
UCLASS()
class LIDAR_API ALidarActor : public AActor
{
GENERATED_BODY()
// --- Methods --- //
public:
/**
* Default constructor for ALidarActor
*/
ALidarActor();
/**
* Called every frame to grab the scene data and send it over to ROS
*/
virtual void Tick(float DeltaTime) override;
/*
* Called when a property is changed from the Editor to recalculate dependencies and produce debugging output
*/
void PostEditChangeProperty(FPropertyChangedEvent & PropretyChangedEvent) override;
protected:
/**
* Called when the game starts to open a connection to a rosbridge server via a rosbridge websocket
*/
virtual void BeginPlay() override;
/**
* Called when the game stops to close the connection to the rosbridge server that was opened at BeginPlay()
*/
virtual void EndPlay(const EEndPlayReason::Type Reason) override;
private:
/**
* Method helping pritning out debug messages
*/
void PrintDebugLog(FString string) const;
// --- Variables --//
public:
/**
* Flag to controll if debugging output is printed on screen
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Debugging")
bool bShowDebugLog;
/**
* The IPv4 address of the computer running the rosbridge server. Default value is 127.0.0.1
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|ROSBridge", meta = (DisplayName = "IPv4 Address"))
FString IPv4Address;
/**
* The port number that the rosbridge server is listening to. According to protocol port 0 is reserved, and the port
* part of an address has 16 bit --> 65535 as max port number. Default port for rosbridge websocket is 9090.
* @see https://en.wikipedia.org/wiki/Port_(computer_networking)
*/
UPROPERTY(EditAnywhere, Category = "LiDar|ROSBridge", meta = (ClampMin = "1", ClampMax = "65535"))
uint32 Port;
/**
* The ros topic that the actor is publishing to. Default value is "UE4LaserScan"
* @see https://wiki.ros.org/ROS/Tutorials/UnderstandingTopics
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|ROSBridge", meta = (DisplayName = "ROSTopic"))
FString ROSTopic;
/**
* The angle of the area covered by the laser scanner in degrees
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Scanning Specs",
meta = (ClampMin = "0.0", ClampMax = "360.0", DisplayName = "Scanning Angle in Degrees"))
float ScanAngleDeg;
/**
* The angle of the area covered by the laser scanner in radians
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Scanning Specs",
meta = (ClampMin = "0.0", ClampMax = "6.2831853", DisplayName = "Scanning Angle in Radians"))
float ScanAngleRad;
/**
* The angular resolution of the laser scanner in degrees
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Scanning Specs",
meta = (ClampMin = "0.0", ClampMax = "360.0", DisplayName = "Angular Resolution in Degrees"))
float AngularResInDeg;
/**
* The angular resolution of the laser scanner in radians
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Scanning Specs",
meta = (ClampMin = "0.0", ClampMax = "360.0", DisplayName = "Angular Resolution in Radians"))
float AngularResInRad;
/**
* The angular resolution of the laser scanner in steps inside the area covered by the scanner
* 360°/2^16 = 0.005° - highest precision LiDAR yields a 0.07 precision - so we should be good :)
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Scanning Specs",
meta = (ClampMin = "0.0", ClampMax = "360.0", DisplayName = "Angular Resolution in Steps inside Scanning Angle"))
uint16 AngularResStepsInside;
/**
* The angular resolution of the laser scanner in steps inside a full 360° angle (even if the scanner does not cover a
* full 360° angle
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Scanning Specs",
meta = (ClampMin = "0.0", ClampMax = "360.0", DisplayName = "AngularResolution in Steops of 360°"))
uint16 AngularResStepsOf360;
/**
* Minimum distance that an object has to be away from the sensor to get realized
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Scanning Specs",
meta = (ClampMin = "0.0", DisplayName="Minimum Distance in meter"))
float MinimumDistance;
/**
* Maximum distance that an object can be away from the sensor and still be realized
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Scanning Specs",
meta = (ClampMin = "0.0", DisplayName="Maximum Distance in meter"))
float MaximumDistance;
/**
* Maximum distance that an object can be away from the sensor and still be realized
*/
UPROPERTY(EditAnywhere, Category = "LiDAR|Scanning Specs",
meta = (ClampMin = "0.0", DisplayName="Time between Measurements in seconds"))
float TimePerScan;
private:
/**
* RosBridgeHandler
*/
TSharedPtr<FROSBridgeHandler> Handler;
/**
* ROSBridgePublisher
*/
TSharedPtr<FROSBridgePublisher> Publisher;
/**
* LaserScan message object containting the data of the scan
*/
TSharedPtr<sensor_msgs::LaserScan> ScanData;
/**
* Counts every tick as this information is needed in the message header for ROS
*/
uint32 TickCount;
/**
* Cummulated time passed between ticks
*/
float TimePassed;
// --- Constants ---//
/**
* Message type to send via ROSBridge
*/
static const FString ROSMsgType;
/**
* Constant to calculate form angles in degree to angles in radians
* Eg. 90° <=> 1.57
*/
static const float Degree2Radian;
/**
* Camara capture component for depth image
* TODO: This is accessible for debugging purposes - should be removed once finished
*/
UPROPERTY(EditAnywhere, Category = "LaserScanner|Cam")
USceneCaptureComponent2D* DepthCapture;
/*
* Buffers for reading the data from the gpu
*/
TArray<FFloat16Color> DepthImage;
/*
* Scene Capture Source resolution
*/
uint32 SCSResolution;
};
|
# Evaluates the supplied globals for each module in ModDict after calling each supplied function.
# Example usage is as follows:
###
# import Module1 as Module1
# import Module2 as Module2
# import makeFunctionAndGlobalDict as mfgd
# import evaluateGlobals as eg
# ModDict = {
# 'Module1': mfgd.makeFunctionAndGlobalDict( ['mod1Function1','mod1Function2'] , ['mod1global1','mod1global2','mod1global3'] )
# 'Module2': mfgd.makeFunctionAndGlobalDict( ['mod2Function1'] , ['mod2global1','mod2global2','mod2global3','mod2global4'] )
# }
# resultDict = eg.evaluateGlobals(ModDict,locals())
###
# Requires: Modules can't have the same name. Two globals for a given module can't have the same name.
# Functions must be able to be called on their respective module. Globals must
# be defined in their respective modules.
# Returns: Returns [resultDict], which is a dictionary whose keys are the modules that were passed
# through modDict and the values are dictionaries containing the values for the specified globals
# Note: Must pass in globals() as second argument to insure that all imports that have been done are accessible
# by the evaluateGlobals module
# Called by runTest
def testEvaluateGlobals(ModDict, oldLocs):
resultDict = dict()
for mod, funcGlobDict in ModDict.items():
# print('Mod: ' + mod)
# print('Func Glob Dict: ' + str(funcGlobDict))
# print('Globals: ' + str(globals()))
# print('Old Locs: ' + str(oldLocs))
# print(oldLocs[mod])
newMod = oldLocs[mod]
tempDict = dict()
for function in funcGlobDict['functionList']:
newStrLst = function.split('(', 1)
s = newStrLst[1][0:-1]
if len(s) == 0:
getattr(newMod, newStrLst[0])()
else:
getattr(newMod, newStrLst[0])(s)
for glob in funcGlobDict['globalList']:
tempDict[glob] = getattr(newMod,glob)
resultDict[mod] = tempDict
# print(tempDict)
# # Initializing string of execution
# stringexec = ''
#
# # Calling all functions and assigning all globals
# for function in funcGlobDict['functionList']:
# stringexec += mod + '.' + function + '\n'
# for glob in funcGlobDict['globalList']:
# stringexec += glob + '=' + mod + '.' + glob + '\n'
#
# # Initializing location
# loc = {}
#
# # Executing string of execution with current globals and storing resulting globals in loc
# exec(stringexec, oldLocs, loc)
#
# # Storing the module-variable pair [mod],[loc] into the dictionary [resultDict]
# resultDict[mod] = loc
return resultDict
def __main__():
from functionsAndGlobals import functionsAndGlobals
# TODO: Import modules to be tested
# Note: Even though it says the modules are unused, these imports are vital for runTest to work properly.
# Their information gets passed into runTest through locals()
import BSSN.BrillLindquist as BrillLindquist
import BSSN.ShiftedKerrSchild as ShiftedKerrSchild
import BSSN.StaticTrumpet as StaticTrumpet
import BSSN.UIUCBlackHole as UIUCBlackHole
# TODO: Modules that need to be imported to pre-initialize module and their function calls
# None
# TODO: Create lists of globals to calculate
CartGlobalList = ['alphaCart', 'betaCartU', 'BCartU', 'gammaCartDD', 'KCartDD']
SphGlobalList = ['alphaSph', 'betaSphU', 'BSphU', 'gammaSphDD', 'KSphDD']
# TODO: Create Module dictionary based on imported modules, functions to initialize the modules, and globals
# IMPORTANT: The name of the modules in ModDicT MUST have the same name as the imported module.
# Example: If you say 'import MyModules.Module1 as M1', then ModDict should have the entry 'M1',not 'Module1'.
ModDict = {
'BrillLindquist': functionsAndGlobals(['BrillLindquist(ComputeADMGlobalsOnly = True)'], CartGlobalList),
'ShiftedKerrSchild': functionsAndGlobals(['ShiftedKerrSchild(ComputeADMGlobalsOnly = True)'],
SphGlobalList),
'StaticTrumpet': functionsAndGlobals(['StaticTrumpet(ComputeADMGlobalsOnly = True)'], SphGlobalList),
'UIUCBlackHole': functionsAndGlobals(['UIUCBlackHole(ComputeADMGlobalsOnly = True)'], SphGlobalList)
}
resultDict = testEvaluateGlobals(ModDict, locals())
print("Original Result Dict: \n\t{'BSSN_T4UUmunu_vars': {'rho': rho, 'S': S, 'sD': [sD0, sD1, sD2], 'sDD': [[sDD00, sDD01, sDD02], [sDD01, sDD11, sDD12], [sDD02, sDD12, sDD22]]}}")
print('Result Dict: \n\t' + str(resultDict))
if __name__ == '__main__':
__main__()
|
/**
*
*/
package models;
import java.util.Date;
import javax.persistence.Entity;
import play.db.jpa.Blob;
import play.db.jpa.Model;
/**
* @author huang
*
*/
@Entity
public class DownloadFile extends Model {
/**
*
*/
public Blob fileData;
public String url;
public String fileName;
public String fileType;
public String uploadDate;
public DownloadFile(Blob fileData) {
this.fileData = fileData;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUploadDate() {
return uploadDate;
}
public void setUploadDate(String uploadDate) {
this.uploadDate = uploadDate;
}
}
|
// Copyright @ MyScript. All rights reserved.
#ifndef IInkUIRefImpl_h
#define IInkUIRefImpl_h
#import <iink/IINK.h>
#import <IInkUIReferenceImplementation/Helper.h>
#import <IInkUIReferenceImplementation/IInkUIRefImplUtils.h>
#import <IInkUIReferenceImplementation/NSAttributedString+Helper.h>
#import <IInkUIReferenceImplementation/NSFileManager+Additions.h>
#import <IInkUIReferenceImplementation/UIfont+Helper.h>
#import <IInkUIReferenceImplementation/UIFont+Traits.h>
#import <IInkUIReferenceImplementation/Canvas.h>
#import <IInkUIReferenceImplementation/FontMetricsProvider.h>
#import <IInkUIReferenceImplementation/ImageDrawer.h>
#import <IInkUIReferenceImplementation/InputView.h>
#import <IInkUIReferenceImplementation/ImageLoader.h>
#import <IInkUIReferenceImplementation/RenderView.h>
#import <IInkUIReferenceImplementation/InputView.h>
#import <IInkUIReferenceImplementation/DisplayViewController.h>
#import <IInkUIReferenceImplementation/EditorViewController.h>
#endif /* IInkUIRefImpl_h */
|
"""
source package
"""
from .computer import *
from .utils import load_data_generated
from .animation import start_animation |
<filename>examples/get-alert-list/main.go
// Copyright 2020 go-myjvn authors. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
package main
import (
"context"
"fmt"
"github.com/kazukiigeta/go-myjvn"
)
func main() {
c := myjvn.NewClient(nil)
alertList, err := c.GetAlertList(context.Background())
if err != nil {
fmt.Println(err)
}
n := len(alertList.Entries)
fmt.Println("---------------------------------------")
fmt.Println(alertList.Title)
fmt.Println("---------------------------------------")
fmt.Printf("%d alerts are found.\n\n", n)
fmt.Printf("Here is the latest one.\n\n")
fmt.Printf("%+v\n", *alertList.Entries[n-1])
fmt.Println("---------------------------------------")
}
|
<filename>2017/challenge_312_easy.cpp<gh_stars>0
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
// https://www.reddit.com/r/dailyprogrammer/comments/67dxts/20170424_challenge_312_easy_l33tspeak_translator/
// TODO : Translate from 1337 back to English
map<char, string> engToLeet = {
{'A', "4"},
{'B', "6"},
{'E', "3"},
{'I', "|"},
{'L', "1"},
{'M', "(V)"},
{'N', "(\\)"},
{'O', "0"},
{'S', "5"},
{'T', "7"},
{'V', "\\/"},
{'W', "`//"}
};
string toLeet(string in)
{
string out;
for (int i=0; i<in.size(); i++)
{
if (engToLeet.count(toupper(in[i])) > 0)
{
out += engToLeet[toupper(in[i])];
}
else
{
out += in[i];
}
}
return out;
}
int main()
{
for (string temp; getline(cin, temp); )
{
cout << temp << " -> " << toLeet(temp) << endl;
}
} |
package com.example.game2048.Game;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.example.game2048.Tool.Config;
import com.example.game2048.Music.BackgoudSound;
import com.example.game2048.R;
import com.example.game2048.Tool.Tool;
public class Card extends FrameLayout {
private TextView label;
private View background;
private boolean tag64=true;
private boolean tag512=true;
private boolean tag1024=true;
public Card(Context context) {
super(context);
LayoutParams lp = null;
background = new View(getContext());
lp = new LayoutParams(-1, -1);
lp.setMargins(20, 20, 0, 0);
background.setBackground(getResources().getDrawable(R.drawable.card_bg));
addView(background, lp);
label = new TextView(getContext());
label.setTextColor(getResources().getColor(R.color.Textcolor));
label.setTextSize(28);
label.setGravity(Gravity.CENTER);
lp = new LayoutParams(-1, -1);
lp.setMargins(20, 20, 0, 0);
addView(label, lp);
setNum(0);
}
private int num = 0;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
if (num<=0) {
label.setText("");
}else{
label.setText(num+"");
}
switch (num) {
case 0:
label.setBackgroundColor(0x00000000);
break;
case 2:
label.setBackground(getResources().getDrawable(R.drawable.bg_2));
break;
case 4:
label.setBackground(getResources().getDrawable(R.drawable.bg_4));
break;
case 8:
label.setBackground(getResources().getDrawable(R.drawable.bg_8));
break;
case 16:
label.setBackground(getResources().getDrawable(R.drawable.bg_16));
break;
case 32:
label.setBackground(getResources().getDrawable(R.drawable.bg_32));
break;
case 64:
label.setBackground(getResources().getDrawable(R.drawable.bg_64));
if(tag64&& Tool.FIRST_To_64[Config.NUM-3]){
MainActivity.getMainActivity().getAnimLayer().create64(this);
BackgoudSound.getInstance(getContext()).play(7);
tag64=false;
Tool.FIRST_To_64[Config.NUM-3]=false;
}
break;
case 128:
label.setBackground(getResources().getDrawable(R.drawable.bg_128));
break;
case 256:
label.setBackground(getResources().getDrawable(R.drawable.bg_256));
break;
case 512:
label.setBackground(getResources().getDrawable(R.drawable.bg_512));
if(tag512&& Tool.FIRSR_TO_512[Config.NUM-3]){
MainActivity.getMainActivity().getAnimLayer().paly_animation(getContext());
BackgoudSound.getInstance(getContext()).play(8);
tag512=false;
Tool.FIRSR_TO_512[Config.NUM-3]=false;
}
break;
case 1024:
label.setBackground(getResources().getDrawable(R.drawable.bg_1024));
if(tag1024&& Tool.FIRSR_TO_1024[Config.NUM-3]){
MainActivity.getMainActivity().getAnimLayer().play_animation1024();
BackgoudSound.getInstance(getContext()).play(9);
tag1024=false;
Tool.FIRSR_TO_1024[Config.NUM-3]=false;
}
break;
case 2048:
label.setBackground(getResources().getDrawable(R.drawable.bg_2048));
break;
default:
label.setBackgroundColor(0xff3c3a32);
break;
}
}
public boolean equals(Card o) {
return getNum()==o.getNum();
}
protected Card clone(){
Card c= new Card(getContext());
c.setNum(getNum());
return c;
}
public TextView getLabel() {
return label;
}
}
|
import Component from 'vue-class-component';
import VueComponentBase from '../../../VueComponentBase';
import ProduitVO from '../../../../../../shared/modules/Commerce/Produit/vos/ProduitVO';
import ModuleDAO from '../../../../../../shared/modules/DAO/ModuleDAO';
@Component({
template: require('./ProduitComponent.pug'),
components: {}
})
export default class ProduitComponent extends VueComponentBase {
private produits: ProduitVO[] = null;
private async created(): Promise<void> {
this.startLoading();
// Récupération des produits
this.produits = await ModuleDAO.getInstance().getVos<ProduitVO>(ProduitVO.API_TYPE_ID);
// Fin de chargement
this.stopLoading();
}
} |
public class PrimeNumbers {
public static void main(String[] args) {
System.out.println("The list of prime numbers from 0 to 100 is :");
for (int i = 0; i <= 100; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
/* method to check if given number is prime or not */
public static boolean isPrime(int num) {
if (num <= 1)
return false;
for (int i = 2; i < Math.sqrt(num); i++) {
if (num % i == 0)
return false;
}
return true;
}
} |
package com.honyum.elevatorMan.net;
import com.honyum.elevatorMan.net.base.RequestBean;
import org.jetbrains.annotations.NotNull;
/**
* Created by Star on 2017/7/11.
*/
public class AddWorkOrderInfoRequest extends RequestBean {
private AddWorkOrderInfoBody body;
public AddWorkOrderInfoBody getBody() {
return body;
}
public AddWorkOrderInfoRequest setBody(AddWorkOrderInfoBody body) {
this.body = body;
return this;
}
public class AddWorkOrderInfoBody {
/*"bizType":"1",
"orderName":"工单名称",
"bizId":"795927da-c224-4ae0-a293-49c560039fdb",
"communityId":"f4135d24-86ce-4150-8eea-0a071544b121",
"elevatorId":"f7b43523-093d-4d4c-bfe5-4036d345c90c",
"branchId":"ffcd9687-c142-42e3-a84b-548bd64df4da",
"contractId":"3fa7c29d-3fd6-4bf1-a16d-8e0f048f58d9",
"propertyBranchId":"8776f746-984e-4d4e-b441-eae357073e84",
"isNeedParts":1,
"partsNeedDate":"2017-12-03 09:46:44",
"expectMaintainStartDate":"2017-12-27 09:46:49",
"expectMaintainEndDate":"2018-01-02 09:46:53",
"orderContent":"维保/维修内容简述",
"bizCode":"00001(hm)",
"createUserName":"测试维修1",
"createUserTel":"13800138000"*/
private String bizType;
private String workOrderId;
public String getLiftNum() {
return liftNum;
}
public void setLiftNum(String liftNum) {
this.liftNum = liftNum;
}
public String getBaoxiuId() {
return baoxiuId;
}
public void setBaoxiuId(String baoxiuId) {
this.baoxiuId = baoxiuId;
}
private String liftNum;
private String baoxiuId;
private String orderName;
private String bizId;
private String communityId;
private String elevatorId;
private String branchId;
private String contractId;
private String propertyBranchId;
private int isNeedParts;
private String partsNeedDate;
private String expectMaintainStartDate;
private String expectMaintainEndDate;
private String orderContent;
public String getAppearance() {
return appearance;
}
public void setAppearance(String appearance) {
this.appearance = appearance;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getProcessResult() {
return processResult;
}
public void setProcessResult(String processResult) {
this.processResult = processResult;
}
public String getPreventiveMeasure() {
return preventiveMeasure;
}
public void setPreventiveMeasure(String preventiveMeasure) {
this.preventiveMeasure = preventiveMeasure;
}
private String appearance;//现象
private String reason;//原因
private String processResult;//处理结果
private String preventiveMeasure;//预防措施
private String bizCode;
private String createUserName;
private String createUserTel;
private String assistantId;
private String workId;
public void setIsNeedParts(int isNeedParts) {
this.isNeedParts = isNeedParts;
}
public int getIsNeedParts() {
return isNeedParts;
}
public void setCommunityId(String communityId) {
this.communityId = communityId;
}
public String getCommunityId() {
return communityId;
}
public void setElevatorId(String elevatorId) {
this.elevatorId = elevatorId;
}
public String getElevatorId() {
return elevatorId;
}
public void setBranchId(String branchId) {
this.branchId = branchId;
}
public String getBranchId() {
return branchId;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public String getOrderName() {
return orderName;
}
public void setBizType(String bizType) {
this.bizType = bizType;
}
public String getBizType() {
return bizType;
}
public void setContractId(String contractId) {
this.contractId = contractId;
}
public String getContractId() {
return contractId;
}
public String getBizCode() {
return bizCode;
}
public String getBizId() {
return bizId;
}
public void setBizCode(String bizCode) {
this.bizCode = bizCode;
}
public void setBizId(String bizId) {
this.bizId = bizId;
}
public void setCreateUserName(String createUserName) {
this.createUserName = createUserName;
}
public void setCreateUserTel(String createUserTel) {
this.createUserTel = createUserTel;
}
public void setExpectMaintainEndDate(String expectMaintainEndDate) {
this.expectMaintainEndDate = expectMaintainEndDate;
}
public void setExpectMaintainStartDate(String expectMaintainStartDate) {
this.expectMaintainStartDate = expectMaintainStartDate;
}
public void setPartsNeedDate(String partsNeedDate) {
this.partsNeedDate = partsNeedDate;
}
public void setPropertyBranchId(String propertyBranchId) {
this.propertyBranchId = propertyBranchId;
}
public String getCreateUserName() {
return createUserName;
}
public String getCreateUserTel() {
return createUserTel;
}
public String getExpectMaintainEndDate() {
return expectMaintainEndDate;
}
public String getExpectMaintainStartDate() {
return expectMaintainStartDate;
}
public String getPartsNeedDate() {
return partsNeedDate;
}
public String getPropertyBranchId() {
return propertyBranchId;
}
public String getAssistantId() {
return assistantId;
}
public void setAssistantId(String assistantId) {
this.assistantId = assistantId;
}
public String getWorkId() {
return workId;
}
public void setWorkId(String workId) {
this.workId = workId;
}
public String getOrderContent() {
return orderContent;
}
public void setOrderContent(String orderContent) {
this.orderContent = orderContent;
}
public String getWorkOrderId() {
return workOrderId;
}
public void setWorkOrderId(String workOrderId) {
this.workOrderId = workOrderId;
}
}
}
|
export const ANDROID_TARGET = "android";
export const IOS_TARGET = "ios";
import apps from "./apps";
export const getApp = href => {
const appRgx = /([a-zA-z]*).com/;
const match = href.match(appRgx);
if (match && match.length > 1) return match[1];
};
export const getAndroidDeepLink = href => {
const app = getApp(href);
if (Object.keys(apps).includes(app)) {
return apps[app](href, ANDROID_TARGET);
}
};
export const getIOSDeepLink = href => {
const app = getApp(href);
if (Object.keys(apps).includes(app)) {
return apps[app](href, IOS_TARGET);
}
};
/*
// Medium
"android-app://com.medium.reader/https/medium.com/p/e736460a8cd4"
""
"https://www.medium.com/"
*/
|
import React, { Component } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import './css/Navbar.css'
class Navbar extends Component {
render() {
return (
<header>
<div class="container">
<div class="nav">
<h2>ReadStop</h2>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/view">View Books</a></li>
<li><a href="#Footer">Contact Us</a></li>
</ul>
</div>
</div>
</header>
);
}
}
export default Navbar;
|
#!/usr/bin/env bash
# vim:ts=4:sts=4:sw=4:et
#
# Author: Hari Sekhon
# Date: 2020-01-07 11:57:18 +0000 (Tue, 07 Jan 2020)
#
# https://github.com/harisekhon/bash-tools
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback to help steer this or other code I publish
#
# https://www.linkedin.com/in/harisekhon
#
set -euo pipefail
[ -n "${DEBUG:-}" ] && set -x
srcdir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1090
. "$srcdir/lib/aws.sh"
# shellcheck disable=SC2034,SC2154
usage_description="
Prints password policy in 'key = value' pairs for easy viewing / grepping
See Also:
aws_iam_harden_password_policy.sh - sets a hardeded password policy along CIS Foundations Benchmark recommendations
that script calls this one before and after changing the password policy
$usage_aws_cli_required
"
# used by usage() in lib/utils.sh
# shellcheck disable=SC2034
usage_args=""
help_usage "$@"
aws iam get-account-password-policy --output json |
jq -r '.PasswordPolicy | to_entries | map(.key + " = " + (.value | tostring)) | .[]'
|
#!/usr/bin/env sh
npm run test -- $1 --watch $2 $3 |
<filename>huatuo/src/main/java/com/huatuo/util/Menu_pop_store.java
package com.huatuo.util;
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import com.huatuo.R;
import com.huatuo.interfaces.HandleSortType_Interface;
public class Menu_pop_store {
private Activity mContext;
private View showPupWindow = null; // 选择区域的view
/** 一级菜单名称数组 **/
private String[] GroupNameArray;
/** 二级菜单名称数组 **/
private String[] childNameArray;
/*
* private TextView radio_distanceNearest = null; private TextView
* radio_appraiseHigh = null; private TextView radio_orderMore = null;
*/
private LinearLayout pop_area_empty = null;
private ListView store_service_sortType_lv;
private ListView childListView = null;
private String mCurrentAreaName;
private String mCurrentAreaCode;
private AlphaAnimation animation;
public PopupWindow mPopupWindow = null;
private View mView;
private static Menu_pop_store instance;
private HandleSortType_Interface mhHandleSortType_Interface;
private int[] sortType_arr_ID = new int[] { R.string.near_fromMine, R.string.appraise_high, R.string.price_low };
private String[] sortType_arr = new String[3];
private MyAdapter adapter;
public static Menu_pop_store getInstance() {
if (instance == null) {
synchronized (Menu_pop_store.class) {
if (instance == null) {
instance = new Menu_pop_store();
}
}
}
return instance;
}
/**
* 动态添加排序类型
*/
private void addSortType() {
for (int i = 0; i < sortType_arr_ID.length; i++) {
sortType_arr[i] = mContext.getResources().getString(sortType_arr_ID[i]);
}
}
/**
* 展示区域选择的对话框
*
* @param handleInterface
*/
public void showPupupWindow(Activity context, View view, final HandleSortType_Interface handleSortType_Interface,
int type) {
mContext = context;
mView = view;
mhHandleSortType_Interface = handleSortType_Interface;
addSortType();
setPopAnimation();
CommonUtil.log("pop:============================mPopupWindow:" + mPopupWindow);
if (mPopupWindow == null) {
showPupWindow = LayoutInflater.from(mContext).inflate(R.layout.store_pop, null);
initPopuWindow(showPupWindow);
/*
* radio_distanceNearest = (TextView) showPupWindow
* .findViewById(R.id.radio_distanceNearest); radio_appraiseHigh =
* (TextView) showPupWindow .findViewById(R.id.radio_appraiseHigh);
* radio_orderMore = (TextView) showPupWindow
* .findViewById(R.id.radio_orderMore);
*/
store_service_sortType_lv = (ListView) showPupWindow.findViewById(R.id.store_service_sortType_lv);
adapter = new MyAdapter();
store_service_sortType_lv.setAdapter(adapter);
store_service_sortType_lv.setOnItemClickListener(new MyItemOnClickListener());
// pop_area_empty = (LinearLayout)
// showPupWindow.findViewById(R.id.pop_area_empty);
// pop_area_empty.setOnClickListener(new OnClickListener() {
//
// @Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// if (null != mPopupWindow) {
// mPopupWindow.dismiss();
// }
// }
// });
}
showPupWindow.setAnimation(animation);
showPupWindow.startAnimation(animation);
showPupWindow.setFocusable(true);
mPopupWindow.showAsDropDown(mView, CommonUtil.dip2px(mContext, 6.5f), CommonUtil.dip2px(mContext, 0));
// mPopupWindow.showAtLocation(mView,Gravity.TOP|Gravity.RIGHT,
// CommonUtil.dip2px(mContext, 6.5f),CommonUtil.dip2px(mContext, 110));
// mPopupWindow.showAsDropDown(mView);
// 设置activity 背景颜色变灰
// backgroundAlpha(0.7f);
mPopupWindow.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
// TODO Auto-generated method stubs
// backgroundAlpha(1f);
}
});
CommonUtil.log("默认选中的item:" + type);
adapter.setSelecttion(type);// 设置默认选中的item
}
private void setPopAnimation() {
int[] location = new int[2];
mView.getLocationOnScreen(location);// 获取控件在屏幕中的位置,方便展示Popupwindow
animation = new AlphaAnimation(0, 1);
animation.setDuration(300);
}
/**
* 初始化 PopupWindow
*
* @param view
*/
public void initPopuWindow(View view) {
/* 第一个参数弹出显示view 后两个是窗口大小 */
mPopupWindow = new PopupWindow(view, CommonUtil.dip2px(mContext, 110), LayoutParams.WRAP_CONTENT);
// /* 设置背景显示 */
// mPopupWindow.setBackgroundDrawable(mContext.getResources().getDrawable(
// R.drawable.custom_pop_bg));
/* 设置触摸外面时消失 */
mPopupWindow.setOutsideTouchable(true);
// 实例化一个ColorDrawable颜色为半透明
ColorDrawable dw = new ColorDrawable(R.color.pop_menu);
dw.setAlpha(0);
mPopupWindow.setBackgroundDrawable(dw);
// BitmapDrawable bt = new BitmapDrawable();
// bt.setAlpha(0);
// mPopupWindow.setBackgroundDrawable(bt );
mPopupWindow.update();
mPopupWindow.setTouchable(true);
/* 设置点击menu以外其他地方以及返回键退出 */
mPopupWindow.setFocusable(true);
/**
* 1.解决再次点击MENU键无反应问题 2.sub_view是PopupWindow的子View
*/
view.setFocusableInTouchMode(true);
}
/**
* 设置添加屏幕的背景透明度
*
* @param bgAlpha
*/
public void backgroundAlpha(float bgAlpha) {
// WindowManager.LayoutParams lp = mContext.getWindow().getAttributes();
WindowManager.LayoutParams lp = mContext.getWindow().getAttributes();
lp.alpha = bgAlpha; // 0.0-1.0
mContext.getWindow().setAttributes(lp);
}
class MyItemOnClickListener implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setSelecttion(position);
if (null != mhHandleSortType_Interface) {
mhHandleSortType_Interface.callBack(position, sortType_arr[position]);
}
if (null != mPopupWindow) {
CommonUtil.log("mPopupWindow.dismiss();");
mPopupWindow.dismiss();
}
}
}
class MyAdapter extends BaseAdapter {
private int index = -1;
private void setSelecttion(int position) {
index = position;
notifyDataSetChanged();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return sortType_arr.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return sortType_arr[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView sortTypeName = null;
View line;
convertView = LayoutInflater.from(mContext).inflate(R.layout.sort_type_lv_item2, null);
sortTypeName = (TextView) convertView.findViewById(R.id.tv_sortTypeName);
line = (View) convertView.findViewById(R.id.line);
sortTypeName.setText(sortType_arr[position]);
if (position == sortType_arr.length - 1) {
line.setVisibility(View.GONE);
} else {
line.setVisibility(View.VISIBLE);
}
// if (index == position) {
// sortTypeName.setBackgroundColor(mContext.getResources().getColor(R.color.pop_checked_bg));
// } else {
// sortTypeName.setBackgroundColor(mContext.getResources().getColor(R.color.white));
// }
return convertView;
}
}
}
|
// Function to check if a number is prime
function isPrime(num)
{
// 1 is not a prime
if (num <= 1)
return false;
// Since 2 is prime
if (num == 2)
return true;
// 3 is prime
if (num == 3)
return true;
// Numbers divisible by 2, 3 are not prime
if (num % 2 == 0 || num % 3 == 0)
return false;
// Check if number is divisible upto square root
for (var i = 5; i * i <= num; i = i + 6)
{
if (num % i == 0 || num % (i + 2) == 0)
return false;
}
return true;
} |
#
# from src/acker.c
#
# int A(int, int) to ack
#
ack () {
if [ "${1}" -eq "0" ]; then
printf $((${2} + 1))
exit
fi
if [ "${2}" -eq "0" ]; then
ack $((${1} - 1)) 1
fi
ack $((${1} - 1)) $(ack ${1} $((${2} - 1)))
}
|
import { Platform } from '@angular/cdk/platform';
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable, Injector } from '@angular/core';
import { NzIconService } from 'ng-zorro-antd/icon';
import { TitleService } from '@delon/theme';
import { LazyService } from '@delon/util';
import { ICONS } from '../../style-icons';
@Injectable()
export class StartupService {
constructor(
private injector: Injector,
iconSrv: NzIconService,
@Inject(DOCUMENT) private doc: any,
private lazy: LazyService,
private platform: Platform
) {
iconSrv.addIcon(...ICONS);
}
load(): Promise<void> {
const slowEl = this.doc.querySelector('#_slow');
return new Promise(resolve => {
if (slowEl) {
slowEl.remove();
}
this.injector.get(TitleService).suffix = 'Ng Alain';
if (this.platform.isBrowser) {
setTimeout(() => this.lazyLoad(), 100);
}
resolve();
});
}
lazyLoad(): void {
const win = this.doc.defaultView as any;
win.hj =
win.hj ||
function () {
(win.hj.q = win.hj.q || []).push(arguments);
};
win._hjSettings = {
hjid: 920546,
hjsv: 6
};
Promise.all([
this.lazy.loadScript(`https://www.googletagmanager.com/gtag/js?id=UA-120202005-1`),
this.lazy.loadScript(`https://static.hotjar.com/c/hotjar-${win._hjSettings.hjid}.js?sv=${win._hjSettings.hjsv}`)
]).then(() => {
const dataLayer: any[] = win.dataLayer || [];
dataLayer.push(['js', new Date()]);
dataLayer.push(['config', 'UA-120202005-1']);
});
}
}
|
<gh_stars>10-100
# frozen_string_literal: true
require 'cuba'
require 'cuba/render'
require 'bigdecimal'
module I18nYamlEditor
# The frontend rendering engine
class Web < Cuba
plugin Cuba::Render
settings[:render][:template_engine] = 'erb'
settings[:render][:views] = File.expand_path(
File.join(File.dirname(__FILE__), '..', '..', 'views')
)
use Rack::ShowExceptions
# Reads global App instance
def app
I18nYamlEditor.app
end
define do
on get, root do
on param('filters') do |filters|
opts = {}
opts[:key] = /#{filters["key"]}/ unless filters['key'].to_s.empty?
opts[:text] = /#{filters["text"]}/i unless filters['text'].to_s.empty?
opts[:complete] = false if filters['incomplete'] == 'on'
opts[:empty] = true if filters['empty'] == 'on'
keys = app.store.filter_keys(opts)
res.write view('translations.html', keys: keys, filters: filters)
end
on default do
categories = app.store.categories.sort
res.write view('categories.html', categories: categories, filters: {})
end
end
on post, 'update' do
translations = req['translations']
app.save_translations(translations) if translations
url = Rack::Utils.build_nested_query(filters: req['filters'])
res.redirect "/?#{url}"
end
on get, 'debug' do
res.write partial('debug.html',
translations: app.store.translations.values)
end
end
end
end
|
def count_word_occurrences(file_name, words_to_count):
word_counts = {word: 0 for word in words_to_count}
with open(file_name, 'r') as file:
text = file.read()
text = text.replace('\n', ' ')
text = ''.join(e for e in text if e.isalnum() or e.isspace())
words = text.split()
for word in words:
if word in word_counts:
word_counts[word] += 1
for word, count in word_counts.items():
print(f"Occurrences of '{word}': {count}")
# Usage
file_name = "sample_text.txt"
words_to_count = ["License", "software", "distributed"]
count_word_occurrences(file_name, words_to_count) |
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
/**
* Constructor: OpenLayers.Class
* Base class used to construct all other classes. Includes support for
* multiple inheritance.
*
* To create a new OpenLayers-style class, use the following syntax:
* > var MyClass = OpenLayers.Class(prototype);
*
* To create a new OpenLayers-style class with multiple inheritance, use the
* following syntax:
* > var MyClass = OpenLayers.Class(Class1, Class2, prototype);
* Note that instanceof reflection will only reveil Class1 as superclass.
* Class2 ff are mixins.
*
*/
OpenLayers.Class = function() {
var Class = function() {
this.initialize.apply(this, arguments);
};
var extended = {};
var parent, initialize, Type;
for(var i=0, len=arguments.length; i<len; ++i) {
Type = arguments[i];
if(typeof Type == "function") {
// make the class passed as the first argument the superclass
if(i == 0 && len > 1) {
initialize = Type.prototype.initialize;
// replace the initialize method with an empty function,
// because we do not want to create a real instance here
Type.prototype.initialize = function() {};
// the line below makes sure that the new class has a
// superclass
extended = new Type();
// restore the original initialize method
if(initialize === undefined) {
delete Type.prototype.initialize;
} else {
Type.prototype.initialize = initialize;
}
}
// get the prototype of the superclass
parent = Type.prototype;
} else {
// in this case we're extending with the prototype
parent = Type;
}
OpenLayers.Util.extend(extended, parent);
}
Class.prototype = extended;
return Class;
};
|
<filename>tests/unit/bud-api/repository/experiments.test.ts
import {Bud, factory} from '@repo/test-kit/bud'
import {join} from 'path'
describe('bud.experiments', function () {
let bud: Bud
beforeAll(async () => {
bud = await factory({
features: {
dashboard: false,
log: false,
},
location: {
project: join(process.cwd(), 'examples/sage'),
},
})
})
it('is a function', () => {
expect(bud.experiments).toBeInstanceOf(Function)
})
it('enables build.config.experiments', async () => {
bud.experiments('lazyCompilation', true)
await bud.build.make()
const output = await bud.hooks.filterAsync(
'build.experiments',
)
expect(output).toEqual({lazyCompilation: true})
})
})
|
<filename>tailwind.config.js
const defaultTheme = require('tailwindcss/defaultTheme');
const colors = require('tailwindcss/colors');
module.exports = {
mode: 'jit',
purge: [
'./vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php',
'./storage/framework/views/*.php',
'./resources/views/**/*.blade.php',
],
theme: {
extend: {
fontFamily: {
sans: ['Nunito', ...defaultTheme.fontFamily.sans],
},
borderWidth: {
default: '1px',
'0': '0',
'2': '2px',
'3': '3px',
'4': '4px',
'6': '6px',
'8': '8px',
},
colors: {
...colors,
'primary': 'var(--primary-color)',
'primary-light': 'var(--primary-light-color)',
'primary-dark': 'var(--primary-dark-color)',
},
textColor: {
'default': 'var(--text-default-color)',
'muted': 'var(--text-muted-color)',
'label': 'var(--text-label-color)',
},
backgroundColor: {
'body': 'var(--background-body-color)',
'card': 'var(--background-card-color)',
'hover': 'var(--background-hover-color)',
'input': 'var(--background-input-color)',
'navbar': 'var(--background-navbar-color)',
'sidebar': 'var(--background-sidebar-color)',
'modal': 'var(--background-modal-color)',
},
borderColor: {
'input': 'var(--border-input-color)',
'navbar': 'var(--border-navbar-color)',
},
ringColor: {
'primary': 'rgba(71, 205, 255, var(--tw-ring-opacity))'
}
},
},
variants: {
extend: {
opacity: ['disabled'],
},
// colors
},
plugins: [require('@tailwindcss/forms')],
};
|
<filename>ci/validate_onnx.py
import onnx
from onnx import numpy_helper
import os
import glob
import numpy as np
import tempfile
def convert(onnx2daq, onnx, daq, table_file=''):
daq = "temp.daq"
os.system("{} {} {} {}".format(onnx2daq, onnx, daq, table_file))
print("Converted to daq")
def finish(model):
os.system("adb shell rm /data/local/tmp/{}".format(os.path.basename(model)))
if model[-4:] == '.daq':
os.system("rm {}".format(model))
def run(input_arrs, daq, dnn_retrieve_result, quant_input=False, quant_output=False):
input_txts = []
for i, input_arr in enumerate(input_arrs):
if len(input_arr.shape) == 4:
nchw_shape = input_arr.shape
nhwc_shape = (nchw_shape[0], nchw_shape[2], nchw_shape[3], nchw_shape[1])
input_arr = np.moveaxis(input_arr, 1, -1)
assert input_arr.shape == nhwc_shape
input_txt = 'input{}.txt'.format(i)
np.savetxt(input_txt, input_arr.flatten(), delimiter='\n')
input_txts.append(input_txt)
input_txts_arg = " ".join(input_txts)
input_txts_in_android_arg = " ".join(map(lambda x: "/data/local/tmp/" + x, input_txts))
txt = os.path.join(tempfile._get_default_tempdir(), next(tempfile._get_candidate_names()))
os.system("adb push {} /data/local/tmp/".format(input_txts_arg))
os.system("adb push {} /data/local/tmp/dnn_retrieve_result".format(dnn_retrieve_result))
os.system('adb shell "LD_LIBRARY_PATH=/data/local/tmp/ /data/local/tmp/dnn_retrieve_result --nchw_result /data/local/tmp/{} {} {} {}"'.format(os.path.basename(daq), "--quant_input" if quant_input else "", "--quant_output" if quant_output else "", input_txts_in_android_arg))
os.system("adb shell rm {}".format(input_txts_in_android_arg))
os.system("adb shell rm /data/local/tmp/dnn_retrieve_result")
os.system("adb pull /data/local/tmp/result {}".format(txt))
os.system("adb shell rm /data/local/tmp/result")
os.system("rm {}".format(input_txts_arg))
actual = np.loadtxt(txt)
assert not np.any(np.isnan(actual))
return actual
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Test onnx model on nnapi')
parser.add_argument('dir', type=str, help='onnx model file')
parser.add_argument('dnn_retrieve_result', type=str, help='dnn_retrieve_result binary file')
parser.add_argument('--onnx2daq', type=str, help='onnx2daq binary file')
parser.add_argument('--table_file', type=str, help='table file for 8-bit quantization', default='')
parser.add_argument('--quant_input', help='whether the input is quant8', action='store_true')
parser.add_argument('--quant_output', help='whether the output is quant8', action='store_true')
args = parser.parse_args()
onnx_model = glob.glob(os.path.join(args.dir, '*.onnx'))
assert len(onnx_model) == 1
onnx_model = onnx_model[0]
data_dirs = glob.glob(os.path.join(args.dir, 'test_data_set_*'))
for data_dir in data_dirs:
# Load inputs
inputs = []
inputs_num = len(glob.glob(os.path.join(data_dir, 'input_*.pb')))
for i in range(inputs_num):
input_file = os.path.join(data_dir, 'input_{}.pb'.format(i))
tensor = onnx.TensorProto()
with open(input_file, 'rb') as f:
tensor.ParseFromString(f.read())
np_arr = numpy_helper.to_array(tensor)
if args.quant_input:
np_arr = np_arr.astype(np.uint8)
inputs.append(np_arr)
# Load reference outputs
ref_outputs = []
ref_outputs_num = len(glob.glob(os.path.join(data_dir, 'output_*.pb')))
for i in range(ref_outputs_num):
output_file = os.path.join(data_dir, 'output_{}.pb'.format(i))
tensor = onnx.TensorProto()
with open(output_file, 'rb') as f:
tensor.ParseFromString(f.read())
ref_outputs.append(numpy_helper.to_array(tensor))
if args.onnx2daq is None:
model = onnx_model
else:
model = "temp.daq"
convert(args.onnx2daq, onnx_model, model, args.table_file)
os.system("adb push {} /data/local/tmp/".format(model))
actual = run(inputs, model, args.dnn_retrieve_result, args.quant_input, args.quant_output)
expected = ref_outputs[i].flatten()
print('====================')
try:
print("Max relative diff: {}".format(np.max(np.abs(expected - actual) / expected)))
np.testing.assert_array_almost_equal(expected, actual, decimal=3)
print('{} passed'.format(os.path.basename(data_dir)))
except (AssertionError, ValueError) as e:
print('{} failed'.format(os.path.basename(data_dir)))
print(str(e))
print(expected)
print('-----')
print(actual)
print(np.argmax(actual))
finish(model)
|
#! /usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
# code-generator does work with go.mod but makes assumptions about the project living in `$GOPATH/src`.
# To work around this and support any location:
# create a temporary directory, use this as an output base, and copy everything back once generated.
export GOPATH=$(go env GOPATH) # export gopath so it's available to generate scripts
SCRIPT_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." >/dev/null 2>&1 && pwd )"
CODEGEN_VERSION=$(go list -m k8s.io/code-generator | awk '{print $NF}' | head -1)
CODEGEN_PKG="${GOPATH}/pkg/mod/k8s.io/code-generator@${CODEGEN_VERSION}"
TEMP_DIR=$(mktemp -d)
cleanup() {
rm -rf ${TEMP_DIR}
}
trap "cleanup" EXIT SIGINT
chmod +x ${CODEGEN_PKG}/generate-groups.sh
${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \
github.com/argoproj/argo-rollouts/pkg/client github.com/argoproj/argo-rollouts/pkg/apis \
"rollouts:v1alpha1" \
--output-base "${TEMP_DIR}" \
--go-header-file ${SCRIPT_ROOT}/hack/boilerplate.go.txt
cp -r "${TEMP_DIR}/github.com/argoproj/argo-rollouts/." "${SCRIPT_ROOT}/"
# To use your own boilerplate text use:
# --go-header-file ${SCRIPT_ROOT}/hack/custom-boilerplate.go.txt
CONTROLLERGEN_VERSION=$(go list -m sigs.k8s.io/controller-tools | awk '{print $2}' | head -1)
CONTROLLERGEN_PKG=$(echo `go env GOPATH`"/pkg/mod/sigs.k8s.io/controller-tools@${CONTROLLERGEN_VERSION}")
go build -o dist/controller-gen $CONTROLLERGEN_PKG/cmd/controller-gen/
./dist/controller-gen --version
|
import assert from 'assert'
import nock, { Definition } from 'nock'
import { URL } from 'url'
import Knex from 'knex'
import { v4 as uuid } from 'uuid'
import {
EventType,
isPaymentEventType,
WebhookService,
generateWebhookSignature,
invoiceToData,
paymentToData
} from './service'
import { createTestApp, TestContainer } from '../tests/app'
import { randomAsset } from '../tests/asset'
import { truncateTables } from '../tests/tableManager'
import { Config } from '../config/app'
import { IocContract } from '@adonisjs/fold'
import { initIocContainer } from '../'
import { AppServices } from '../app'
import { Invoice } from '../open_payments/invoice/model'
import { OutgoingPayment } from '../outgoing_payment/model'
describe('Webhook Service', (): void => {
let deps: IocContract<AppServices>
let appContainer: TestContainer
let webhookService: WebhookService
let knex: Knex
let invoice: Invoice
let payment: OutgoingPayment
let amountReceived: bigint
let amountSent: bigint
let balance: bigint
let webhookUrl: URL
const WEBHOOK_SECRET = 'test secret'
beforeAll(
async (): Promise<void> => {
Config.webhookSecret = WEBHOOK_SECRET
deps = await initIocContainer(Config)
appContainer = await createTestApp(deps)
knex = await deps.use('knex')
webhookService = await deps.use('webhookService')
const accountService = await deps.use('accountService')
const { id: accountId } = await accountService.create({
asset: randomAsset()
})
const invoiceService = await deps.use('invoiceService')
invoice = await invoiceService.create({
accountId,
amount: BigInt(56),
expiresAt: new Date(Date.now() + 60 * 1000),
description: 'description!'
})
const outgoingPaymentService = await deps.use('outgoingPaymentService')
const config = await deps.use('config')
const invoiceUrl = `${config.publicHost}/invoices/${invoice.id}`
payment = await outgoingPaymentService.create({
accountId,
invoiceUrl,
autoApprove: false
})
amountReceived = BigInt(5)
amountSent = BigInt(10)
balance = BigInt(0)
webhookUrl = new URL(config.webhookUrl)
}
)
afterAll(
async (): Promise<void> => {
await appContainer.shutdown()
await truncateTables(knex)
}
)
describe('Send Event', (): void => {
it.each(Object.values(EventType).map((type) => [type]))(
'%s',
async (type): Promise<void> => {
const id = uuid()
nock(webhookUrl.origin)
.post(webhookUrl.pathname, function (this: Definition, body) {
assert.ok(this.headers)
const signature = this.headers['rafiki-signature']
expect(
generateWebhookSignature(
body,
WEBHOOK_SECRET,
Config.signatureVersion
)
).toEqual(signature)
expect(body.id).toEqual(id)
expect(body.type).toEqual(type)
if (isPaymentEventType(type)) {
expect(body.data).toEqual(
paymentToData(payment, amountSent, balance)
)
} else {
expect(body.data).toEqual(invoiceToData(invoice, amountReceived))
}
return true
})
.reply(200)
if (isPaymentEventType(type)) {
await webhookService.send({
id,
type,
payment,
amountSent,
balance
})
} else {
await webhookService.send({
id,
type,
invoice,
amountReceived
})
}
}
)
it('throws for failed request', async (): Promise<void> => {
const scope = nock(webhookUrl.origin).post(webhookUrl.pathname).reply(500)
await expect(
webhookService.send({
id: uuid(),
type: EventType.InvoicePaid,
invoice,
amountReceived
})
).rejects.toThrowError('Request failed with status code 500')
expect(scope.isDone()).toBe(true)
})
})
})
|
#!/bin/bash -ex
useradd -m ubuntu
pip install selenium
chown -R ubuntu:ubuntu /home/ubuntu
sh $(dirname "$0")/init_etc_resolv_conf.sh
sh $(dirname "$0")/init_selenium.sh
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.