language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 891 | 2.234375 | 2 |
[] |
no_license
|
package com.example.boot.user;
import javax.persistence.Entity;
import javax.persistence.*;
@Entity
@Table(name="user_table")
public class User {
@Id
// @GeneratedValue(strategy=GenerationType.AUTO)
private int uid;
private String name;
private String email;
private Integer mgr_id;
public User(int uid,String name,String email,Integer mgr_id)
{
this.uid=uid;
this.name=name;
this.email=email;
this.mgr_id=mgr_id;
}
public User()
{
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getMgr_id() {
return mgr_id;
}
public void setMgr_id(Integer mgr_id) {
this.mgr_id = mgr_id;
}
}
|
C++
|
UTF-8
| 3,806 | 2.875 | 3 |
[] |
no_license
|
#include <sys/stat.h>
#include <fstream>
#include <vector>
#include <iostream>
#include "json.hpp"
#include "file_segment.hpp"
using json = nlohmann::json;
const string FileSegment::kSegmentFileNum = "SegmentNum";
const string FileSegment::kSourceFileName = "SourceFileName";
const string FileSegment::kSegmentFiles = "SegmentFiles";
const int FileSegment::kBlockSize = 1024 * 1024; // 1MB
void FileSegment::segment(string file_name, int segment_num, string json_file) {
// 检查源文件是否存在
if (!exist(file_name)) {
cout << "file [" << file_name << "] doesn't exist!" << endl;
return;
}
// 检查分片数量是否大于0
if (segment_num <= 0) {
cout << "segment number should be greater than 0!" << endl;
return;
}
// 分片文件名
vector<string> segment_files;
for (int i = 0; i < segment_num; i++) {
segment_files.push_back(file_name + to_string(i+1) + ".tmp");
cout << "segment_file --- " << segment_files[i] << endl;
}
ifstream src_file_input(file_name);
// 输入文件大小
size_t src_file_size = file_size(src_file_input);
// 分片文件大小
size_t segment_size = src_file_size / segment_num;
// 分片输出文件
for (int i = 0; i < segment_num; i++) {
ofstream segment_file_output(segment_files[i]);
if (i == segment_num-1) { // 最后一次,要将剩余文件片全部写入
size_t left_size = src_file_size % segment_size;
copy_file(src_file_input, segment_file_output, segment_size + left_size);
} else {
copy_file(src_file_input, segment_file_output, segment_size);
}
segment_file_output.close();
}
src_file_input.close();
ofstream json_output(json_file);
json j;
j[kSegmentFileNum] = segment_num;
j[kSourceFileName] = file_name;
j[kSegmentFiles] = segment_files;
json_output << j;
json_output.close();
}
void FileSegment::merge(string json_file) {
json j;
if (!exist(json_file)) {
cout << "json file [" << json_file << "] doesn't exist!" << endl;
return;
}
ifstream json_input(json_file);
json_input >> j;
// 源文件名
string src_file = j[kSourceFileName];
// 检查源文件是否已经存在
if (exist(src_file)) {
src_file += ".copy";
}
ofstream result(src_file);
// 文件分片数量
int segment_num = j[kSegmentFileNum];
// 分片文件名
vector<string> segment_files = j[kSegmentFiles];
// 检查文件分片是否齐全
for (auto it = segment_files.begin(); it != segment_files.end(); ++it) {
if (!exist(*it)) {
cout << "segment file [" << *it << "] doesn't exist!" << endl;
return;
}
}
// 合并文件
for (auto it = segment_files.begin(); it != segment_files.end(); it++) {
cout << "copy file [" << *it << "]" << endl;
ifstream seg_input(*it);
size_t seg_input_size = file_size(seg_input);
copy_file(seg_input, result, seg_input_size);
seg_input.close();
}
json_input.close();
result.close();
}
void FileSegment::copy_file(ifstream &input, ofstream &output, size_t input_size) {
char* data = new char[kBlockSize];
for (size_t block = 0; block < input_size / kBlockSize; block++) {
read_file_in_block(data, input);
write_file_in_block(data, output);
}
size_t left_size = input_size % kBlockSize;
if (left_size != 0) {
read_file_in_block(data, input, left_size);
write_file_in_block(data, output, left_size);
}
delete [] data;
data = nullptr;
}
bool FileSegment::exist(string name) {
struct stat buffer;
return (stat(name.c_str(), &buffer) == 0);
}
size_t FileSegment::file_size(ifstream &file) {
size_t size;
file.seekg(0, std::ios::end);
size = file.tellg();
file.seekg(0, std::ios::beg);
return size;
}
|
Python
|
UTF-8
| 152 | 2.953125 | 3 |
[] |
no_license
|
from time import sleep
target_time=11
def up_timer(secs):
for i in range(0,secs):
print(i)
sleep(1)
up_timer(target_time)
|
Python
|
UTF-8
| 623 | 4.40625 | 4 |
[] |
no_license
|
# Write 2 recursive functions that will reverse a list of numbers.
# 1. you are not allowed to change the original list. You will return a new list.
def reverse_list01(list):
list = str(list)
new_list = []
if len(new_list)==len(list):
return new_list
return new_list.append((reverse_list01(list[:-1])))
print(reverse_list01([11, 23, 45, 67, 89]))
# 2. you are not allowed to create new lists, you need to return the original list.
def reverse_list02(list):
if len(list) == 0:
return []
return [list[-1]] + reverse_list02(list[:-1])
print(reverse_list02([11, 23, 45, 67, 89]))
|
Java
|
UTF-8
| 9,658 | 1.96875 | 2 |
[] |
no_license
|
package com.hakami1024.vk_news;
import java.util.ArrayList;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import com.hakami1024.utils.VKPost;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.vk.sdk.api.model.VKApiCommunity;
import com.vk.sdk.api.model.VKApiUser;
public class NewsfeedFragment extends ListFragment implements OnScrollListener,
OnRefreshListener, DataUpdating {
VkListAdapter adapter;
private static final String LIST_TOP_INDEX = "com.hakami1024.vk_news.listTopIndex";
private final int TIME_NOW = 1;
private String TAG = "NewsfeedFragment";
public int addNews = 1;
private int topNewsIndex = 0;
SparseArray<VKApiUser> usersArray = new SparseArray<VKApiUser>();
SparseArray<VKApiCommunity> groupsArray = new SparseArray<VKApiCommunity>();
ArrayList<VKPost> news = new ArrayList<VKPost>();
ArrayList<VKPost> updates = new ArrayList<VKPost>();
NewsfeedCreator newsCreator = new NewsfeedCreator(this);
SwipeRefreshLayout refreshLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.d(TAG, "onCreate started");
// newsCreator.getNews(0);
setRetainInstance(true);
/*
* if( savedInstanceState != null ) { topNewsIndex =
* savedInstanceState.getInt(LIST_TOP_INDEX); Log.d(TAG,
* "in onCreate, topNewsIndex = "+topNewsIndex); addNews = 2;
* newsCreator.getNews(); } else Log.d(TAG,
* "savedInstanceState is null");
*/
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.photo_loading)
.cacheInMemory(true).cacheOnDisc(true).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getActivity().getApplicationContext())
.defaultDisplayImageOptions(defaultOptions).build();
ImageLoader.getInstance().init(config);
// newsCreator.getNews();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_newsfeed, parent, false);
refreshLayout = (SwipeRefreshLayout) v;
refreshLayout.setOnRefreshListener(this);
return v;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.getListView().setOnScrollListener(this);
//Log.d(TAG, "setting onItemClickListener");
this.getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Log.d(TAG, "Item Clicked");
Intent i = new Intent(NewsfeedFragment.this.getActivity(),
SingleNewsActivity.class);
i.putExtra(VKPost.POST_DATE, "" + news.get(position).date);
NewsfeedFragment.this.getActivity().startActivity(i);
}
});
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(LIST_TOP_INDEX, topNewsIndex);
Log.i(TAG, "onSavedInstanceState");
}
public void setNewsfeed(JSONObject resp, boolean isFirst) {
try {
//Log.d(TAG, "setNewsfeed: " + resp.toString());
resp = resp.getJSONObject("response");
JSONArray items = resp.getJSONArray("items");
JSONArray profiles = resp.getJSONArray("profiles");
JSONArray groups = resp.getJSONArray("groups");
if (items == null || items.length() == 0)
return;
VKPost[] posts = new VKPost[items.length()];
VKApiUser[] users = new VKApiUser[profiles.length()];
VKApiCommunity[] communities = new VKApiCommunity[groups.length()];
// Log.d(TAG, "JSONArrays and object arrays created. Filling...");
for (int i = 0; i < items.length(); i++) {
try {
posts[i] = new VKPost();
posts[i].parse(items.optJSONObject(i));
} catch (Exception ex) {
Log.d(TAG, "located");
ex.printStackTrace();
}
}
// Log.d(TAG, "filled posts");
for (int i = 0; i < profiles.length(); i++) {
users[i] = new VKApiUser();
users[i].parse(profiles.getJSONObject(i));
usersArray.append(users[i].id, users[i]);
}
// Log.d(TAG, "filled users");
for (int i = 0; i < groups.length(); i++) {
communities[i] = new VKApiCommunity();
communities[i].parse(groups.getJSONObject(i));
groupsArray.append(communities[i].id, communities[i]);
}
// Log.d(TAG, "filled groups");
if (isFirst) {
// adapter.insert(posts[0], 0);
updates.add(posts[0]);
if (updates.size() < 2)
newsCreator
.getUpdate(news.get(0).date, updates.get(0).date);
else
newsCreator.getUpdate(updates.get(updates.size() - 1).date,
updates.get(updates.size() - 2).date);
} else
news.addAll(Arrays.asList(posts));
if (adapter == null) {
adapter = new VkListAdapter(news);
this.setListAdapter(adapter);
//Log.d(TAG, "adapter created");
} // else
adapter.notifyDataSetChanged();
//Log.d(TAG, "in setNewsfeed, news.size() = " + news.size());
} catch (Exception e) {
Log.e(TAG, "error setting Newsfeed");
e.printStackTrace();
}
Log.d(TAG, "topNewsIndex = " + topNewsIndex);
if (news.size() > topNewsIndex)
addNews = 0;
else {
newsCreator.getNews();
// getListView().setSelection( news.size()-1 );
}
}
public void setNoNewsfeed() {
if (!updates.isEmpty()) {
Log.d(TAG, "setNoNewsfeed: updates");
news.addAll(0, updates);
getListView().setSelection(updates.size());
getListView().smoothScrollToPosition(updates.size());
for (int i = 0; i < updates.size(); i++)
adapter.getView(i, null, null);
updates.clear();
adapter.notifyDataSetChanged();
}
addNews = 0;
refreshLayout.setRefreshing(false);
}
private class VkListAdapter extends ArrayAdapter<VKPost> {
public VkListAdapter(ArrayList<VKPost> news) {
super(getActivity(), 0, news);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(TAG, "on position " + position);
if (convertView == null) {
Log.d(TAG, "convertView creating");
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.news_item, null);
VKPostHolder holder = new VKPostHolder(convertView,
VKPostViewer.countReposts(getItem(position)), false,
position);
VKPostViewer viewer = new VKPostViewer(getItem(position),
usersArray, groupsArray, holder, false) {
@Override
void changeDataSet() {
adapter.notifyDataSetChanged();
Log.d(TAG, "changeDataSet worked");
}
};
convertView.setTag(holder);
// convertView.setTag(position);
// convertView.setTag(viewer);
viewer.setOnView();
} else {
Log.d(TAG, "" + convertView + " " + convertView.getTag());
VKPostHolder holder;// = (VKPostHolder)convertView.getTag();
if (convertView.getTag() == null
|| ((VKPostHolder) convertView.getTag()).time != getItem(position).date) {
if (convertView.getTag() == null) {
holder = new VKPostHolder(convertView,
VKPostViewer.countReposts(getItem(position)),
false, position);
Log.e(TAG, "RECREATING HOLDER");
} else {
holder = (VKPostHolder) convertView.getTag();
holder.context = convertView.getContext();
holder.resetPost(position,
VKPostViewer.countReposts(getItem(position)),
convertView);
Log.i(TAG, "RESET HOLDER");
}
VKPostViewer viewer = new VKPostViewer(getItem(position),
usersArray, groupsArray, holder, false) {
@Override
void changeDataSet() {
adapter.notifyDataSetChanged();
Log.d(TAG, "changeDataSet worked");
}
};
viewer.setOnView();
convertView.setTag(holder);
} else {
// Log.d(TAG, " "+convertView.getTag().toString());
Log.d(TAG, "all is already prepared");
// viewer = (VKPostViewer) convertView.getTag();
}
}
return convertView;
}
}
int lastState = OnScrollListener.SCROLL_STATE_IDLE;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Log.d(TAG, "scrollState = "+scrollState);
if (scrollState == SCROLL_STATE_TOUCH_SCROLL
&& lastState == SCROLL_STATE_IDLE && addNews == 0)
addNews = 1;
lastState = scrollState;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount
&& addNews < 2) {
addNews = 2;
// Log.d(TAG, "firstVisible: " + firstVisibleItem);
topNewsIndex = firstVisibleItem;
newsCreator.getNews();
} else if (firstVisibleItem == 0) {
// newsCreator.getNews( from_time );
}
}
@Override
public void onRefresh() {
if (addNews < 2) {
addNews = 2;
refreshLayout.setRefreshing(true);
newsCreator.getUpdate(
news == null || news.size() == 0 ? 0 : news.get(0).date,
TIME_NOW);
}
}
}
|
JavaScript
|
UTF-8
| 595 | 2.578125 | 3 |
[] |
no_license
|
/*
Author: Joanne
Date: 2018-05-07
Description: 描述背景类
属性:
img: 传进来的图片对象
speed: 移动的速度
step: 移动的距离
*/
define(function(require, exports, module) {
function Background(img, speed) {
this.img = img;
this.speed = speed;
this.step = 0;
}
Background.prototype = {
constructor: Background,
// 移动的方法
move: function() {
this.step ++;
// this.step += 20;
},
}
module.exports = Background;
})
|
Markdown
|
UTF-8
| 20,143 | 2.921875 | 3 |
[
"LicenseRef-scancode-boost-original"
] |
permissive
|
# 正規表現 {regular_expressions}
## イントロダクション {introduction}
正規表現は、テキストのマッチのための領域固有言語です。テキストのマッチのために小さなプログラムをゼロから作ることもできますが、間違いを起こしやすいですし、面倒くさいですし、あまりポータブルでもフレキシブルでもありません。
代わりにマッチを(シンプルなケースでは)マッチする文字タイプとどれだけの文字をマッチさせたいかを決める数量詞を文字列として表現する正規表現を使います。
例えば、普通の文字と数字は文字通りマッチします。`\w`は単語の文字にマッチし、`\s`は(スペース、タブ、改行など)の空白文字にマッチします。ピリオド(`.`)は(改行をのぞいて)あらゆる文字にマッチします。
基本的な数量詞は、マッチがゼロ回かそれ以上あるアスタリスク(`*`)、1回かそれ以上nマッチするプラス(`+`)、`{min,max}`という形で表される範囲です。
これだけで、語を探す(`\w+`)機能や画像タグの中の`alt`属性(`<img.*alt=".*">`)を探す機能が手に入ります。
もっと長いテキストのマッチも必要ですが、マッチの部分集合(subset)が必要だと感じることも多いと思います。例えば、上記の例では、もし`alt`属性のテキストを置換したいとします。もし、括弧を使って、正規表現を囲むと、置換のための文字列のなかで使われうる変数を _捕まえる(キャプチャ)_ ことができます。置換のための文字列のフォーマットはこのセクションの最後で説明しますが、初めに捕まえたもの(キャプチャ)には、`$1`、2番目は`$2`を使います。
なので、`alt`属性のテキストを変えるためには、`(<img.*alt=").*(">)`を検索して、それを`$1Text Intentionally Removed$2`に置換できます。
_上記の例では`.*`が使われています。しかしながら、アスタリスク演算子はどん欲(greedy)です。つまり、(マッチする限り)できるだけたくさんの文字にマッチします。なので、どん欲ではなくしたい場合は`?`を加えて`.*?`にします。_
### 外部リソース {external_resources}
* [Regular-Expressions.info](http://www.regular-expressions.info/)
* A.M. Kuchlingの [Regular Expression HOWTO](http://www.amk.ca/python/howto/regex/)
* Steve Mansourの [A Tao of Regular Expressions](http://linuxreviews.org/beginner/tao_of_regular_expressions/)
* Jeffrey Friedlの [Mastering Regular Expressions](http://www.oreilly.com/catalog/regex2/) (書籍)
## TextMateでの正規表現 {regular_expressions_in_textmate}
これはTextMateが正規表現を活用できる機会のリストです:
* (プロジェクトに加えられた)フォルダレファランスで表示されるファイルを正規表現を使うことによってフィルタリングする。
* 検索とプロジェクト内の検索は正規表現を代わりに使うことができます。
* 正規表現を使ってフォールディング(たたむ)マーカを
見つける
* 正規表現のマッチに基づいて、インデントを計算する。
* ランゲージグラマーは基本的には、それぞれのモードで、正規表現をもつ(サイクルつきの)木構造です。
* スニペットでは正規表現を変数に適用できたり、(リアルタイムに)ミラーリングされたプレースホルダに適用できます。
よって、言うまでもなく正規表現はTextMateでは重要な役割をします。知らなくても幸せな生活を送ることができますが、(もしまだ詳しくないなら)本やチュートリアルなどを使って、正規表現により詳しくなることを強く推奨します。
TextMateだけではなく、(`sed`, `grep`, `awk`, `find`などの)多くのシェルコマンドでは正規表現をサポートします。PerlやRubyのような有名なスクリプト言語には、言語の深いレベルで正規表現をサポートしています。
## シンタックス (鬼車) {syntax_oniguruma}
TextMateではK. Kosakoさんによる鬼車正規表現ライブラリを使います。
以下は<http://www.geocities.jp/kosako3/oniguruma/doc/RE.txt>からの引用です。
Oniguruma Regular Expressions Version 3.6.0 2005/02/01
syntax: ONIG_SYNTAX_RUBY (default)
1. Syntax elements
\ escape (enable or disable meta character meaning)
| alternation
(...) group
[...] character class
2. Characters
\t horizontal tab (0x09)
\v vertical tab (0x0B)
\n newline (0x0A)
\r return (0x0D)
\b back space (0x08)
\f form feed (0x0C)
\a bell (0x07)
\e escape (0x1B)
\nnn octal char (encoded byte value)
\xHH hexadecimal char (encoded byte value)
\x{7HHHHHHH} wide hexadecimal char (character code point value)
\cx control char (character code point value)
\C-x control char (character code point value)
\M-x meta (x|0x80) (character code point value)
\M-\C-x meta control char (character code point value)
(* \b is effective in character class [...] only)
3. Character types
. any character (except newline)
\w word character
Not Unicode:
alphanumeric, "_" and multibyte char.
Unicode:
General_Category --
(Letter|Mark|Number|Connector_Punctuation)
\W non word char
\s whitespace char
Not Unicode:
\t, \n, \v, \f, \r, \x20
Unicode:
0009, 000A, 000B, 000C, 000D, 0085(NEL),
General_Category -- Line_Separator
-- Paragraph_Separator
-- Space_Separator
\S non whitespace char
\d decimal digit char
Unicode: General_Category -- Decimal_Number
\D non decimal digit char
\h hexadecimal digit char [0-9a-fA-F]
\H non hexadecimal digit char
4. Quantifier
greedy
? 1 or 0 times
* 0 or more times
+ 1 or more times
{n,m} at least n but not more than m times
{n,} at least n times
{,n} at least 0 but not more than n times ({0,n})
{n} n times
reluctant
?? 1 or 0 times
*? 0 or more times
+? 1 or more times
{n,m}? at least n but not more than m times
{n,}? at least n times
{,n}? at least 0 but not more than n times (== {0,n}?)
possessive (greedy and does not backtrack after repeated)
?+ 1 or 0 times
*+ 0 or more times
++ 1 or more times
({n,m}+, {n,}+, {n}+ are possessive op. in ONIG_SYNTAX_JAVA only)
ex. /a*+/ === /(?>a*)/
5. Anchors
^ beginning of the line
$ end of the line
\b word boundary
\B not word boundary
\A beginning of string
\Z end of string, or before newline at the end
\z end of string
\G matching start position (*)
* Ruby Regexp:
previous end-of-match position
(This specification is not related to this library.)
6. Character class
^... negative class (lowest precedence operator)
x-y range from x to y
[...] set (character class in character class)
..&&.. intersection (low precedence at the next of ^)
ex. [a-w&&[^c-g]z] ==> ([a-w] AND ([^c-g] OR z)) ==> [abh-w]
* If you want to use '[', '-', ']' as a normal character
in a character class, you should escape these characters by '\'.
POSIX bracket ([:xxxxx:], negate [:^xxxxx:])
Not Unicode Case:
alnum alphabet or digit char
alpha alphabet
ascii code value: [0 - 127]
blank \t, \x20
cntrl
digit 0-9
graph include all of multibyte encoded characters
lower
print include all of multibyte encoded characters
punct
space \t, \n, \v, \f, \r, \x20
upper
xdigit 0-9, a-f, A-F
Unicode Case:
alnum Letter | Mark | Decimal_Number
alpha Letter | Mark
ascii 0000 - 007F
blank Space_Separator | 0009
cntrl Control | Format | Unassigned | Private_Use | Surrogate
digit Decimal_Number
graph [[:^space:]] && ^Control && ^Unassigned && ^Surrogate
lower Lowercase_Letter
print [[:graph:]] | [[:space:]]
punct Connector_Punctuation | Dash_Punctuation |
Close_Punctuation | Final_Punctuation | Initial_Punctuation
| Other_Punctuation | Open_Punctuation
space Space_Separator | Line_Separator | Paragraph_Separator |
0009 | 000A | 000B | 000C | 000D | 0085
upper Uppercase_Letter
xdigit 0030 - 0039 | 0041 - 0046 | 0061 - 0066
(0-9, a-f, A-F)
7. Extended groups
(?#...) comment
(?imx-imx) option on/off
i: ignore case
m: multi-line (dot(.) match newline)
x: extended form
(?imx-imx:subexp) option on/off for subexp
(?:subexp) not captured group
(subexp) captured group
(?=subexp) look-ahead
(?!subexp) negative look-ahead
(?<=subexp) look-behind
(?<!subexp) negative look-behind
Subexp of look-behind must be fixed character
length. But different character length is allowed
in top level alternatives only. ex. (?<=a|bc) is
OK. (?<=aaa(?:b|cd)) is not allowed.
In negative-look-behind, captured group is not
allowed, but shy group(?:) is allowed.
(?>subexp) atomic group
do not backtrack in subexp.
(?<name>subexp) define named group
(All characters of the name must be a word
character. And first character must not be a digit
or uppper case)
Not only a name but a number is assigned like a
captured group.
Assigning the same name as two or more subexps is
allowed. In this case, a subexp call can not be
performed although the back reference is possible.
8. Back reference
\n back reference by group number (n >= 1)
\k<name> back reference by group name
In the back reference by the multiplex definition name,
a subexp with a large number is referred to preferentially.
(When not matched, a group of the small number is referred to.)
* Back reference by group number is forbidden if named group is
defined in the pattern and ONIG_OPTION_CAPTURE_GROUP is not setted.
9. Subexp call ("Tanaka Akira special")
\g<name> call by group name
\g<n> call by group number (n >= 1)
* left-most recursive call is not allowed.
ex. (?<name>a|\g<name>b) => error
(?<name>a|b\g<name>c) => OK
* Call by group number is forbidden if named group is defined in the
pattern and ONIG_OPTION_CAPTURE_GROUP is not setted.
* If the option status of called group is different from calling
position then the group is option is effective.
ex. (?-i:\g<name>)(?i:(?<name>a)){0} match to "A"
10. Captured group
Behavior of the no-named group (...) changes with the following
conditions. (But named group is not changed.)
case 1. /.../ (named group is not used, no option)
(...) is treated as a captured group.
case 2. /.../g (named group is not used, 'g' option)
(...) is treated as a no-captured group (?:...).
case 3. /..(?<name>..)../ (named group is used, no option)
(...) is treated as a no-captured group (?:...).
numbered-backref/call is not allowed.
case 4. /..(?<name>..)../G (named group is used, 'G' option)
(...) is treated as a captured group.
numbered-backref/call is allowed.
where
g: ONIG_OPTION_DONT_CAPTURE_GROUP
G: ONIG_OPTION_CAPTURE_GROUP
('g' and 'G' options are argued in ruby-dev ML)
These options are not implemented in Ruby level.
-----------------------------
A-1. Syntax depend options
+ ONIG_SYNTAX_RUBY
(?m): dot(.) match newline
+ ONIG_SYNTAX_PERL and ONIG_SYNTAX_JAVA
(?s): dot(.) match newline
(?m): ^ match after newline, $ match before newline
A-2. Original extensions
+ hexadecimal digit char type \h, \H
+ named group (?<name>...)
+ named backref \k<name>
+ subexp call \g<name>, \g<group-num>
A-3. Lacked features compare with perl 5.8.0
+ [:word:]
+ \N{name}
+ \l,\u,\L,\U, \X, \C
+ (?{code})
+ (??{code})
+ (?(condition)yes-pat|no-pat)
* \Q...\E
This is effective on ONIG_SYNTAX_PERL and ONIG_SYNTAX_JAVA.
* \p{property}, \P{property}
This is effective on ONIG_SYNTAX_PERL and ONIG_SYNTAX_JAVA.
Alnum, Alpha, Blank, Cntrl, Digit, Graph, Lower,
Print, Punct, Space, Upper, XDigit, ASCII are supported.
Prefix 'Is' of property name is allowed in ONIG_SYNTAX_PERL only.
ex. \p{IsXDigit}.
Negation operator of property is supported in ONIG_SYNTAX_PERL only.
\p{^...}, \P{^...}
A-4. Differences with Japanized GNU regex(version 0.12) of Ruby
+ add hexadecimal digit char type (\h, \H)
+ add look-behind
(?<=fixed-char-length-pattern), (?<!fixed-char-length-pattern)
+ add possessive quantifier. ?+, *+, ++
+ add operations in character class. [], &&
('[' must be escaped as an usual char in character class.)
+ add named group and subexp call.
+ octal or hexadecimal number sequence can be treated as
a multibyte code char in character class if multibyte encoding
is specified.
(ex. [\xa1\xa2], [\xa1\xa7-\xa4\xa1])
+ allow the range of single byte char and multibyte char in character
class.
ex. /[a-<<any EUC-JP character>>]/ in EUC-JP encoding.
+ effect range of isolated option is to next ')'.
ex. (?:(?i)a|b) is interpreted as (?:(?i:a|b)), not (?:(?i:a)|b).
+ isolated option is not transparent to previous pattern.
ex. a(?i)* is a syntax error pattern.
+ allowed incompleted left brace as an usual string.
ex. /{/, /({)/, /a{2,3/ etc...
+ negative POSIX bracket [:^xxxx:] is supported.
+ POSIX bracket [:ascii:] is added.
+ repeat of look-ahead is not allowed.
ex. /(?=a)*/, /(?!b){5}/
+ Ignore case option is effective to numbered character.
ex. /\x61/i =~ "A"
+ In the range quantifier, the number of the minimum is omissible.
/a{,n}/ == /a{0,n}/
The simultanious abbreviation of the number of times of the minimum
and the maximum is not allowed. (/a{,}/)
+ /a{n}?/ is not a non-greedy operator.
/a{n}?/ == /(?:a{n})?/
+ Zero-length match in infinite repeat stops the repeat,
then changes of the capture group status are checked as stop
condition.
/(?:()|())*\1\2/ =~ ""
/(?:\1a|())*/ =~ "a"
A-5. Disabled functions by default syntax
+ capture history
(?@...) and (?@<name>...)
ex. /(?@a)*/.match("aaa") ==> [<0-1>, <1-2>, <2-3>]
see sample/listcap.c file.
A-6. Problems
+ Invalid encoding byte sequence is not checked in UTF-8.
* Invalid first byte is treated as a character.
/./u =~ "\xa3"
* Incomplete byte sequence is not checked.
/\w+/ =~ "a\xf3\x8ec"
// END
## 置換文字列シンタックス(フォーマット文字列) {replacement_string_syntax_format_strings}
正規表現の置換を使うとき、置換のための文字列は、キャプチャを参照したり、ケースフォールディングを実行したり、(キャプチャのレジスタに基づいて)条件付きの挿入をしたり、最小限のエスケープ文字列をサポートするフォーマット文字列として解釈されます。
### キャプチャ {captures}
キャプチャを参照するには、`$n`を使ってください(`n`はキャプチャレジスタの番号です)。`$0`はマッチ全体を意味します。
用例:
検索: <img src="(.*?)">
置換: <img src="$1" alt="$1">
### コードフォールディング {case_foldings}
`\u`か`\l`を先頭に追加することによってその次文字を大文字に変えたり、小文字に変えたりすることができます。これは、主に、その次の文字がキャプチャレジスタに由来するときに便利です。用例:
検索: (<a.*?>)(.*?)(</a>)
置換: $1\u$2$3
より長い文字列を`\U`や`\L`を使って大文字や小文字に変換できます。`E`を使って、コードフォールディングを無効にできます。用例:
検索: (<a.*?>)(.*?)(</a>)
置換: $1\U$2\E$3
### 条件付きの挿入 {conditional_insertions}
置換が何かがマッチしたかどうかによることがあります。これは、キャプチャ`«n»`がマッチしたら、`«insertion»`を挿入するために、`(?«n»:«insertion»)`を使えばできます。キャプチャ`«n»`がマッチしなかったら、`«otherwise»`を挿入するために`(?«n»:«insertion»:«otherwise»)`を使うこともできます。
キャプチャを条件付きにするには、`foo|(bar)|fud`のように変形の中に置いてください。もしくは、`(bar)?`のようにクエスチョンマークを加えることができます。`(.*)`ゼロ個の文字でもマッチしてしまうので、代わりに`(.+)?`を使ってください。
例えば、もし文字五文字以上の時に、8文字に切り詰めて、省略記号を挿入したい時には、、以下のようにします:
検索: (\w+(?:\W+\w+){,7})\W*(.+)?
置換: $1(?2:…)
ここではまず、それぞれの語が語ではない文字(スペースに)先行された、7つの語(`(?:\W+\w+){,7}`)が後にくる(`\w+`)にマッチさせます。その後、、任意で、キャプチャレジスタ2(`(.+)?`)へ(語ではない文字によって区切られた)それに続くものは何でも書き入れます。
置換はまず、マッチした8文字まで(`$1`)を挿入します。それからもしキャプチャ2が何かにしたら、省略記号(`(?2:…)`)を挿入します。
### エスケープコード {escape_codes}
ケースフォールディングのエスケープコードに加えて、`\n`で改行文字を、`\t`でタブ文字を、`\$`でドル文字を挿入できます。
|
JavaScript
|
UTF-8
| 9,909 | 2.515625 | 3 |
[] |
no_license
|
const _ = require('underscore');
const errors = require('web3-core-helpers').errors;
const Ws = require('@web3-js/websocket').w3cwebsocket;
const isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
let _btoa = null;
let parseURL = null;
if (isNode) {
_btoa = str => {
return Buffer.from(str).toString('base64');
};
const url = require('url');
if (url.URL) {
// Use the new Node 6+ API for parsing URLs that supports username/password
const newURL = url.URL;
parseURL = url => new newURL(url);
}
else {
// Web3 supports Node.js 5, so fall back to the legacy URL API if necessary
parseURL = require('url').parse;
}
}
else {
_btoa = btoa;
parseURL = url => new URL(url);
}
class WebsocketProvider {
constructor(url, options={}) {
if (!Ws) {
throw new Error('websocket is not available');
}
this.responseCallbacks = {};
this.notificationCallbacks = [];
this._customTimeout = options.timeout;
// The w3cwebsocket implementation does not support Basic Auth
// username/password in the URL. So generate the basic auth header, and
// pass through with any additional headers supplied in constructor
const parsedURL = parseURL(url);
this.headers = options.headers || {};
this.url = url;
this.protocol = options.protocol || undefined;
if (parsedURL.username && parsedURL.password) {
headers.authorization = 'Basic ' + _btoa(parsedURL.username + ':' + parsedURL.password);
}
// Allow a custom client configuration
this.clientConfig = options.clientConfig;
// Allow a custom request options
// https://github.com/theturtle32/WebSocket-Node/blob/master/docs/WebSocketClient.md#connectrequesturl-requestedprotocols-origin-headers-requestoptions
this.requestOptions = options.requestOptions;
// When all node core implementations that do not have the
// WHATWG compatible URL parser go out of service this line can be removed.
if (parsedURL.auth) {
headers.authorization = 'Basic ' + _btoa(parsedURL.auth);
}
this.createConnection();
// make property `connected` which will return the current connection status
Object.defineProperty(this, 'connected', {
get: () => this.connection && this.connection.readyState === this.connection.OPEN,
enumerable: true,
});
this.getAccessToken = options.getAccessToken;
this.syncInterval = options.syncInterval || 60000 // 1 min
return new Promise(async (resolve, reject) => {
try {
await this._syncAuth();
resolve(this);
}
catch(error) {
reject(error)
}
});
}
createConnection() {
this.connection = new Ws(
this.url,
this.protocol,
undefined,
this.headers,
this.requestOptions,
this.clientConfig
);
this.addDefaultEvents();
this.connection.onmessage = this.onmessage.bind(this);
}
async _refreshToken() {
try {
const token = await this.getAccessToken();
this.headers['Authorization'] = `Bearer ${token}`;
this.createConnection();
this._tick();
}
catch(error) {
throw new Error('Cannot get a new access token');
}
}
async _syncAuth() {
if(this.getAccessToken !== null) {
try {
await this._refreshToken();
}
catch {
this._tick(10000); // retry in 10 secs
}
}
}
_tick(ts=this.syncInterval) {
setTimeout(() => this._syncAuth(), ts)
}
onmessage(e) {
const data = (typeof e.data === 'string') ? e.data : '';
this._parseResponse(data).forEach(result => {
let id = null;
// get the id which matches the returned id
if(_.isArray(result)) {
result.forEach(load => {
if(this.responseCallbacks[load.id]) {
id = load.id;
}
});
}
else {
id = result.id;
}
// notification
if(!id && result && result.method && result.method.indexOf('_subscription') !== -1) {
this.notificationCallbacks.forEach(callback => {
if(_.isFunction(callback)) {
callback(result);
}
});
// fire the callback
}
else if(this.responseCallbacks[id]) {
this.responseCallbacks[id](null, result);
delete this.responseCallbacks[id];
}
});
}
addDefaultEvents() {
this.connection.onerror = this._timeout;
this.connection.onclose = () => {
this._timeout();
// reset all requests and callbacks
this.reset();
};
}
_parseResponse(data) {
const returnValues = [];
// DE-CHUNKER
const dechunkedData = data
.replace(/\}[\n\r]?\{/g,'}|--|{') // }{
.replace(/\}\][\n\r]?\[\{/g,'}]|--|[{') // }][{
.replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{
.replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{
.split('|--|');
dechunkedData.forEach(data => {
// prepend the last chunk
if(this.lastChunk) {
data = this.lastChunk + data;
}
let result = null;
try {
result = JSON.parse(data);
}
catch(e) {
this.lastChunk = data;
// start timeout to cancel all requests
clearTimeout(this.lastChunkTimeout);
this.lastChunkTimeout = setTimeout(() => {
this._timeout();
throw errors.InvalidResponse(data);
}, 1000 * 15);
return;
}
// cancel timeout and set chunk to null
clearTimeout(this.lastChunkTimeout);
this.lastChunk = null;
if(result) {
returnValues.push(result);
}
});
return returnValues;
}
_addResponseCallback(payload, callback) {
const id = payload.id || payload[0].id;
const method = payload.method || payload[0].method;
this.responseCallbacks[id] = callback;
this.responseCallbacks[id].method = method;
// schedule triggering the error response if a custom timeout is set
if (this._customTimeout) {
setTimeout(() => {
if (this.responseCallbacks[id]) {
this.responseCallbacks[id](errors.ConnectionTimeout(this._customTimeout));
delete this.responseCallbacks[id];
}
}, this._customTimeout);
}
}
_timeout() {
for(let key in this.responseCallbacks) {
if(this.responseCallbacks.hasOwnProperty(key)){
this.responseCallbacks[key](errors.InvalidConnection('on WS'));
delete this.responseCallbacks[key];
}
}
}
_hasTokenExpired() {
const universalBtoa = b64Encoded => {
try {
return atob(b64Encoded);
} catch (err) {
return Buffer.from(b64Encoded, 'base64').toString();
}
};
const base64Url = this._token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
universalBtoa(base64)
.split('')
.map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
.join('')
);
const {exp} = JSON.parse(jsonPayload);
return Math.floor(Date.now() / 1000) > exp;
}
async send(payload, callback) {
if(this._hasTokenExpired()) {
await this._refreshToken();
}
if (this.connection.readyState === this.connection.CONNECTING) {
setTimeout(() => {
this.send(payload, callback);
}, 10);
return;
}
// try reconnect, when connection is gone
// if(!this.connection.writable)
// this.connection.connect({url: this.url});
if (this.connection.readyState !== this.connection.OPEN) {
console.error('connection not open on send()');
if (typeof this.connection.onerror === 'function') {
this.connection.onerror(new Error('connection not open'));
}
else {
console.error('no error callback');
}
callback(new Error('connection not open'));
return;
}
this.connection.send(JSON.stringify(payload));
this._addResponseCallback(payload, callback);
}
on(type, callback) {
if(typeof callback !== 'function') {
throw new Error('The second parameter callback must be a function.');
}
switch(type){
case 'data':
this.notificationCallbacks.push(callback);
break;
case 'connect':
this.connection.onopen = callback;
break;
case 'end':
this.connection.onclose = callback;
break;
case 'error':
this.connection.onerror = callback;
break;
}
}
removeListener(type, callback) {
switch(type){
case 'data':
this.notificationCallbacks.forEach((cb, index) => {
if(cb === callback)
this.notificationCallbacks.splice(index, 1);
});
break;
// TODO remvoving connect missing
// default:
// this.connection.removeListener(type, callback);
// break;
}
}
removeAllListeners(type) {
switch(type){
case 'data':
this.notificationCallbacks = [];
break;
case 'connect':
this.connection.onopen = null;
break;
case 'end':
this.connection.onclose = null;
break;
case 'error':
this.connection.onerror = null;
break;
default:
// this.connection.removeAllListeners(type);
break;
}
}
reset() {
this._timeout();
this.notificationCallbacks = [];
// this.connection.removeAllListeners('error');
// this.connection.removeAllListeners('end');
// this.connection.removeAllListeners('timeout');
this.addDefaultEvents();
}
disconnect() {
if (this.connection) {
this.connection.close();
}
}
supportsSubscriptions() {
return true;
}
}
module.exports = WebsocketProvider;
|
Swift
|
UTF-8
| 459 | 2.953125 | 3 |
[] |
no_license
|
import Foundation
public extension Data {
func toInt<I: FixedWidthInteger>(_ format: I.Type) -> Int {
return Int(converted() as I)
}
var toBool: Bool { converted() }
private func converted<T>() -> T {
withUnsafeBytes { $0.load(as: T.self) }
}
var toString: String {
String(data: self, encoding: .utf8)!
}
}
public extension Date {
static var now: Date { Date() }
var elapsedDuration: TimeInterval { Date.now.timeIntervalSince(self) }
}
|
Python
|
UTF-8
| 977 | 2.796875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import csv
import sys
import math
import matplotlib.pyplot as plt
import numpy as np
if (len(sys.argv) != 2):
print "Usage: " + sys.argv[0] + "file.csv"
sys.exit()
try:
csvfile = open(sys.argv[1], 'rb')
except:
print "Error while trying to open " + sys.argv[1]
sys.exit()
reader = csv.reader(csvfile, delimiter=',')
first = False
array = []
for r in reader:
if (first == False):
fields = r
first = True
else:
array.append(r)
ar = np.array(array)
print ar
plt.rcdefaults()
fig, ax = plt.subplots()
ar[ar == ''] = "nan" # TODO ATTENTION AUX NANS
astronomy = ar[: , fields.index("Astronomy")].astype(float)
defense = ar[: , fields.index("Defense Against the Dark Arts")].astype(float)
plt.scatter(astronomy, defense, s=0.5)
print (len(astronomy))
print (len(defense))
print "here"
ax.set_ylabel('Defense Against The Dark Arts')
ax.set_xlabel('Astronomy')
ax.set_title('Quelles sont les deux features qui sont semblables ?')
plt.show()
|
Java
|
UTF-8
| 7,287 | 1.882813 | 2 |
[
"MIT"
] |
permissive
|
package com.example.a1news;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.util.Pair;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
//import android.widget.SearchView;
import androidx.appcompat.widget.SearchView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.a1news.api.ApiClient;
import com.example.a1news.api.ApiInterface;
import com.example.a1news.models.Article;
import com.example.a1news.models.News;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
public static final String API_KEY = "enter your Api key here";
public static final String KEY_WORD = "Covid";
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private List<Article> articles = new ArrayList<>();
private Adapter adapter;
private String Tag = MainActivity.class.getSimpleName();
private TextView topHeadLine;
private SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
topHeadLine = findViewById(R.id.topHeadLine);
recyclerView = findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(false);
onLoadingSwipeRefresh("");
}
public void loadJson(final String keyword){
topHeadLine.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(true);
ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
String country = Utils.getCountry();
String language = Utils.getLanguage();
Call<News> call;
if(keyword.length() > 0){
call = apiInterface.getNewsSearch(keyword, language, "publishedAt", API_KEY);
}else{
call = apiInterface.getNews(country, KEY_WORD, API_KEY);
}
call.enqueue(new Callback<News>() {
@Override
public void onResponse(Call<News> call, Response<News> response) {
if (response.isSuccessful() && response.body().getArticle()!=null){
if(!articles.isEmpty()){
articles.clear();
}
articles = response.body().getArticle();
adapter = new Adapter(articles, MainActivity.this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
initListener();
topHeadLine.setVisibility(View.VISIBLE);
swipeRefreshLayout.setRefreshing(false);
} else{
topHeadLine.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(MainActivity.this, "No Result.", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<News> call, Throwable t) {
topHeadLine.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void initListener(){
adapter.setOnItemClickListener(new Adapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
ImageView imageView = view.findViewById(R.id.img);
Intent intent = new Intent(MainActivity.this, NewsDetailActivity.class);
Article article = articles.get(position);
intent.putExtra("url", article.getUrl());
intent.putExtra("title", article.getTitle());
intent.putExtra("img", article.getUrlToImage());
intent.putExtra("date", article.getPublishedAt());
intent.putExtra("source", article.getSource().getName());
intent.putExtra("author", article.getAuthor());
Pair<View, String> pair = Pair.create((View) imageView, ViewCompat.getTransitionName(imageView));
ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(
MainActivity.this,
pair
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
startActivity(intent, optionsCompat.toBundle());
} else {
startActivity(intent);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
//final SearchView searchView = (SearchView) menu.findItem(R.id.action_search);
MenuItem menuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) menuItem.getActionView();
MenuItem searchMenuItem = menu.findItem(R.id.action_search);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setQueryHint("Search latest News...");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
if (query.length() > 2){
onLoadingSwipeRefresh(query);
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchMenuItem.getIcon().setVisible(false, false);
return true;
}
@Override
public void onRefresh() {
loadJson("");
}
private void onLoadingSwipeRefresh(final String keyword){
swipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
loadJson(keyword);
}
}
);
}
}
|
Python
|
UTF-8
| 234 | 3.65625 | 4 |
[] |
no_license
|
user_sec = int(input("Введите количество секунд: "))
hours = user_sec // 3600
minutes = (user_sec - hours * 3600) // 60
seconds = user_sec - hours * 3600 - minutes * 60
print(hours, minutes, seconds, sep=":")
|
SQL
|
UTF-8
| 517 | 3.25 | 3 |
[] |
no_license
|
CREATE TABLE [scc].[Parent] (
[ParentID] SMALLINT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR (70) NULL,
[MiddleName] NVARCHAR (70) NULL,
[LastName] NVARCHAR (70) NULL,
[PhoneNumber] NVARCHAR (50) NULL,
[Identification] BIT NULL,
[PersonID] INT NULL,
CONSTRAINT [PK_scc_Parent] PRIMARY KEY CLUSTERED ([ParentID] ASC),
CONSTRAINT [FK_scc_Parent_Person] FOREIGN KEY ([PersonID]) REFERENCES [scc].[Person] ([PersonID])
);
|
TypeScript
|
UTF-8
| 3,656 | 3.53125 | 4 |
[
"MIT"
] |
permissive
|
import { getHashBuffer } from '@casual-simulation/crypto';
/**
* Defines an interface for normal JS objects that represent Atom IDs.
*/
export interface StorableAtomId {
site: number;
timestamp: number;
priority: number;
}
/**
* Defines an ID for an atom.
*
* 16 bytes per ID. (each number is 8 bytes)
*/
export interface AtomId {
/**
* The ID of the originator of this atom.
*/
site: number;
/**
* The lamport timestamp of this atom.
*/
timestamp: number;
/**
* The priority of this atom.
* If specified, causes this atom to sort to the beginning
* on a chain of atoms that share the same cause.
*/
priority: number;
}
/**
* Determines if the two given IDs equal each other.
* @param first
* @param second
*/
export function idEquals(first: AtomId, second: AtomId) {
return (
first === second ||
(first &&
second &&
second.site === first.site &&
second.timestamp === first.timestamp &&
second.priority === first.priority)
);
}
/**
* Creates a new Atom ID.
* @param site
* @param timestamp
* @param priority
*/
export function atomId(
site: number,
timestamp: number,
priority: number = 0
): AtomId {
return {
site,
timestamp,
priority,
};
}
/**
* Defines an interface for an atom operation.
*/
export interface AtomOp {
type: number;
}
/**
* Defines an atom.
* That is, an object that represents a unique operation paired with a unique cause.
* The cause is effectively the parent of this atom because without it the atom logically could not exist.
*
* 32 bytes + value size per atom.
*/
export interface Atom<T extends AtomOp> {
/**
* The ID of this atom.
*/
id: AtomId;
/**
* The ID of this atom's parent.
*/
cause: AtomId;
/**
* The operation that the atom contains.
*/
value: T;
/**
* The checksum for this atom.
* Used to verify that a atom is valid if a signature is not provided.
*/
checksum: number;
/**
* The base 64 encoded signature that can be used to verify that the atom
* was created by the correct site.
* If null, then no signature is available.
*/
signature?: string;
}
/**
* Defines an interface that represents an atom that has been archived.
*/
export interface ArchivedAtom {
/**
* The key that relates this atom to a particular tree/weave.
*/
key: string;
/**
* The atom that was archived.
*/
atom: Atom<any>;
}
/**
* Creates a new atom.
* @param id
* @param cause
* @param value
*/
export function atom<T extends AtomOp>(
id: AtomId,
cause: AtomId,
value: T
): Atom<T> {
const hash = getHashBuffer([id, cause, value]);
return {
id,
cause,
value,
// Read only 32 bits of the hash.
// This should be good enough to prevent collisions for weaves
// of up to ~2 billion atoms instead of never.
checksum: hash.readUInt32BE(0),
};
}
/**
* Verifies that the given atom matches its own checksum.
* @param atom The atom to check.
*/
export function atomMatchesChecksum<T extends AtomOp>(atom: Atom<T>) {
const hash = getHashBuffer([atom.id, atom.cause, atom.value]);
const checksum = hash.readUInt32BE(0);
return checksum === atom.checksum;
}
/**
* Converts the given atom ID into a string that is suitable for
* storage.
* @param id The ID.
*/
export function atomIdToString(id: AtomId): string {
return `${id.site}@${id.timestamp}:${id.priority}`;
}
|
Java
|
UTF-8
| 3,340 | 2.03125 | 2 |
[] |
no_license
|
package com.minpostel.mvc.entities;
import javax.persistence.*;
import java.util.Date;
import java.io.Serializable;
@Entity
@Table(name = "archivePapier")
public class ArchivePapier implements Serializable {
@Id
@GeneratedValue
private Long archivePapierID;
private int nbrePage;
private int nbreFeuille;
private String objet;
private String numSignature;
private Date dateSignature;
private String signature;
private String premierNom;
private String dernierNom;
private String sort;
private String motifSort;
private String numOrdre;
private String description;
private String motsCles;
private String photo;
@ManyToOne
@JoinColumn(name = "utilisateurID")
private Utilisateur utilisateur;
@ManyToOne
@JoinColumn(name = "natureID")
private Nature nature;
@ManyToOne
@JoinColumn(name = "dptID")
private Departement departement;
public Long getArchivePapierID() {
return archivePapierID;
}
public void setArchivePapierID(Long archivePapierID) {
this.archivePapierID = archivePapierID;
}
public int getNbrePage() {
return nbrePage;
}
public void setNbrePage(int nbrePage) {
this.nbrePage = nbrePage;
}
public int getNbreFeuille() {
return nbreFeuille;
}
public void setNbreFeuille(int nbreFeuille) {
this.nbreFeuille = nbreFeuille;
}
public String getObjet() {
return objet;
}
public void setObjet(String objet) {
this.objet = objet;
}
public String getNumSignature() {
return numSignature;
}
public void setNumSignature(String numSignature) {
this.numSignature = numSignature;
}
public Date getDateSignature() {
return dateSignature;
}
public void setDateSignature(Date dateSignature) {
this.dateSignature = dateSignature;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getPremierNom() {
return premierNom;
}
public void setPremierNom(String premierNom) {
this.premierNom = premierNom;
}
public String getDernierNom() {
return dernierNom;
}
public void setDernierNom(String dernierNom) {
this.dernierNom = dernierNom;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getMotifSort() {
return motifSort;
}
public void setMotifSort(String motifSort) {
this.motifSort = motifSort;
}
public String getNumOrdre() {
return numOrdre;
}
public void setNumOrdre(String numOrdre) {
this.numOrdre = numOrdre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMotsCles() {
return motsCles;
}
public void setMotsCles(String motsCles) {
this.motsCles = motsCles;
}
public String getPhoto() {
return photo;
}
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
public Nature getNature() {
return nature;
}
public void setNature(Nature nature) {
this.nature = nature;
}
public Departement getDepartement() {
return departement;
}
public void setDepartement(Departement departement) {
this.departement = departement;
}
public void setPhoto(String photo) {
this.photo = photo;
}
}
|
Python
|
UTF-8
| 1,278 | 3.65625 | 4 |
[] |
no_license
|
#1 p = open('text.txt', 'r') # открыть в режиме чтение
# a = p.read()
# print(a)
# p.close()
#2 with open('text1.txt', 'r') as a: #построчно читать файл и сохранять его в виде списка
# b = a.readlines()
# print(b)
#3 p = open('text.txt', 'r') # открыть в режиме чтение cтрока за строкой читала файл
# for line in p:
# print(line)
#4 with open('text.txt') as f: #найти самые длинные слова.
# a = f.read().split()
# print(max(a, key=len))
#5 with open('text1.txt') as a: #подсчета количества строк в текстовом файле
# print(len(a.readlines()))
#6 s = ['Aito','Kirill','Taalai','Umut'] #перевести список по строкам
# s = [i + '\n' for i in s]
# with open('text1.txt','w') as f:
# f.writelines(s)
# # print(f.read())
#7 p = open('text.txt', 'w') # открыть в режиме чтение
# p.close()
# print('Возвращает True если файл был закрыт: ', p.closed)
#8 with open('text.txt') as f: #подсчета количества слов в текстовом файле
# print(len(sorted(f.read().split())))
|
C++
|
UTF-8
| 3,435 | 2.90625 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Form.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ashypilo <ashypilo@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/08 12:34:14 by ashypilo #+# #+# */
/* Updated: 2019/10/08 15:20:35 by ashypilo ### ########.fr */
/* */
/* ************************************************************************** */
#include "Form.hpp"
Form::Form(std::string name, int get_sign, int get_execute):name(name), grade_sign(get_sign), grade_execute(get_execute)
{
if (this->grade_execute > 150 || this->grade_sign > 150)
throw Form::GradeTooHighException();
else if (this->grade_execute < 1 || this->grade_sign < 1)
throw Form::GradeTooLowException();
this->indicat = 0;
return ;
}
Form::Form(const Form& over):name(over.name), grade_sign(over.grade_sign), grade_execute(over.grade_execute)
{
*this = over;
return ;
}
Form::~Form()
{
return ;
}
Form& Form::operator=(const Form& over)
{
if (this != &over)
{
*this = over;
this->indicat = over.indicat;
}
return (*this);
}
void Form::beSigned(Bureaucrat& bur)
{
if (bur.getGrade() > this->grade_sign)
throw Form::GradeTooLowException();
this->indicat = 1;
}
/*****************************************/
Form::GradeTooHighException::GradeTooHighException()
{
return ;
}
Form::GradeTooHighException::GradeTooHighException(const GradeTooHighException& over)
{
*this = over;
return ;
}
Form::GradeTooHighException::~GradeTooHighException() throw()
{
return ;
}
Form::GradeTooHighException& Form::GradeTooHighException::operator=(const Form::GradeTooHighException& over)
{
exception::operator=(over);
return (*this);
}
const char* Form::GradeTooHighException::what() const throw()
{
return ("Too high grade");
}
Form::GradeTooLowException::GradeTooLowException()
{
return ;
}
Form::GradeTooLowException::GradeTooLowException(const GradeTooLowException& over)
{
*this = over;
return ;
}
Form::GradeTooLowException::~GradeTooLowException() throw()
{
return ;
}
Form::GradeTooLowException& Form::GradeTooLowException::operator=(const Form::GradeTooLowException& over)
{
exception::operator=(over);
return (*this);
}
const char* Form::GradeTooLowException::what() const throw()
{
return ("Too low grade");
}
/****************************************/
std::string Form::getName() const
{
return (this->name);
}
bool Form::getIndicat() const
{
return (this->indicat);
}
int Form::getGrade_sign() const
{
return (this->grade_sign);
}
int Form::getGrade_execute() const
{
return (this->grade_execute);
}
std::ostream& operator<<(std::ostream &out, const Form &f)
{
out << f.getName() + " has signature status" << f.getIndicat() << "Grade sign = " << f.getGrade_sign() << " and Grade execute = " << f.getGrade_execute() << std::endl;
return (out);
}
|
C#
|
UTF-8
| 4,464 | 2.609375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Windows;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using DFA2.Model;
using DFA2.ViewModel;
namespace DFA2
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
List<string> inputStrings = new List<string>();
string Text = "";
DirectoryInfo dir = new DirectoryInfo(@"..\..\..");
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
string path = dir.FullName + "\\parsData.txt";
try
{
using (StreamReader streamReader = new StreamReader(path, System.Text.Encoding.Default))
{
string tmpStr = "";
while ((tmpStr = streamReader.ReadLine()) != null)
{
inputStrings.Add(tmpStr);
}
using (StreamReader streamReader1 = new StreamReader(path, System.Text.Encoding.Default))
{
Text += streamReader1.ReadToEnd();
}
fileDataTb.ItemsSource = inputStrings;
}
}
catch (Exception ex)
{
MessageBox.Show("ошибка чтения файла, содержимое не загружено " + ex.Message);
}
}
private void parseStrRb_Checked(object sender, RoutedEventArgs e)
{
inputStringTb.IsEnabled = true;
if (startParseAllBtn != null)
startParseAllBtn.IsEnabled = false;
if (startParseStringBtn != null)
startParseStringBtn.IsEnabled = true;
}
private void parseAllRb_Checked(object sender, RoutedEventArgs e)
{
if (startParseAllBtn != null)
startParseAllBtn.IsEnabled = true;
if (startParseStringBtn != null)
startParseStringBtn.IsEnabled = false;
}
private void parseStrRb_Unchecked(object sender, RoutedEventArgs e)
{ }
private void startParseAllBtn_Click(object sender, RoutedEventArgs e)
{
DfaViewModel dfa = new DfaViewModel();
if (dfa.Err != "")
MessageBox.Show(dfa.Err);
Stopwatch timer = new Stopwatch();
timer.Start();
dfa.StartParse(Text);
outputDg.ItemsSource = dfa.outputUnits;
timer.Stop();
testRes.Text = "время выполнения - " + (timer.ElapsedMilliseconds).ToString("E") + " Мс";
timer.Reset();
//if (dfa.outputUnits != null)
// SaveData(dfa.outputUnits, "AllText");
}
private void startParseStringBtn_Click(object sender, RoutedEventArgs e)
{
Stopwatch timer = new Stopwatch();
timer.Start();
//Dfa dfa = new Dfa();
//if (inputStringTb.Text.Length > 0)
//{
// dFA.Start(inputStringTb.Text);
// outputDg1.ItemsSource = dFA.OutputUnits;
//}
//timer.Stop();
//testRes.Text = "время выполнения - " + (timer.ElapsedMilliseconds).ToString("E") + " Мс";
//timer.Reset();
//if (dFA.OutputUnits != null)
// SaveData(dFA.OutputUnits, "Line");
}
private void SaveData(List<OutputUnit> results, string fileName)
{
string uriSL = dir.FullName + "\\" + fileName + "ParsResult.xml";
try
{
using (Stream fStream = new FileStream(uriSL, FileMode.Create, FileAccess.Write, FileShare.None))
{
XmlSerializer xmlFormat = new XmlSerializer(typeof(List<OutputUnit>));
xmlFormat.Serialize(fStream, results);
MessageBox.Show("результат разбора записан в файл по адресу " + uriSL);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}
|
JavaScript
|
UTF-8
| 2,778 | 3.0625 | 3 |
[] |
no_license
|
// Written by Funnbot on November 23, 2018
const Logger = require("./Util/Logger");
const path = require("path");
// New promise based api for fs
const fs = require("bluebird").promisifyAll(require("fs"));
// Database object cache
let cache = {};
let location; // = "database.json"
// For database concurency, only one write can be active at a time,
let isWriteEnqueued = false;
let isWriting = false;
class Database {
/**
* Load the database into memory
* @param {String} _location
* @static
*/
static async load(_location) {
location = path.join(__dirname, "..", _location);
try {
// Attempt to read into cache
const rawData = await fs.readFileAsync(location);
// If its a new db file dont require it to be json;
if (rawData.length == 0) cache = {};
else cache = JSON.parse(rawData);
} catch (err) {
Logger.fatal("DB Load", "Check if it exists, has read/write permission, and the JSON is valid. File: " + location, err);
}
}
/**
* Get a value by its key
* @static
* @param {String} key
*/
static get(key) {
if (!cache.hasOwnProperty(key)) return null;
return cache[key];
}
/**
* Set a value by its key
* @param {String} key
* @param {Any} value
* @returns
*/
static async set(key, value) {
cache[key] = value;
// Don't trigger another if it will write
if (isWriteEnqueued) return;
Database.write()
}
/**
* Access the entire cache
* @static
* @param {Function} predicate(cache)
* @returns
*/
static find(predicate) {
return predicate(cache);
}
/**
* Write the cache to the json file
* @async
* @static
* @private
*/
static async write() {
// Who needs fancy thread blocking when you can java
// I dont know if we even need to handle concurrency, however if there a multiple writes during a write, it will only do 2 instead of 40
if (isWriting) {
isWriteEnqueued = true;
return;
}
if (!cache) Logger.err("DB Write", "Cache was deleted, preventing overwrite.");
try {
let data = JSON.stringify(cache);
isWriting = true;
await fs.writeFileAsync(location, data);
isWriting = false;
Logger.info("DB Write", "Write successful");
} catch (err) {
Logger.error("DB Write", "Did you delete the database file? Do I still have permission?");
}
if (isWriteEnqueued) {
isWriteEnqueued = false;
Database.write();
}
}
}
module.exports = Database;
|
C++
|
UTF-8
| 1,608 | 3 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
#define ll long long
using namespace std;
char c[3][3];
bool isWinV(char x, int col) {
int cnt = 0;
for (int i = 0; i < 3; i++) {
if (c[i][col] == x) {
cnt++;
}
}
return (cnt == 3);
}
bool isWinH(char x, int row) {
int cnt = 0;
for (int i = 0; i < 3; i++) {
if (c[row][i] == x) {
cnt++;
}
}
return (cnt == 3);
}
bool isWinDa(char x) {
int cnt = 0;
for (int i = 0; i < 3; i++) {
if (c[i][i] == x) {
cnt++;
}
}
return (cnt == 3);
}
bool isWinDb(char x) {
int cnt = 0;
for (int i = 0; i < 3; i++) {
if (c[2-i][i] == x) {
cnt++;
}
}
return (cnt == 3);
}
void solve() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = '.';
}
}
string aa, bb, cc;
cin >> aa >> bb >> cc;
for (int i = 0; i < 3; i++) {
c[0][i] = aa[i];
}
for (int i = 0; i < 3; i++) {
c[1][i] = bb[i];
}
for (int i = 0; i < 3; i++) {
c[2][i] = cc[i];
}
for (int i = 0; i < 3; i++) {
if (isWinH('O', i)) {
cout << "O\n";
return;
}
if (isWinH('X', i)) {
cout << "X\n";
return;
}
if (isWinH('+', i)) {
cout << "+\n";
return;
}
if (isWinV('O', i)) {
cout << "O\n";
return;
}
if (isWinV('X', i)) {
cout << "X\n";
return;
}
if (isWinV('+', i)) {
cout << "+\n";
return;
}
}
if (isWinDa('X') || isWinDb('X')) {
cout << "X\n";
return;
}
if (isWinDa('O') || isWinDb('O')) {
cout << "O\n";
return;
}
if (isWinDa('+') || isWinDb('+')) {
cout << "+\n";
return;
}
cout << "DRAW\n";
}
int main () {
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
|
C++
|
UTF-8
| 386 | 2.890625 | 3 |
[] |
no_license
|
#include <cstdio>
#include "FJ64_16k.h" // For a fast `is_prime` function: http://ceur-ws.org/Vol-1326/020-Forisek.pdf
int main() {
double ans = 0.5;
for (uint64_t p = 0; ; ++p) {
if (p % 1000000 == 0) {
printf("%lld %.9f\n", p, ans);
}
if (!is_prime(p)) continue;
if (p % 3 == 1) ans *= (p - 2.0) / (p - 1.0);
if (p % 3 == 2) ans *= p / (p - 1.0);
}
}
|
Java
|
UTF-8
| 1,516 | 3.46875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.zingking.javadesignmode.mediator;
/**
* Copyright © 2018, www.zingking.cn All Rights Reserved.
* Create by Z.kai 2019/1/21
* Describe: 具体中介者,协调各同事类行为
*/
public class Mediator extends AbstractMediator {
private static final String TAG = "Mediator";
@Override
public void buyComputer(int number) {
// 购买电脑数量需要根据销售情况确认
int saleState = getSale().getSaleState();
// 销售良好,正常采购
if (saleState > 80) {
System.out.println(TAG + ": 购入" + number + "台。");
getStock().increase(number);
}
// 销售不好,折半采购
else {
System.out.println(TAG + ": 购入" + number / 2 + "台。");
getStock().increase(number / 2);
}
}
@Override
public void sellComputer(int number) {
System.out.println(TAG + ": 销售" + number + "台。");
// 销售电脑需要判断库存是否充足
if (getStock().getStockNumber() < number) {
getPurchase().buyIbmComputer(number);
}
getStock().decrease(number);
}
@Override
public void clearStock() {
System.out.println(TAG + ": 清仓处理。");
getSale().offSale();
getPurchase().refuseBuyIbm();
}
@Override
public void offSale() {
System.out.println(TAG + ": 折价销售。");
getStock().decrease(getStock().getStockNumber());
}
}
|
C#
|
UTF-8
| 2,222 | 2.625 | 3 |
[] |
no_license
|
using OpenQA.Selenium;
using System;
namespace EbayAutoFramework.Webdriver
{
public class WebDriverContext
{
private static WebDriverContext _instance;
private IWebDriver _webDriver = null;
private WebDriverContext()
{
}
public static WebDriverContext getInstance()
{
if (_instance == null)
{
_instance = new WebDriverContext();
}
return _instance;
}
public IWebDriver getWebDriver()
{
if (_webDriver == null)
{
createSession();
}
return _webDriver;
}
public void createSession()
{
if (_webDriver != null)
{
cleanUp();
}
String browser = "chrome";
_webDriver = WebDriverFactory.createWebDriver(browser);
}
private void cleanUp()
{
if (_webDriver != null)
{
_webDriver.Close();
_webDriver.Quit();
// TODO: Investigate how to close orphaned chromedriver.exe.
// This code works if the tests are run sequentially, but not in parallel.
/*Process p;
try
{
String command = "";
if (Platform.CurrentPlatform.IsPlatformType (Platform))
{
command = "TASKKILL /F /IM chromedriver.exe";
}
else if (Platform.getCurrent().is (Platform.MAC))
{
command = "pkill -9 chromedriver";
}
p = Runtime.getRuntime().exec(command);
p.waitFor();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
_webDriver = null;*/
}
}
}
}
|
Markdown
|
UTF-8
| 3,552 | 3.09375 | 3 |
[] |
no_license
|
# piTunes monorepo [](https://github.com/bernhardfritz/pitunes/actions/workflows/ci.yml)
<img src="pitunes.png" align="right">
Host your music yourself and stream it from anywhere using a web browser.
* Password protected
* Encrypted HTTPS traffic
* ID3 tag support
* Dark mode
[](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/bernhardfritz/pitunes/master/docker-compose.pwd.yml)
## Supported platforms
| Platform | Release |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| :penguin: | https://github.com/bernhardfritz/pitunes/releases/latest/download/pitunes-x86_64-unknown-linux-musl.tar.xz |
| :strawberry: | <table><tbody><tr><td>RPi 1</td><td>https://github.com/bernhardfritz/pitunes/releases/latest/download/pitunes-arm-unknown-linux-musleabihf.tar.xz</td></tr><tr><td>RPi 2+</td><td>https://github.com/bernhardfritz/pitunes/releases/latest/download/pitunes-armv7-unknown-linux-musleabihf.tar.xz</td></tr></tbody></table> |
| :whale: | https://hub.docker.com/r/bernhardfritz/pitunes |
## Quickstart
### Installation
```bash
wget <url> # download release
tar -xf <filename> # extract archive
./pitunes # start server
```
### Login
Enter server address in your web browser and login:
Username: `admin`
Password: `password`
### Change default password
Navigate to Graph*i*QL and execute:
Query:
```graphql
mutation UpdateUserMutation($username: String!, $input: UserInput!) {
updateUser(username: $username, input: $input)
}
```
Query variables:
```json
{
"username": "admin",
"input": {
"password": "something"
}
}
```
Close and reopen browser after changing password.
## Screenshots


|
Java
|
UTF-8
| 2,106 | 1.890625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.service.Impl;
import java.util.List;
import org.apache.catalina.util.CharsetMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.controller.LoginController;
import com.mapper.pojo.Cart;
import com.mapper.pojo.CartExample;
import com.mapper.pojo.CartKey;
import com.onlineshop.mapper.CartMapper;
import com.service.ICartService;
@Service
public class CartServiceImpl implements ICartService {
@Autowired
private CartMapper CartMapper;
public int selectCartByGid(Cart car) {
for (int i = 1; i < LoginController.cart.size(); i ++)
{
if (LoginController.cart.get(i).getCid() == car.getCid())
return i;
}
return -1;
}
public int deleteByExample(CartExample example) {
// TODO Auto-generated method stub
return CartMapper.deleteByExample(example);
}
public int insert(Cart record) {
// TODO Auto-generated method stub
return CartMapper.insert(record);
}
public int insertSelective(Cart record) {
// TODO Auto-generated method stub
return CartMapper.insertSelective(record);
}
public List<Cart> selectByExample(CartExample example) {
// TODO Auto-generated method stub
return CartMapper.selectByExample(example);
}
// public int deleteByPrimaryKey(Integer cid) {
// // TODO Auto-generated method stub
// return CartMapper.deleteByPrimaryKey(cid);
// }
// public Cart selectByPrimaryKey(Integer cid) {
// // TODO Auto-generated method stub
// return CartMapper.selectByPrimaryKey(cid);
// }
public int updateByPrimaryKey(Cart record) {
// TODO Auto-generated method stub
return CartMapper.updateByPrimaryKey(record);
}
public Cart selectByPrimaryKey(CartKey key) {
// TODO Auto-generated method stub
return CartMapper.selectByPrimaryKey(key);
}
public List<Cart> selectByPrimaryusername(String username) {
// TODO Auto-generated method stub
return CartMapper.selectByPrimaryusername(username);
}
public int deleteByPrimaryKey(CartKey key) {
// TODO Auto-generated method stub
return CartMapper.deleteByPrimaryKey(key);
}
}
|
Markdown
|
UTF-8
| 33,180 | 2.65625 | 3 |
[] |
no_license
|
# 大标题
## 二级标题
### 三级标题
* 记住*的作用
- 记住-的作用
# Html 部分
### 7月17日
* 注册 github
* 开始使用Markdown格式文件
### git操作
* git add . 暂存文件夹下所有文件 git add <文件名> 暂存该文件
* git commit -m "提交信息" 把代码提交到本地
* git push 将代码提交到远程
### vscode的操作
* crtl + a 选中所有, alt + shift + f 格式化代码, crtl + f 查找, crtl + s 保存代码
### 7月22号
* 链接分类 锚点链接 点完链接可以直接跳到页面中的该位置 <a href="#live><?a><br /> id="live"
* html注释标签 用来注释用的,不显示 ctrl +/ 特殊字符
* p28 综合案列复习: 目录文件夹, 标签
* p29 综合案列复习:路径,锚点链接
* p30 标签分类 <表格标签 列表标签 表单标签 综合标签 查阅文档>
* p31 1 表格标签:表格标签作用,语法.表格用于展示,显示数据.语法:有三种方式
* p32 表格标签:表格单元格:<th>table head 缩写 突出表现重要性
* p33 表格标签 属性:<align 排列 > <border 边界> <cellpadding 单元格边距> <cellspacing单元格间距> <width宽度>
* p34 案例分析:先制作表格结构在书写表格属性
* p35 表格结构标签:<thead>标签:头部区域,<thead>在<tr>内<tbody>标签:主体区域te.全部在<table></table>中
* p36 表格标签:合并单元格:1跨行合并:rowspan 跨列合并:colspan.合并单元格,先确定行还是列在写合并式,最后删除多余的单元格
* p37 表格标签:整理表格的三部分:1表格的相关标签,2 表格的相关属性 3合并单元格 <table标签 > <tr标签><td单元格>
* p38 列表标签:是用来布局的. 列表分为三大类:无序列表,有序列表,自定义列表. 1无序列表用<ul>表示,列表项用<li>定义,<ul>里面只能出现<li>,<li>里面可以添加所有元素
* p39 列表标签:2 有序列表:<ol>用于定义有序列表,用数字显示,用<li>定义列表项
* p40 列表标签:3 自定义列表:用于对术语和名词进行解释和描述,没有任何项目符号.<dl>,<dl>用于定义列表,<dt>和<dd>k
* p41 总结三种列表:1 无序列表:<ul></ul>,里面只能包含<li>,没有顺序,<li>里面可以包含任何标签 2 有序列表:<ol></OL>里面只能包含<li>,有顺序,<li>里面可以包含任何标签 3 自定义列表:<dl></dl>里面只能包含<dt>和<dd>,<dt>和<dd>里面可以放任何标签
* p42 表单标签:表单是为了收集用户信息,表单是表单域,表单控件和提示信息三个组成
* p43 表单域:包含表单元素的区域,<form>用于定义表单域
* p44 表单控件: <input>用于收集用户信息,包含type属性,<input>是单标签,
* p45
* p47 <input>中的其他属性:<name>定义input元素的名称,<value>规定input元素的值,<check>规定此input元素首次加载时应当被选中,<maxlength>规定输入字段中的字符的最大长度.
* p48<input>表单元素使用场景:<value>属性="值".<name>属性后面的值,是自定义的.<checked>属性:表示默认选中转态.用于单选按钮和复选按钮.<type>可以让input表单元设置不同的形态
* p51 <label>标签:用于绑定一个表单元素,<label>标签的for属性应当与相关元素的ID属性相同.<label标签为input元素定义标注(标签)>
* P52 <select>标签控件定义下拉列表,中至少包含一对<option>
* p52 <textarea>用于定义多行文本输入的控件,特大号的文本框.cols=每行中的字符数,rows=显示的行数
* p53 表单元素的几个总结点:input输入元素,select下拉表单元素,textarea文本域表单元素
*p60:css: css简介. 目标:什么是css,能够使用css,能够设置文本样式,说出css的三种引入方式,能够使用chrome调试工具调试样式
* p61:css简介:主要使用场景就是美化网页,布局网页的.css是层叠样式表<Cascading Style Sheets>的简称.css也是一种语言,用于设置html页面中的文本内容<字体,大小,对齐方式>,图片的外形,以及版面的布局和外显示样式. 美化html
* p62 css的语法规范:css由两部分构成选择器以及一条或多条声明 h1:选择器,color:属性,font:属性. 属性和属性之间用<:>来分割,多个键值对之间用<;>来区分
* p63 css代码风格:主要的书写方式:1 样式格式书写.2 样式大小写风格 3 样式空格风格 1样式格式书写:紧凑书写,展开书写 2样式大小写 3: 空格规范:属性值前面,冒号后面,保留一个空格.选择器<标签>和大括号中间保留空格
* p64 css基础选择器:选择器的作用,就是选择标签用的
* css基础选择器:选择器的分类:基础选择器和复合选择器两类. 基础选择器是由单个选择器组成的,
* 基础选择器包括:标签选择器,类选择器,id选择器和通配选择器.
* 标签选择器:是指用html标签名称作为选择器,按标签分类
* 类选择器:类选择器的使用场景:单独选一个或者几个标签.
* id选择器:用#来定义,html元素以ID来设置ID选择器,css中ID选择器以#来定义.ID只能调用一次,别人用不了
*
* p68 类选择器多类名:多类名使用方式:给一个标签指定多个类名 多类名开发中的场景:可以把一些标签的样式相同的放在一个类里面,都可以调用这个公众的类
* p70 通配符选择器:*选取页面中所有的元素,不需要调用,自动就给所有的元素使用样式co
* p71 css字体属性:用于定义字体系列,大小,粗细,和文本样式,使用font-family属性定义文本的字体系列,各种字体用逗号隔开,
* p72 css字体`大小:用font-size属性定义字体大小.px<像素>大小是网页的常用的单位,谷歌默认字体大小16px,也可以给body指定整个页面文字的大小
* p73 css字体加粗:css使用font-weight属性设置字体文本的粗细,<normal>默认值<不加粗的> <bold>定义粗体<加粗的> 100-900 400等同于normal,而700等同于bold 这个数字后面不跟单位
* p74 文本样式:使用font-style属性设置文本的风格 normal的作用,浏览器会显示标准的字体样式 font-style:normal italic的作用,浏览器会显示斜体的字体样式
* p75 字体复合属性:使用font属性时,必须按上面语法格式中的顺序书写,不能跟换顺序,并且各个属性间以空格隔开,不需要设置的属性可以忽略<取默认值>,但必须保留font-size和font-family属性,否则font属性将不起作用
* p76 字体属性总结:font-size表示字号,单位是px像素,一定要跟上单位. font-family表示字体,实际工作中按照团队约定来书写字体. font-weight表示字体粗细,加粗是700或者bold不加粗是normal或者400,记住数字不要跟单位. font-style表示字体样式,倾斜是italic,不倾斜是normal,常用normal. font表示字体连写:1字体连写是有顺序的,不能随意换位置 2其中字号和字体必须同时出现
* p77 css文本属性:css Text<文本>属性可定义文本的外观,比如文本的颜色,对齐文本,装饰文本,文本缩写,行间距. color属性用于定义文本的颜色
* p78对齐文本:Text-align属性用于设置元素内文本内容的水平对齐方式 属性值:<left,左对齐><right,右对齐><center,居中对齐>
* p79 装饰文本:text-decoration属性规定添加文本的修饰,<none,默认><underline,下划线><overline,上划线><line-through删除线>
* p80 文本缩进:text-indent属性用来指定文本的第一行的缩进,通常是将段落的首行缩进.em是一个相对单位,就是一个<font-size>一个文本的大小
* p81 行间距:line-height属性用于设置行间的距离<行高>.可以控制文字行与行之间的距离
* p82css文本属性总结:
<color>表示文本颜色,用十六进制,简写#fff.
` <text-align>表示文本对齐,可以设定文本水平的对齐方式.
<text-indent>表示文本缩进,用于段落首行缩进两个字的间距,text-indent;2em
<text-decoration>表示文本修饰,记住添加下划线,underline取消下划线 none
<line-height>表示行高,控制行与行之间的距离
* p83 css的引入方式:css的三种样式表:
1 行内样式表<行内表>
2 内部样式表<嵌入式>
3 外部样式表<链接式>
* 行内样式表:是在元素标签内部的style属性中设定css样式.适合于修改简单样式.style其实就是标签的属性,在双引号中间,写法要符合css规范,可以控制当前的标签设置样式
* 外部样式表:适用于较多的情况,引入外部样式表步骤:1,新建一个后缀名为css的文件,把所有css代码都放入此文件中 2,在html文件页面中,使用<link>标签引入这个文件
* p86 css引入方式总结:行内样式表;书写方便,权重高,但是结构样式混写.使用较少,控制一个标签.
内部样式表:部分结构和样式分离,但是没有彻底分离.使用较多,控制一个页面
外部样式表:完全实现结构和样式分离,但是需要引入,使用最多,可控制多个页面
*87-90 综合案例
Chrome调试工具:打开Chrome浏览器,按下F12键或者右击页面空白处 检查.
1 Ctrl+滚轮可以放大开发者工具代码大小
2 左边是html元素结构,右边是css样式
3 右边css样式可以改动数值<左右箭头或者直接输入>和查看颜色
4 Ctrl+0复原浏览器大小
5 如果点击元素,发现右侧没有样式引入,极有可能是类明或者样式引入错误
6 如果有样式,但是样式前面有黄色叹号提示,则是样式属性书写错位
* css:目标 1 能使用emmet语法
2 能够使用css复合选择器
3能够书写伪类选择器的使用规范
4 能够说出元素有几种显示模式
5 能够写出元素显示模式的相互转换代码
6 能够写出背景图片的设置方式
7 能够计算css的权重
* p93 emmet语法:快速生成HTML结构语法
1 生成标签 直接输入标签名按tab键即可 比如 div 然后tab,就可以生成<div></div>
2 如果想要生成多个相同的标签 加上*就可以了 比如div*3就可以生成3个div
3 如果有父子极关系的标签,可以用> 比如ul>li 就可以了
4 如果有兄弟关系的标签,用+就可以了 比如div+p
5 如果生成带有类名或者id名字的,直接写 .demo或者#two tab 键就可以了
6 如果生成的div类名是有顺序的,可以用自增符号$
* p94 快速生成css样式语法:css基本采取简写形式即可
* p95 快速格式化代码: vscode 快速格式化代码:shift+Alt+F
* p96 css复合选择器:在css中,可以根据选择器的类型把选择器分为基础选择器和复合选择器,复合选择器是建立在基础选择器之上,对基本选择器进行组合形成的.
* 复合选择器可以更准确,更高效的选择目标元素<标签
* 复合选择器是由两个或多个基础选择器,通过不同的方式组合而成的
* 常用的复合选择器包括:后代选择器,子选择器,并集选择器,伪类选择器等
* p97 css的复合选择器: 1 后代选择器:后代选择器又称为包含选择器,可以选择父元素里面的子元素.其写法就是把外层标签写在前面,内层标签写在后面,中间用空格分隔.当标签发生嵌套时,内层标签就成为外层的后代
* p98 css的复合选择器: 2 子选择器: 子选择器只能选择作为某元素的最近一级子元素.简单理解就是选亲二中元素
*P 100 并集选择器:并集选择器可以选择多组标签,同时为他们定义相同的样式.通常用于集体申明.通过英文符号<,>连接而成,任何形式的选择器都可以作为并集选择器的一部分
* P101伪类选择器:用于某些选择器添加特殊的效果,比如给链接添加特殊的效果,或选择第一个,第n个元素.书写的最大的特点是用冒号<;>表示,比如:hover,:first-child
* p102 链接伪类选择器:注意事项:1为了确保生效,请按照LVHA的循序顺序声明:link-:visited-:hover-:active
2记忆法:love hate或者lv包包hao
3因为a链接在浏览器中具有默认样式,所以我们实际工作中都需要给链接单独指定样式
* p103 focus伪类选择器:用于选择获得焦点的表单元素.焦点就是光标,一般情况<input>类表单元素才能获取,因此这个选择器也主要针对表单元素
* p104:复合选择器总结: 选择器 作用 特征 使用情况 隔开符号及用法
后代选择器 用来选择后代元素 可以是子孙后代 较多 符号是空格.nav a
子代选择器 选择最近一级元素 只选亲儿子 较少 符号是大于.nav>p
并集选择器 选择某些相同的元素 可以用于集体声明 较多 符号是逗号.nav,.header
链接伪类选择器 选择不同状态的链接 跟链接相关 较多 重点记住a{}和a:hover 实际开发的写法
:focus选择器 选择获得光标的表单 跟表单相关 较少 input:focus 记住这个写法
* p105 css的元素显示模式:作用:网页的标签非常多,在不同地方会用到不同类型的标签,了解他们的特点可以更好的布局我们的网页.html元素一般分为块元素和行内元素两种类型
* p106 html元素分为块元素和行内元素:常见的块元素有<h1>~<h6>,<div>,<ul>,<ol>,<li>等,其中<div>标签是最典型的块元素
块元素的特点:1 比较霸道,自己独占一边
2 高度,宽度,外边距以及内边距都可以控制
3宽度默认是容器<父级宽度>的100%
4是一个容器及盒子,里面可以放行内或者块元素
* p107 行内元素:常见的行内元素有<a>,<strong>,<b>,<em>,<i>,<del>,<s>,<ins>,<u>,<span>等,其中<span>标签是最典型的行内元素.有的地方也将行内元素称为内联元素.
行内元素的特点:1 相邻行内元素在一行上,一行可以显示多个
2 高,宽直接设置是无效的
3 默认宽度就是它本身内容的宽度
4 行内元素只能容纳文本或其他行内元素 注意:链接里面不能再放链接 特殊情况链接<a>里面可以放块级元素,但是给<a>转换一下块级模式最安全
* p108 行内块元素:在行内元素中有几个特殊的标签--<img/>,<input/>,<td>,他们同时具有块元素和行元素的特点.
行内块元素的特点:1 和相邻行内元素<行内块>在一行上,但是他们之间会有空白缝隙,一行可以显示多个<行内元素特点>
2 默认宽度就是它本身内容的宽度<行内元素特点>
3 高度,行高,外边距以及内边距都可以控制<块元素特点>
* p109 css的元素显示模式; 元素模式 元素排列 设置样式 默认宽度 包含
块级元素 一行只能放一个块级元素 可以设置宽度高度 容器级可以包含任何标签
行内元素 一行可以放多个行内元素 不可以直接设置宽度高度 容纳文本或则其他行内元素
行内块元素 一行放多个行内块元素 可以设置宽度和高度 它本身内容的宽度
* 元素显示模式转换:特殊情况下,我们需要元素模式的转换,简单理解:一个模式的元素需要另外一个模式的特性
* p 112 案例:简洁版小米侧边栏:案例的核心思路分为两步
1 把链接a转换为块元素,这样链接就可以单独占一行,并且有宽度和高的
2 鼠标经过a给 链接设置背景颜色
* p 113 技巧:单行文字垂直居中的代码: 解决方案:让文字的行高等于盒子的高的就可以让文字在当前盒子内垂直居中 单行文字垂直居中的原理:行高的上下空隙和下空隙把文字挤到中间了.是如果行高小于盒子高度,文字会偏上,如果行高大于盒子高度,则文字偏下
* p114 css背景:通过给css背景属性,可以给页面元素添加背景样式.背景属性可以设置背景颜色,背景图片,背景平铺,背景图片位置,背景图像固定 1 背景颜色:background-color属性定义了元素的背景颜色<background-color>:颜色值;
* p115 背景图片:background-image属性描述了元素的背景图像.实际开发常见于logo或者一些装饰性的小图片或者是超大的背景图片,优点是非常便于控制位置<精灵图也是一种运用场景>
参数值 作用
none 无背景图<默认的
url 使用绝对或相对地址指定背景图像
* p116 背景平铺:如果需要在HTML页面上对背景图像进行平铺,可以使用background-repeat属性 <repeat 平铺> <no-repeat 不平铺> <repeat-x 背景图像在横向上平铺> <repeat-y 背景图像在纵向平铺>
* p117 背景图片位置:利用<background-position>属性可以改变图片在背景中的位置.background-position:x y;参数代表的意思是:x坐标和y坐标.可以使用方位名词或者精准单位
参数值 说明
length 百分数|由浮点数字和单位标识符组成的长度值
postion top|center|botton|left|center|right方位名词
1 参数是方位名称:* 如果指定的两个值都是方位名词,则两个值前后顺序无关,比如left和top left效果一致
* 如果只指定了一个方位名词,另一个省略,则第二个值默认居中对齐
* p118 背景图片位置:案列
* p120 背景图片位置:1参数是方位名词:*如果指定的两个值都是方位名词,则两个值前后顺序无关,比如left top和top left效果一致 *如果只指定了一个方位名词,另一个值省略,则第二个值默认居中对齐
2参数是精确单位*如果参数是精确坐标,那么第一个肯定是x坐标,第二个一定是y坐标
*如果只指定一个数值,那该数值一定是x坐标,另一个默认垂直居中
* p121 参数是混合单位:如果指定的两个值是精准单位和方位名词混合使用,则第一个值是x坐标,第二个值是y坐标
* p122 背景图像固定<背景附着> <background-attachment>属性设置背景图像是否固定或者随着页面的其余部分滚动
<background-attachment>后期可以制作视差滚动的效果
参数 作用
scrool 背景图像是随对象内容滚动
fixed 背景图像固定
* p123 背景复合写法:为了简化背景属性的代码,我们可以将这些属性合并简写在同一个属性<background>中.从而节约代码量
当使用简写属性时,没有特定的书写顺序,一般习惯约定顺序为:
background:背景颜色,背景图片地址,背景平铺,背景图像滚动,背景图片位置
background:transparent url<image.jpg> repeat-y fixed top;
* p124 背景色半透明:css3为我们提供了背景颜色半透明的效果
background:rgba<0,0,0,0.3>
* 最后一个参数是alpha透明度,取值范围在0~1之间
* 我们习惯把0.3的0省略掉,写为background:rgba<0,0,0.3>
* 注意:背景半透明是指盒子背景半透明,盒子里面的内容不受影响
* css3新增属性,是IE9+版本浏览器才支持的
* 但是现在实际开发,我们不太关注兼容性写法了,可以放心使用
* p125 css背景,背景总结: 属性 作用 值
background-color 背景颜色 预定义的颜色值/十六进制/RGB码
background-image 背景图片 url<图片路径>
background-repeat 是否平铺 repeat/no-repeat/repeat-x/repeat-y
background-postion 背景位置 length/postion 分别是x 和 y坐标
background-attachment 背景附着 scroll<背景滚动> /fixed<背景固定>
背景简写 书写更简单 背景颜色 背景图片地址 背景平铺 背景滚动 背景位置
背景色半透明 背景颜色半透明 background:rgba<0,0,0,0.3>;后面必须是4个值
* p126 综合案例-五彩导航:练习价值 1 链接属于行内元素,但是此时需要宽度高度,因此需要模式转换
2 里面文字需要水平居中和垂直居中.因此需要单行文字垂直居中的代码
3 链接里面需要设置背景图片,因此需要用到背景相关的相关属性设置
4 鼠标经过变化背景图片,因此需要用到链接伪类选择器
* p128 <css三大特性>:css有三个非常重要的的三个特性:层叠性,继承性,优先性
* <层叠性>:相同选择器给设置相同的样式,此时一个样式就会覆盖<层叠>另一个冲突的样式.层叠性主要解决样式冲突的问题
层叠性原则:1 样式冲突,遵循的原则是就近原则,哪个样式离结构近,就执行哪个样式
2 样式不冲突,不会层叠
* p129 <继承性>:css中的继承:子标签会继承父标签的某些样式,如文本颜色字号.简单的理解就是:子承父业
恰当地使用继承可以简化代码,降低css样式的复杂性
子元素可以继承父元素的演样式<text,font-,line- 这些元素的开头的可以继承,以及color属性>
* p130 <继承性>:行高的继承: 行高可以跟单位也可以不跟单位
如果子元素没有设置行高,则会继承父元素的行高的1.5
此时子元素的行高是:当前子元素的文字大小的*1.5
body行高1.5 这样写法最大的优势就是里面的子元素可以根据自己文字大小自动调整行高
* p131 <优先级>:当同一个元素指定多个选择器,就会有优先级的产生
选择器相同,则执行层叠性
选择器不同,则根据选择器权重执行
选择器的权重如下所示:
选择器 选择器权重
继承 或者 * 0,0,0,0
元素选择器 0,0,0,1
类选择器,伪类选择器 0,0,1,0
ID选择器 0,1,0,0
行内样式style="" 1,0,0,0
!important 无穷大
* p132 优先级注意点: 权重是有4组数字组成,但是不会有进位
可以理解为类选择器永远大于元素选择器.ID选择器永远大于类选择器.以此类推
等级判断从左向右,如果某一个数值相同,则判断下一位数值
可以简单记忆法:通配符和继承权重为0,标签选择器为1,类<伪类>选择器为10.ID选择器100,行内样式表为1000,!important无穷大
继承的权重是0,如果该元素没有直接选中,不管父元素权重多高,子元素得到的权重都是0
* p133 <优先级> 权重叠加:如果是复合选择器,则会有权重叠加,需要计算权重.
权重叠加:如果是复合选择器,则会有权重叠加,需要计算权重
* div ul li -----> 0,0,0,3
* .nav ul li ----> 0,0,1,2
* a:hover -------> 0,0,1,1
* .nav a --------> 0,0,1,1
* p134 权重练习题:
* p135 css盒子模型:目标: 1 能够准阐述盒子模型的4个组成部分
2 能够利用边框复合写法给元素添加边框
3 能够计算盒子的实际大小
4 能够利用盒子模型布局模块案例
5 能够给盒子设置圆角边框
6 能够给盒子添加阴影
7 能够给文字添加阴影
* p136 盒子模型: 页面布局学习三大核心,盒子模型,浮动 和定位.学习好盒子模型能帮助我们布局页面.
网页布局过程: 1 先准备好相关的网页元素,网页元素基本都是盒子Box
2 利用css设置好盒子样式,然后摆放到相应的位置
3 往盒子里面装内容
网页布局的核心本质:就是利用css摆盒子
* p137 盒子模型组成:盒子模型就是把HTML页面中的布局元素看作是一个矩形的盒子,也就是一个盛装内容的容器.css盒子模型本质上是一个盒子,封装周围的HTML元素,它包括:边框,外边框,内边框,和实际内容
盒子模型组成:<border 边框><content 内容><padding 内边框><外边距 margin>
* p138 盒子模型边框border:border可以设置元素的边框.边框有三步法组成:边框宽度<粗细>边框样式 边框颜色
属性 作用
border-width 定义边框粗细,单位是px
border-style 边框的样式
border-color 边框颜色
* p139 边框的复合写法:css边框属性允许你指定一个元素边框的样式和颜色
边框简写:border:1px solid red; 没有顺序
边框分开写法: border-top: 1px solid red; /*只设定上边框, 其余同理 */
* p140 表格的细线边框:border-collapse属性控制浏览器绘制表格边框的方式.它控制相邻单元格的边框
语法:
border-collapse:collapse;
* collapse单词是合并的意思
* border-collapse:collapse;表示相邻边框合并在一起
* p141 边框影响盒子实际大小: 1 测量盒子大小的时候,不量边框
2 如果测量的时候包括了边框,则需要width/height减去边框宽度
* p142 内边距:padding属性用于设置内边距,即边框与内容之间的距离
属性 作用
padding-left 左内边框
padding-right 右内边框
padding-top 上边边框
padding-bottom 下边边框
* p143 内边距<padding>:padding属性可以有一到四个值:
值的个数 表达意思
padding:5px 1个值,代表上下左右都有5像素内边距
padding:5px 10px 2个值,代表上下内边距是5像素 左右内边距是10像素
padding:5px 10px 20px 3个值,代表上内边距5像素 左右内边距10像素 下内边距20像素
padding:5px 10px 20px 30px 4个值,上是5像素 右10像素 下20像素 左是30像素 顺时针
* p144 内边距:<padding>: 1 内容和边距有了距离,添加了内边距
2 padding影响了盒子实际大小
如果盒子已经有了宽度和高度,此时再指定内边距,会撑大盒子
解决方案:如果保证盒子跟效果图大小保持一致,则让width/height减去多出来的内边距大小即可
* p145-147 案例:新浪导航案例-padding影响盒子好处
* p148 <内边距>:如果盒子本身没有指定width/height属性,则此时padding不会撑开盒子大小
* p149 外边距<margin>:margin属性用于设置外边距,即控制盒子和盒子之间的距离
属性 作用
margin-left 左内边距
margin-right 右内边距
margin-top 上外边距
margin-bottom 下外边距
margin简写方式代表的意思跟padding完全一致
* p150 外边距典型应用:外边距可以让块级盒子水平居中,条件:
1 盒子必须指定了宽度
2 盒子左右的外边框都设置为auto
* p151 外边距典型应用::常见写法,一下三种
* margin-left:auto; margin-right:auto
* margin:auto;
* margin:0 auto;
注意:以上写法是让块元素水平居中,行内元素或者行内块元素水平居中给其父元素添加text-alight:center即可
* p152 外边距合并:使用margin定义块元素的垂直外边距时,可能会出现外边距的合并.
主要有两种情况:
1 相邻块元素垂直外边距的合并
2 嵌套块元素垂直外边距的塌陷
当上下相邻的两个块元素<兄弟关系>相遇时,如果上面的元素有下外边距margin-bottom,下面的元素有上外边距margin-top.则他们之间的垂直间距不是margin-bottom与margin-top之和,取两个值中的较大者这种现象被称为相邻元素垂直外边距的合并
* p153 外边距合并:使用margin定义块元素的垂直外边距时,可能会出现外边距的合并:
2 嵌套块元素垂直外边距的塌陷:对于两个嵌套关系<父子关系>的块元素,父元素有上外边距同时子元素也有上外边距,此时父元素会塌陷较大的外边距值.
解决方案:
1 可以为父元元素定义上外边框
2 可以为父元素定义上内边距
3 可以为父元素添加overflow:hidden
* p154 清除内外边距:网页元素很多都带有默认的内外边距,而且不同浏览器默认的也不一致,因此我们在布局前,首先要清除下网页元素的内外边距 *{
padding:0; /*清除内边距 */
margin:0; /*清除外边距 */
}
注意:行内元素为了照顾兼容性,尽量只设置左右内外边距,不要设置上下内外边距.但是转换为块级和行内元素就可以了
* p155 PS基本操作:因为网页美工大部分效果图都是利用PS<Photoshop>来做的,所以我们大部分都是在PS里面完成
* 文件 打开:可以打开我们要测量的图片
* Ctrl+R:可以打开标尺,或者视图 标尺
* 右击标尺,把里面的单位改为像素
* Ctrl+加号<+>可以放大视图,Ctrl+减号<->可以缩小视图
* 按住空格键,鼠标可以变成小手,拖动PS视图
* 用选区拖动,可以测量大小
* Ctrl+D 可以取消选区,或者在旁边空白处点击一下也可以取消选区
* p156 综合案例-产品模块布局:
* p165 圆角边框: 语法:border-radius:length; radius半径<圆的半径>原理:<椭>圆边与边框的交集形成圆角效果
* p167 border-radius属性用于设置元素的外边框圆角.
语法:border-radius:length\
* 参数值可以为数值或百分比的形式
* 如果是正方形,想要设置一个圆,把数值修改为高度或者宽度的一半即可,或者直接写为50%
* 如果是个矩形,设置为高度的一半就可以做
* 该属性是一个简写属性,可以跟四个值,分别代表左上角,右上角,右下角,左下角
* 分开写:border-top-left-radius, border-top-right-radius, border-bottom-right-radius和border-bottom-left-radius
* p168 盒子阴影:可以用box-shadow属性为盒子添加阴影:
语法:box-shadow: h-shadow blur spread color inset;
值 描述
h-shadow 必需.水平阴影的位置.允许负值
v-shadow 必需.垂直阴影的位置.允许负值
blur 可选.模糊距离
spread 可选.阴影的尺寸
color 可选.阴影的颜色,可参考css颜色值
inset 可选.将外部阴影<outset>改为内部阴影
注意: 1 默认的是外阴影,但是不可以写这个单词,否则导致阴影无效
2 盒子阴影不占用空间,不会阴影其他盒子排列
* p169 文字阴影:可以用text-shadow属性将阴影应用于文本:
语法:text-shadow: h-shadow v-shadow blur color;
值 描述
h-shadow 必需.水平阴影的位置.允许负值
v-shadow 必需.垂直阴影的位置.允许负值
blur 可选.模糊的距离
color 可选.阴影的颜色.参考css颜色值
* p170 传统网页布局的三种方式:网页布局的本质--用css来摆放盒子.把盒子摆放到相应的位置
|
Java
|
UTF-8
| 5,062 | 2.328125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2006 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.beans;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.efaps.db.Context;
import org.efaps.util.EFapsException;
/**
* <p>
* The class could be used to load the resource bundles automatically. The
* class owns methods to translate texts.
* </p>
* Example of an Usage:
* <ul>
* <li>add the resource bundle bean to the faces configuration:<br/>
* <b><code>
* <!-- resource bundle bean used for translation --><br/>
* <managed-bean><br/>
* <managed-bean-name>i18n</managed-bean-name><br/>
* <managed-bean-class>org.efaps.beans.ResourceBundleBean</managed-bean-class><br/>
* <managed-bean-scope>application</managed-bean-scope><br/>
* <!-- set bundle (base) name --><br/>
* <managed-property><br/>
* <property-name>bundleName</property-name><br/>
* <value>StringResource</value><br/>
* </managed-property><br/>
* </managed-bean><br/>
* </code></b>
* </li>
* <li>
* add to your bean the instance variable <b><code>i18nBean</code></b> from
* class <b><code>ResourceBundleBean</code></b>
* </li>
* <li>add method <b><code>setI18nBean(ResourceBundleBean _i18nBean)</code></b> to your bean</li>
* <li>define the managed property for your bean:<br/>
* <b><code>
* <managed-property><br/>
* <property-name>i18nBean</property-name><br/>
* <value>#{i18n}</value><br/>
* </managed-property><br/>
* </code></b>
* </li>
* <li>use with<br/>
* <b><code>String translated = this.i18nBean.translate("Admin_UI_Command.Label");</code></b><br/>
* the resource bundle bean in your bean
* </ul>
*
* @author tmo
* @version $Rev$
*/
public class ResourceBundleBean {
/**
* The map stores a resource bundle depending on the language / country as
* key.
*/
private final Map < String, ResourceBundle > bundles = new HashMap < String, ResourceBundle > ();
/**
* The string stores the bundle name in which the strings are stored.
*/
private String bundleName = null;
/**
*
*/
public void setBundleName(final String _bundleName) {
this.bundleName = _bundleName;
}
public String translate(final String _id) {
Context context = null;
try {
context = Context.getThreadContext();
} catch (EFapsException e) {
}
return translate(context, _id);
}
public String translate(final Context _context, final String _id) {
return translate(_context != null ? _context.getLocale() : null, _id);
}
/**
* Gets a string for the given identifier from this resource bundle. If no
* string for the given identifier can be found, the return value is the key
* with prefix and suffix of three question marks (???).
*
* @param _locale locale object used to translate
* @param _id identifier for which the the translation is searched
*/
public String translate(final Locale _locale, final String _id) {
String key = _locale != null ? _locale.getLanguage() + _locale.getCountry() : "";
ResourceBundle bundle = bundles.get(key);
if (bundle == null) {
bundle = ResourceBundle.getBundle(this.bundleName, _locale);
bundles.put(key, bundle);
}
String ret;
try {
ret = bundle.getString(_id);
} catch (MissingResourceException e) {
ret = "???" + _id + "???";
}
return ret;
}
public ResourceBundle getResourceBundle() throws EFapsException {
return getResourceBundle(Context.getThreadContext());
}
public ResourceBundle getResourceBundle(final Context _context) {
return getResourceBundle(_context != null ? _context.getLocale() : null);
}
public ResourceBundle getResourceBundle(final Locale _locale) {
String key = _locale != null ? _locale.getLanguage() + _locale.getCountry() : "";
ResourceBundle bundle = bundles.get(key);
if (bundle == null) {
bundle = ResourceBundle.getBundle(this.bundleName, _locale);
bundles.put(key, bundle);
}
return bundle;
}
}
|
C
|
UTF-8
| 3,673 | 3.515625 | 4 |
[] |
no_license
|
/**
* 动态数组的实现
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "darray.h"
struct _DArray
{
void** data;
int size;
int alloc_size;
void* data_destroy_ctx;
DataDestroyFunc data_destroy;
};
static void darray_destroy_data(DArray* thiz, void* data)
{
if(thiz->data_destroy != NULL) {
thiz->data_destroy(thiz->data_destroy_ctx, data);
}
return;
}
DArray* darray_create(DataDestroyFunc data_destroy, void* ctx)
{
DArray* thiz = malloc(sizeof(DArray));
if(thiz != NULL) {
thiz->data = NULL;
thiz->size = 0;
thiz->alloc_size = 0;
thiz->data_destroy_ctx = ctx;
thiz->data_destroy = data_destroy;
}
return thiz;
}
#define MIN_PRE_ALLOCATE_NR 10
static int darray_expand(DArray* thiz, int need)
{
if(thiz == NULL) return -1;
if((thiz->size + need) > thiz->alloc_size) {
int alloc_size = thiz->alloc_size + (thiz->alloc_size>>1) + MIN_PRE_ALLOCATE_NR;
// void** data
void** data = (void**)realloc(thiz->data, sizeof(void*) * alloc_size);
if(data != NULL) {
thiz->data = data;
thiz->alloc_size = alloc_size;
}
}
if((thiz->size + need) <= thiz->alloc_size) return 0;
else return -1;
}
int darray_prepend(DArray* thiz, void* data)
{
return darray_insert(thiz, 0, data);
}
int darray_append(DArray* thiz, void* data)
{
return darray_insert(thiz, -1, data);
}
int darray_insert(DArray* thiz, int index, void* data)
{
int ret = -1;
unsigned int cursor = index;
if(thiz == NULL) return -1;
// cursor
cursor = cursor < thiz->size ? cursor : thiz->size;
if(darray_expand(thiz, 1) == 0) {
int i = 0;
for(i=thiz->size; i>cursor; i--) {
thiz->data[i] = thiz->data[i-1];
}
thiz->data[cursor] = data;
thiz->size++;
ret = 0;
}
return ret;
}
static int darray_shrink(DArray* thiz)
{
if(thiz == NULL) return -1;
if(thiz->size < (thiz->alloc_size >> 1) && (thiz->alloc_size > MIN_PRE_ALLOCATE_NR)) {
int alloc_size = thiz->size + (thiz->size >> 1);
void** data = (void**)realloc(thiz->data, sizeof(void*) * alloc_size);
if(data != NULL) {
thiz->data = data;
thiz->alloc_size = alloc_size;
}
}
return 0;
}
int darray_delete(DArray* thiz, int index)
{
int i = 0;
int ret = 0;
if(thiz == NULL) return -1;
if(thiz->size < index) return -1;
darray_destroy_data(thiz, thiz->data[index]);
for(i=index; (i+1)<thiz->size; i++) {
thiz->data[i] = thiz->data[i+1];
}
thiz->size--;
darray_shrink(thiz);
return 0;
}
int darray_length(DArray* thiz)
{
if(thiz == NULL) return 0;
return thiz->size;
}
int darray_find(DArray* thiz, DataCompareFunc cmp, void* ctx)
{
int i = 0;
if(thiz == NULL) return -1;
if(cmp == NULL) return -1;
for(i=0; i<thiz->size; i++) {
if(cmp(ctx, thiz->data[i]) == 0) break;
}
return i;
}
int darray_foreach(DArray* thiz, DataVisitFunc visit, void* ctx)
{
int i = 0;
int ret = 0;
if(thiz == NULL) return -1;
if(visit == NULL) return -1;
for(i=0; i<thiz->size; i++) {
ret = visit(ctx, thiz->data[i]);
}
return ret;
}
void darray_destroy(DArray* thiz)
{
int i = 0;
if(thiz != NULL) {
for(i=0; i<thiz->size; i++) {
darray_destroy_data(thiz, thiz->data[i]);
}
if(thiz->data != NULL) {
free(thiz->data);
thiz->data = NULL;
}
if(thiz != NULL) {
free(thiz);
thiz = NULL;
}
}
return;
}
int darray_get_by_index(DArray* thiz, int index, void** data)
{
if(thiz == NULL) return -1;
if(index > thiz->size) return -1;
if(data == NULL) return -1;
*data = thiz->data[index];
return 0;
}
int darray_set_by_index(DArray* thiz, int index, void* data)
{
if(thiz == NULL) return -1;
if(index > thiz->size) return -1;
thiz->data[index] = data;
return 0;
}
|
C#
|
UTF-8
| 3,821 | 2.765625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EmawEngineLibrary.Messaging;
using EmawEngineLibrary.Terrain;
using Microsoft.Xna.Framework;
namespace EmawEngineLibrary.Physics
{
public class CollisionManager : GameComponent, ICollisionManager
{
/// <summary>
/// Creates a CollisionManager and registers it as a game service.
/// </summary>
/// <param name="game"></param>
public CollisionManager(Game game) : base(game)
{
m_postMan = new PostMan(game);
m_collisionObjects = new List<ICollidable>();
m_terrainCollisionObjects = new List<ICollidable>();
Game.Components.Add(this);
Game.Services.AddService(typeof(ICollisionManager), this);
}
public void RegisterCollisionObject(ICollidable collisionObject)
{
m_collisionObjects.Add(collisionObject);
}
public void UnregisterCollisionObject(ICollidable collisionObject)
{
m_collisionObjects.Remove(collisionObject);
}
/// <summary>
/// Registers an ICollidable with the manager as something that cares about colliding with terrain.
/// Also registers for normal collisions.
/// </summary>
/// <param name="collisionObject"></param>
public void RegisterTerrainCollisionObject(ICollidable collisionObject)
{
m_terrainCollisionObjects.Add(collisionObject);
RegisterCollisionObject(collisionObject);
}
public void UnregisterTerrainCollisionObject(ICollidable collisionObject)
{
m_terrainCollisionObjects.Remove(collisionObject);
UnregisterCollisionObject(collisionObject);
}
public override void Update(GameTime gameTime)
{
if (WorldBox != null)
{
foreach (ICollidable col in m_collisionObjects)
{
if (!WorldBox.BoundingBox.Intersects(col.BoundingBox))
m_postMan.SendMessage(MessageType.Collision, WorldBox, col);
}
}
//TODO:Add some spatial organization to the objects so we don't just brute force it.
for (int i = 0; i < m_collisionObjects.Count - 1; i++)
{
for (int j = i + 1; j < m_collisionObjects.Count; j++)
{
ICollidable c1 = m_collisionObjects[i];
ICollidable c2 = m_collisionObjects[j];
//If we have a collision, send out messages to each object from the other,
//and let them react to it.
if (c1.BoundingBox.Intersects(c2.BoundingBox))
{
m_postMan.SendMessage(MessageType.Collision, c1, c2);
m_postMan.SendMessage(MessageType.Collision, c2, c1);
}
}
}
ITerrain terrain = (ITerrain) Game.Services.GetService(typeof (ITerrain));
if (terrain != null)
{
foreach (ICollidable col in m_terrainCollisionObjects)
{
foreach (Vector3 corner in col.BoundingBox.GetCorners())
{
if (terrain.GetHeight(corner.X, corner.Z) >= corner.Y)
m_postMan.SendMessage(MessageType.Collision, null, col);
}
}
}
base.Update(gameTime);
}
public ICollidable WorldBox { get; set; }
private List<ICollidable> m_collisionObjects;
private List<ICollidable> m_terrainCollisionObjects;
private PostMan m_postMan;
}
}
|
Swift
|
UTF-8
| 4,793 | 2.546875 | 3 |
[] |
no_license
|
//
// RegisterPageViewController.swift
// run 2 gether
//
// Created by Shahd Alblu on 10/8/1438 AH.
// Copyright © 1438 Shahd Alblu. All rights reserved.
//
//refrence https://www.letsbuildthatapp.com/
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import MapKit
class RegisterPageViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
@IBOutlet weak var userEmailText: UITextField!
@IBOutlet weak var UserConfirmPassText: UITextField!
@IBOutlet weak var UserPasswordText: UITextField!
@IBOutlet weak var userNameText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named:"background.png")!)
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "background.png")?.draw(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registerButtonTapped(_ sender: Any) {
let userEmail = userEmailText.text
let userPassword = UserPasswordText.text
let userConfirm = UserConfirmPassText.text
let userName = userNameText.text
//check for empty fields
if((userEmail?.isEmpty)!||(userPassword?.isEmpty)!||(userConfirm?.isEmpty)! || (userName?.isEmpty)!)
{
//Disply alert message
displayAlertMessage( userMessage: " All field are required ");
}else if (userPassword != userConfirm){
//Disply alert message
displayAlertMessage( userMessage: " Passwords do not match ");
return;
}
else{
Auth.auth().createUser(withEmail: userEmailText.text!, password: UserPasswordText.text!, completion:
{ user, error in
if error != nil{
self.displayAlertMessage( userMessage: (error?.localizedDescription)! )
}else{
let uid = Auth.auth().currentUser?.uid
let databaseref = Database.database().reference()
let userData : [String : Any] = ["email":self.userEmailText.text!,"uid": uid!, "username":self.userNameText.text!]
databaseref.child("users").child(uid!).setValue(userData)
Helper.helper.switchToNavigationVC()
}
} )
}
//Check if password match
if (userPassword != userConfirm){
//Disply alert message
displayAlertMessage( userMessage: " Passwords do not match ");
return;
}
//Store data
//Display alert message with confirmation
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return true;
}
func displayAlertMessage(userMessage:String){
let Alert=UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title:"ok",style:UIAlertActionStyle.default,handler:nil)
Alert.addAction(okAction)
self.present(Alert, animated:true,completion:nil)
}
private var locationM = CLLocationManager()
private var userlocation: CLLocationCoordinate2D?
func inittheuserlocation(){
if let location = locationM.location?.coordinate {
userlocation = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
//----------------------------------------
let ref = Database.database().reference().child("Location")
let userId = Auth.auth().currentUser?.uid
if userId != nil{
let childref = ref.child(userId!)
let values = [ "latitude": location.latitude, "longitude": location.longitude ] as [String : Any];
childref.updateChildValues(values){ (error, ref) in
if error != nil {
print(error!)
return
}
}
}
}
}
}
|
Java
|
UTF-8
| 376 | 1.585938 | 2 |
[] |
no_license
|
package io.appform.oncall24x7;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Secrets for slack connectivity
*/
@Data
@NoArgsConstructor
public class SlackSecrets {
@NotEmpty
private String clientId;
@NotEmpty
private String clientSecret;
@NotEmpty
private String signingSecret;
}
|
Python
|
UTF-8
| 4,894 | 2.53125 | 3 |
[] |
no_license
|
import autograd.numpy.random as npr
from rnn_fun import *
class Weights(object):
def __init__(self, w_config, w_init_scale):
self.w_num = 0
self.idxs_and_shapes = {}
self.config = w_config
self.init_scale = w_init_scale
self.data = False
for config in self.config:
name, lyr_size, has_bias = config
if not self.idxs_and_shapes.has_key(name):
self.add_shape(config, add_to_config=False)
if not self.data:
self.data = npr.RandomState().randn(self.w_num) * self.init_scale
def add_shape(self, config, add_to_config=True):
name, lyr_size, has_bias = config
start = self.w_num
shape = lyr_size[0] + lyr_size[1]
self.w_num += np.prod(shape) #prod:product of all members
slice_weight = [slice(start, self.w_num),]
if has_bias:
start = self.w_num
self.w_num += np.prod(lyr_size[1])
slice_bias = slice(start, self.w_num)
slice_weight.append(slice_bias)
self.idxs_and_shapes[name] = (slice_weight, lyr_size, has_bias)
if add_to_config: self.w_config.append(config)
def get(self, w_data, name):
idxs, lyr_size, has_bias = self.idxs_and_shapes[name]
shape = lyr_size[0] + lyr_size[1]
weight = [w_data[idxs[0]].reshape(shape),]
if has_bias:
weight.append(w_data[idxs[1]].reshape([1,]+lyr_size[1]))
return weight
def set_weights_from_data(self, w_data, w_config):
for name, lyr_size, has_bias in w_config:
setattr(self, name, self.get(w_data, name))
return self
def change_weights(self, w_data, name, weight, is_bias=False):
if not is_bias: w_slice = self.idxs_and_shapes[name][0][0]
else: w_slice = self.idxs_and_shapes[name][0][1]
w_data[w_slice] = weight.reshape(-1)
def find(self, idx):
'''Find the name a weight scalar belongs to with its index'''
for name in self.idxs_and_shapes:
idxs, _ = self.idxs_and_shapes[name]
for idx_slice in idxs:
if idx in range(self.w_num)[idxs]:
return name
def show(self, w_data, grad=False, fun=np.linalg.norm):
norm_l1 = lambda x: np.sum(np.abs(x))
norm_fun = norm_l1
for name, lyr_size, has_bias in self.config:
weight = self.get(w_data, name)
num = np.prod(lyr_size[1])
w = norm_fun(weight[0])
b = norm_fun(weight[1]) if has_bias else np.nan
if not isinstance(grad, bool):
gg = self.get(grad, name)
gw = norm_fun(gg[0])
gb = norm_fun(gg[1]) if has_bias else np.nan
print_form = "%15s\t=> |\t"
print_form += "w = %.6s <- %.6s @ %.4s%%\t|\t"
print_form += "b = %.6s <- %.6s @ %.4s%%"
print print_form %(
name, w/num, gw/num, gw/w*100, b/num, gb/num, gb/b*100)
else: print "%15s\t=> |\tw = %.6s\t| b = %.6s" %(name, w, b)
class Layer(object):
def __init__(self, size, actfun=lambda x:x):
self.size = size
self.actfun = actfun if actfun else lambda x:x
self.out = False
def __mul__(self, weight):
'''Method of multiply layer's output signal with weight'''
x, w = self.out, weight[0]
axes = (range(1, 1+len(self.size)), range(len(self.size)))
w_dot_x = np.tensordot(x, w, axes=axes)
if len(weight)==2: return x_add_bias(w_dot_x, weight[1])
elif len(weight)==1: return w_dot_x
def __call__(self, signal, actfun=True):
'''Method of produce the layer's output signal'''
if actfun: self.out = self.actfun(signal)
else: self.out = signal
return self
def __imul__(self, gate):
gate_size = [gate.out.shape[0]] + [1] * (len(self.out.shape) - 1)
self.out = np.multiply(self.out, gate.out.reshape(gate_size))
return self
class RnnLayers(object):
def __init__(self, layer_config):
self.config = layer_config
for name, size, actfun in self.config:
setattr(self, name, Layer(size, actfun=actfun))
class RMSPropGrad(object):
def __init__(self, decay_rate):
self.r = 1.
self.dr = decay_rate
self.scale = 1.
def grad(self, grad):
self.r *= self.dr
self.r += (grad**2) * (1 - self.dr)
rms_grad = np.divide(grad, np.sqrt(self.r))
self.scale = np.linalg.norm(grad) / np.linalg.norm(rms_grad)
return rms_grad * self.scale
class MomentumGrad(object):
def __init__(self, decay_rate):
self.r = 0.
self.dr = decay_rate
def grad(self, grad):
self.r *= self.dr
self.r += grad * (1 - self.dr)
return self.r
|
JavaScript
|
UTF-8
| 309 | 3.625 | 4 |
[] |
no_license
|
const countLetters = function(string) {
const result = {};
for (const char of string) {
if (char === ' ') {
continue;
}
if (char in result) {
result[char] += 1;
} else {
result[char] = 1;
}
}
return result;
};
console.log(countLetters("lighthouse in the house"));
|
Java
|
UTF-8
| 3,191 | 2.140625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.aplex.webcan;
import java.util.Iterator;
import java.util.List;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.aplex.webcan.flatui.FlatUI;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
public class BaseApplication extends Application{
private final static String TAG = "BaseApplication";
private static Context mContext;
private static Handler mHandler;
private static Thread mMainThread;
private static long mMainThreadId;
private static Looper mMainThreadLooper;
@Override
public void onCreate()
{
super.onCreate();
mContext = this;
// handler
mHandler = new Handler();
mMainThread = Thread.currentThread();
// id
mMainThreadId = android.os.Process.myTid();
// looper
mMainThreadLooper = getMainLooper();
FlatUI.initDefaultValues(this);
// Setting default theme to avoid to add the attribute "theme" to XML
// and to be able to change the whole theme at once
FlatUI.setDefaultTheme(FlatUI.SKY);
int pid = android.os.Process.myPid();
String processAppName = getAppName(pid);
// 如果APP启用了远程的service,此application:onCreate会被调用2次
// 为了防止环信SDK被初始化2次,加此判断会保证SDK被初始化1次
// 默认的APP会在以包名为默认的process name下运行,如果查到的process name不是APP的process name就立即返回
if (processAppName == null ||!processAppName.equalsIgnoreCase(this.getPackageName())) {
Log.e(TAG, "enter the service process!");
// 则此application::onCreate 是被service 调用的,直接返回
return;
}
//init
EMOptions options = new EMOptions();
// 默认添加好友时,是不需要验证的,改成需要验证
options.setAcceptInvitationAlways(false);
//初始化
EMClient.getInstance().init(this, options);
//在做打包混淆时,关闭debug模式,避免消耗不必要的资源
EMClient.getInstance().setDebugMode(true);
}
public static Context getContext()
{
return mContext;
}
public static Handler getHandler()
{
return mHandler;
}
public static Thread getMainThread()
{
return mMainThread;
}
public static long getMainThreadId()
{
return mMainThreadId;
}
public static Looper getMainThreadLooper()
{
return mMainThreadLooper;
}
private String getAppName(int pID) {
String processName = null;
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = this.getPackageManager();
while (i.hasNext()) {
ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
try {
if (info.pid == pID) {
processName = info.processName;
return processName;
}
} catch (Exception e) {
// Log.d("Process", "Error>> :"+ e.toString());
}
}
return processName;
}
}
|
JavaScript
|
UTF-8
| 2,585 | 4.46875 | 4 |
[] |
no_license
|
//ЗАДАНИЕ
//Напиши скрипт со следующим функционалом:
//При загрузке страницы пользователю предлагается в prompt ввести число. Ввод сохраняется в переменную input и добавляется в массив чисел numbers.
//Операция ввода числа пользователем и сохранение в массив продолжается до тех пор, пока пользователь не нажмет Cancel в prompt.
//После того как пользователь прекратил ввод нажав Cancel, если массив не пустой, необходимо посчитать сумму всех элементов массива и записать ее в переменную total. /////Используй цикл for или for...of. После чего в консоль выведи строку 'Общая сумма чисел равна [сумма]'.
//РЕШЕНИЕ
// let input = "";
// const numbers = [];
// let total = 0;
// do {
// input = prompt("Введите число:");
// if (Number.isNaN(Number(input))) {
// alert("Было введено не число, попробуйте еще раз");
// continue;
// }
// numbers.push(Number(input));
// } while (input !== null);
// // if (numbers.length === 0) {
// // alert("Массив пустой");
// // }
// // for (const element of numbers) {
// // total += element;
// // console.log("Общая сумма чисел: ", total);
// // }
// if (numbers.length === 1) {
// alert("Ничего не введено");
// } else {
// for (const number of numbers) {
// total += number;
// }
// console.log(`Общая сумма чисел равна ${total}`);
// }
// const array = [];
// console.log(numbers);
let input = "";
const numbers = [];
let total = 0;
do {
input = prompt("Введите число:");
if (input === null) {
break;
} else if (Number.isNaN(Number(input))) {
alert("Было введено не число, попробуйте еще раз");
continue;
} else if (input === "") {
alert("Вы ничего не ввели");
continue;
}
numbers.push(Number(input));
} while (input !== null);
if (numbers.length === 0) {
alert("Сложение чисел не проведено");
} else {
for (const number of numbers) {
total += number;
}
alert(`Сумма введенных чисел: ${total}`);
}
|
Java
|
UTF-8
| 6,162 | 2.28125 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2010-2014 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.sonatype.tests.http.server.jetty.util;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
public class FileUtil
{
private static final File TMP = new File( System.getProperty( "java.io.tmpdir" ), "http-tests-"
+ UUID.randomUUID().toString().substring( 0, 8 ) );
static
{
Runtime.getRuntime().addShutdownHook( new Thread()
{
@Override
public void run()
{
try
{
delete( TMP );
}
catch ( IOException e )
{
e.printStackTrace();
}
}
} );
}
public static File createTempFile( String contents )
throws IOException
{
return createTempFile( contents.getBytes( "UTF-8" ), 1 );
}
public static File createTempFile( byte[] pattern, int repeat )
throws IOException
{
mkdirs( TMP );
File tmpFile = File.createTempFile( "tmpfile-", ".data", TMP );
write( pattern, repeat, tmpFile );
return tmpFile;
}
public static void write( String content, File file )
throws IOException
{
try
{
write( content.getBytes( "UTF-8" ), 1, file );
}
catch ( UnsupportedEncodingException e )
{
// broken VM
throw new IOException( e.getMessage() );
}
}
public static void write( byte[] pattern, int repeat, File file )
throws IOException
{
file.deleteOnExit();
file.getParentFile().mkdirs();
FileOutputStream out = null;
try
{
out = new FileOutputStream( file );
for ( int i = 0; i < repeat; i++ )
{
out.write( pattern );
}
}
finally
{
close( out );
}
}
public static long copy( File src, File target )
throws IOException
{
RandomAccessFile in = null;
RandomAccessFile out = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try
{
in = new RandomAccessFile( src, "r" );
target.getParentFile().mkdirs();
out = new RandomAccessFile( target, "rw" );
out.setLength( 0 );
long size = in.length();
// copy large files in chunks to not run into Java Bug 4643189
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4643189
// use even smaller chunks to work around bug with SMB shares
// http://forums.sun.com/thread.jspa?threadID=439695
long chunk = ( 64 * 1024 * 1024 ) - ( 32 * 1024 );
inChannel = in.getChannel();
outChannel = out.getChannel();
int total = 0;
do
{
total += inChannel.transferTo( total, chunk, outChannel );
}
while ( total < size );
return total;
}
finally
{
close( inChannel );
close( outChannel );
close( in );
close( out );
}
}
private static void close( Closeable c )
throws IOException
{
if ( c != null )
{
c.close();
}
}
public static void delete( File file )
throws IOException
{
if ( file == null )
{
return;
}
Collection<File> undeletables = new ArrayList<File>();
delete( file, undeletables );
if ( !undeletables.isEmpty() )
{
throw new IOException( "Failed to delete " + undeletables );
}
}
private static void delete( File file, Collection<File> undeletables )
{
if ( file.isDirectory() )
{
for ( String child : file.list() )
{
delete( new File( file, child ), undeletables );
}
}
if ( !file.delete() && file.exists() )
{
undeletables.add( file.getAbsoluteFile() );
}
}
public static byte[] getContent( File file )
throws IOException
{
RandomAccessFile in = null;
try
{
in = new RandomAccessFile( file, "r" );
byte[] actual = new byte[(int) in.length()];
in.readFully( actual );
return actual;
}
finally
{
close( in );
}
}
public static boolean mkdirs( File directory )
{
if ( directory == null )
{
return false;
}
if ( directory.exists() )
{
return false;
}
if ( directory.mkdir() )
{
return true;
}
File canonDir = null;
try
{
canonDir = directory.getCanonicalFile();
}
catch ( IOException e )
{
return false;
}
File parentDir = canonDir.getParentFile();
return ( parentDir != null && ( mkdirs( parentDir ) || parentDir.exists() ) && canonDir.mkdir() );
}
}
|
Java
|
ISO-8859-2
| 3,421 | 2.609375 | 3 |
[] |
no_license
|
package br.com.project.geral.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import br.com.framework.implementacao.crud.ImplementacaoCrud;
import br.com.framework.interfaces.crud.InterfaceCrud;
import br.com.project.model.classes.Titulo;
@Controller
public class TituloController extends ImplementacaoCrud<Titulo> implements InterfaceCrud<Titulo> {
private static final long serialVersionUID = 1L;
@RequestMapping("**/gerarGraficoInicial")
public @ResponseBody String gerarGraficoInicial(@RequestParam(value = "dias") int dias) {
List<Map<String, Object>> titulosUltimosDias = getTitulosUltimosDias(dias);
/*pegando o total de linhas*/
int totalDeLinhas = titulosUltimosDias.size() + 1;
boolean semDados = false;
if (totalDeLinhas <= 1) {
semDados = true;
}
String[] dados = new String[totalDeLinhas];
int cont = 0;
if (semDados) {
dados[cont ++] = "[\"" + "Sem Dados" + "\"," + "\"" + 0 + "\"," + "\"" + 0 + "\"]";
} else {
dados[cont] = "[\"" + "Tipo" + "\"," + "\"" + "Quantidade" + "\"," + "\"" + "Mdia" + "\"]";
cont++;
for (Map<String, Object> objeto : titulosUltimosDias) {
dados[cont] = "[\"" + objeto.get("situacao") + "\"," + "\"" + objeto.get("quantidade") + "\"," + "\"" + objeto.get("media_valor") + "\"]";
cont++;
}
}
return Arrays.toString(dados);
}
private List<Map<String, Object>> getTitulosUltimosDias(int dias) {
StringBuilder sql = new StringBuilder();
sql.append("select count(1) ");
sql.append("as quantidade, ");
sql.append("tit_origem as situacao, ");
sql.append("trunc(avg(coalesce(tit_valor,0.00)), 2) as media_valor ");
sql.append("from titulo ");
sql.append("where cast(tit_datahora as date) >= (current_date - " + dias + ") ");
sql.append("and cast(tit_datahora as date) <= current_date ");
sql.append("group by tit_origem ");
sql.append(" ");
sql.append("union ");/*unindo as tabelas*/
sql.append(" ");
sql.append("select count(1) ");
sql.append("as quantidade, ");
sql.append("case when tit_baixado then 'BAIXADO' else 'EM ABERTO' end as situacao, ");
sql.append("trunc(avg(coalesce(tit_valor,0.00)), 2) as media_valor ");
sql.append("from titulo ");
sql.append("where cast(tit_datahora as date) >= (current_date - " + dias + ") ");
sql.append("and cast(tit_datahora as date) <= current_date ");
sql.append("group by tit_baixado ");
sql.append(" ");
sql.append("union "); /*unindo as tabelas*/
sql.append(" ");
sql.append("select count(1) ");
sql.append("as quantidade, ");
sql.append("tit_tipo as situacao, ");
sql.append("trunc(avg(coalesce(tit_valor,0.00)), 2) as media_valor ");
sql.append("from titulo ");
sql.append("where cast(tit_datahora as date) >= (current_date - " + dias + ") ");
sql.append("and cast(tit_datahora as date) <= current_date ");
sql.append("group by tit_tipo ");
sql.append(" ");
sql.append("order by quantidade, media_valor ");
return super.getSimpleJdbcTemplate().queryForList(sql.toString());/*retorna uma lista de objetos*/
}
}
|
JavaScript
|
UTF-8
| 371 | 2.59375 | 3 |
[] |
no_license
|
"use strict";
const fs = require("fs"), spawn = require("child_process").spawn, filename = "target.txt";
try {
if (!filename)
throw Error("A file must be specified or it exists");
fs.watch(filename, () => {
const ls = spawn("ls", ["-l", "-h", filename]);
ls.stdout.pipe(process.stdout);
});
}
catch(e) {
console.log(e);
}
|
Java
|
UTF-8
| 2,783 | 2.84375 | 3 |
[] |
no_license
|
package com.test.app.factory;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import com.test.app.bootstrap.DataModel;
import com.test.app.exception.InvalidOrderException;
public class BeverageFactory {
Map<String, List<String>> beverages = DataModel.getBeveragesMap();
Map<String, Double> itemRates = DataModel.getItemRates();
Map<String, Double> ingredientRates = DataModel.getIngredientRates();
public double getInvoiceFromOrder(String order) {
double cost = 0.0d;
List<String> orderItems = getItemsFromOrder(order.trim());
for (String item : orderItems) {
List<String> itemWithIngredients = getIngredientFromItem(item);
checkIfValidOrder(item);
cost = cost + calculateFinalInvoice(itemWithIngredients);
}
return cost;
}
private void checkIfValidOrder(String item) {
List<String> itemIngredients = getIngredientFromItem(item);
if (!beverages.containsKey(itemIngredients.get(0)))
throw new InvalidOrderException(
"Invalid item ordered -> " + item + " .Order again with valid menu item..!!");
List<String> allIngredients = beverages.get(itemIngredients.get(0));
Optional<String> duplicateIngredient = itemIngredients.stream()
.filter(i -> Collections.frequency(itemIngredients, i) > 1).findFirst();
if (duplicateIngredient.isPresent())
throw new InvalidOrderException("Duplicate ingredient not allowed -> " + duplicateIngredient.get());
List<String> ingredients = itemIngredients.subList(1, itemIngredients.size());
boolean validIngredients = ingredients.stream().allMatch(t -> allIngredients.stream().anyMatch(t::contains));
if (!validIngredients)
throw new InvalidOrderException("Invalid ingredient in order.Please check and order again..!!");
if (itemIngredients.size() == allIngredients.size() + 1)
throw new InvalidOrderException("Invalid Order..!! You cannot exclude all items from " + item);
}
private Double calculateFinalInvoice(List<String> itemWithIngredients) {
Double itemValue = itemRates.get(itemWithIngredients.get(0));
Double ingredientsValue = 0.0d;
if (itemWithIngredients.size() > 1)
for (int i = 1; i < itemWithIngredients.size(); i++) {
ingredientsValue = ingredientsValue + ingredientRates.get(itemWithIngredients.get(i));
}
return itemValue - ingredientsValue;
}
private List<String> getItemsFromOrder(String order1) {
return Arrays.stream(order1.split("(?!,\\s*-),")).map(String::trim).map(String::toLowerCase)
.collect(Collectors.toList());
}
private List<String> getIngredientFromItem(String item) {
return Arrays.stream(item.split(",")).map(s -> s.replace("-", "")).map(String::trim)
.collect(Collectors.toList());
}
}
|
Swift
|
UTF-8
| 1,936 | 2.734375 | 3 |
[] |
no_license
|
//
// MealDBAAPIClientTests.swift
// MealDBAppTests
//
// Created by Aldrich Co on 7/17/20.
// Copyright © 2020 Aldrich Co. All rights reserved.
//
import XCTest
@testable import MealDBApp
class APIClientTests: XCTestCase {
func testGetIngredients() {
let expect = expectation(description: "api response returned")
let session = MockSession()
session.nextData = Bundle(for: type(of: self))
.jsonData(named: "ingredients")
let apiClient: APIClientProtocol = APIClient(session: session)
var ingredients: [Ingredient]?
apiClient.getIngredients { result in
ingredients = result
expect.fulfill()
}
waitForExpectations(timeout: 5) { error in
XCTAssertNil(error)
XCTAssertNotNil(ingredients)
XCTAssertEqual(ingredients?.count, 569)
}
}
func testGetMealById() {
let expect = expectation(description: "api response returned")
let session = MockSession()
session.nextData = Bundle(for: type(of: self))
.jsonData(named: "meal")
let apiClient: APIClientProtocol = APIClient(session: session)
var meal: Meal?
apiClient.getMealById(7) { result in
meal = result
expect.fulfill()
}
waitForExpectations(timeout: 5) { error in
XCTAssertNil(error)
XCTAssertNotNil(meal)
XCTAssertEqual(meal?.idMeal, "52772")
XCTAssertEqual(meal?.strMeal, "Teriyaki Chicken Casserole")
}
}
func testGetMealsByIngredient() {
let expect = expectation(description: "api response returned")
let session = MockSession()
session.nextData = Bundle(for: type(of: self))
.jsonData(named: "meals-by-ingredient")
let apiClient: APIClientProtocol = APIClient(session: session)
var meals: [Meal]?
apiClient.getMealsByIngredient("baking powder") { result in
meals = result
expect.fulfill()
}
waitForExpectations(timeout: 5) { error in
XCTAssertNil(error)
XCTAssertNotNil(meals)
XCTAssertEqual(meals?.count, 13)
}
}
}
|
C++
|
GB18030
| 1,629 | 4.125 | 4 |
[] |
no_license
|
#include<iostream>
#include<vector>
using namespace std;
/*
ԭ⣺Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
һÿڽڵ㣬ͷָ룬ֻʹԿռҲֱĽڵֵ
˼·ʹĸָ룬p,qָԵǰڵнһָs¼ һָr¼ǰֱp,qһΪʱ
*/
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode *p, *q, *s, *r;
r = p = head;
q = p->next;
while(p != NULL && q != NULL){
s = q->next;
q->next = p;
p->next = s;
if(r == head) head = q; //ıͷָλ
else r->next = q; //мڵ
if(s == NULL) break; //β
r = p;
p = s;
q = p->next;
}
return head;
}
};
int main(){
Solution c;
int A[] = {7,6,5,4,3,2,1};
ListNode *head = NULL;
for(int i = 0; i < sizeof(A)/4; i++){
ListNode *s = new ListNode(A[i]);
s->next = head;
head = s;
}
ListNode *p = head;
while(p != NULL){
cout << p->val << " ";
p = p->next;
}
cout << endl;
p = c.swapPairs(head);
while(p != NULL){
cout << p->val << " ";
p = p->next;
}
return 0;
}
|
Java
|
UTF-8
| 889 | 2.28125 | 2 |
[] |
no_license
|
package com.rutine.troubleshoot.index;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author rutine
* @date 2020/1/15 13:51
*/
@SpringJUnitConfig
public class LogTest {
@DisplayName("测试log")
@RepeatedTest(10)
public void testLog() {
Logger logger = LoggerFactory.getLogger(LogTest.class);
int threadCount = 50;
int logCount = 1000000;
for (int i = 0; i < threadCount; i++) {
new Thread(() -> {
String threadName = Thread.currentThread().getName();
for (int j = 0; j < logCount; j++) {
logger.info("------> 测试log: {}", threadName);
}
}).start();
}
}
}
|
Markdown
|
UTF-8
| 1,263 | 2.8125 | 3 |
[] |
no_license
|
# A (nearly) offline map
Based on: leaflet.js, mapbox

You should be able to run this example **out of the box** after you put in your own Mapbox API key.
An offline map in one html file, without having to run a (localhost) server: explore geospatial data without having to upload them anywhere in the cloud! (e.g. for security reasons)
**All data is in one .html file**, as you can not serve external files to javascript due to CORS rules. You have to turn your icons into a base64 encoded string and paste your geojson in the file it's entirety.
This particular maps is using a mapbox base map. This can be changed to any other base map.
## What you need
* a **geojson** of your data. A handy tool for geojsons: [geojson.io](http://geojson.io)
* a mapbox **API key**
* **icons** base64 encoded
## Icons
Icons have to be put in the .html file in a base64 encoded string format
The format is `data:image/png;base64, <string>` This is how you get the string on linux:
```bash
base64 iconname.png
```
To copy it as well:
```bash
base64 iconname.png | tr -d "\n" | xclip -selection c
```
## Popups
If you want the popups to have more information, you can add another property to the geojson with some HTML in it.
|
Markdown
|
UTF-8
| 11,985 | 3.140625 | 3 |
[] |
no_license
|
WebScript Coursework 3 - University Of Portsmouth
Student Number: UP837518
The purpose of my dashboard was to create a general business purpose
environment. I chose this because based on the mark scheme we want to
attempt to have some sort of industry standard for things like our
design, to which I thought it was best to base my dashboard around
it. I feel as this is a dashboard that could be used in the industry
in the future as well and with more time and skills, could be developed
much further. To store all of my configurable data, I have chosen to
go with node localStorage and the same goes for storing the data for
all my widgets and panels. With a lot of information packed features
in my dashboard, you can do things such as click on a news source or
calendar event such as moon phases and it will redirect you to
it on a new tab.
How to run the dashboard?
Step 1 :Type npm install if node modules are not already installed
Step 2: Type npm start - this will run on localhost:8080
Key features
In this dashboard, you will find a total of 9 different widgets, of
which the admin has options to use any of their liking or for use
relevant to their businesses. There is also a 10th part which isn't a
widget but is a key feature to my dashboard which is known as drag &
drop. All of these features can only be accessed while in settings,
as soon as you sign out, you no longer have these abilities.
1.Calendar - I have gone for a calendar which is taking its API from
google with some event sources to choose from. When you click on the
source, you're source changes upon which one you select. A neat feature
is that when you click on a event, you are able to add events that are
personalised, save certain public holidays to your personal google
account and much more. All updates made on the external source will then
be displayed on your calendar on the dashboard in the calendar panel.
2.Weather - The weather shows the current weather and weather for the
next 4 days giving you a total of a 5 day forecast. There are already
a few locations which can be chosen from to view the area such as
Portsmouth or my home country Pakistan. There are also icons to view
weather it is day time or night time and also what the weather
conditions are. Features like the exact date and day are also shown.
Highest/Lowest Temp and Average Temp are also displayed. You can change
the weather source by going into the admin panel and selecting the
dropdown menu for the weather source and changing it to the desired
weather source and clicking apply changes.
3.News - I have gone with a news API, which has several news
sources to choose from. The feed includes news sources of different
order, not just main headlines which is something I like as I am able
to read all sorts of news. A feature I've implemented is the auto-scroll
which scroll at a steady pace but when you hover above it, It pauses
for you to view. After every article, there is a view article button
which ones pressed will redirect you to the page of the news article
so that you can see it in much more detail. You can change
the news source by going into the admin panel and selecting the
dropdown menu for the news source and changing it to the desired
news source and clicking apply changes.
4.Geolocation - Geolocation shows you your location based on area name
county and country name. This features works everywhere, hence the name
geolocation and can be accessed by all users to view exactly where they
are when using the dashboard.
5.Date & Time - This features allows you to see the day, date in format
MM:DD:YYYY and time in format HH:MM:SS. This feature I believe is really
essential for workplaces as the date and time is necessary for everyone
and a small but neat feature to have.
6.To do list - The To-do List can work in both the format of things to
do and also it can work in the form of announcements for the staff in
a business for things such as an upcoming event or something like a
important meeting or deadline. This API allows the admin to add
information/text of choice and remove it when its completed. To delete
you click on the text and it removes it and to add, you type the text
you want in the text box provided and click the add button which adds
it to the list.
7.Google Sign in - The purpose of this is, when you sign in, you are
redirected to the settings page where you can access the admin panel
to make changes you want such as news source or background colour.
Likewise, when your done making changes, you apply them and sign out
which will redirect you to the unconfigurable dashboard. To sign in,
you click on the 'Sign in with Google Button' and click your google
account and you will be signed in. To sign out, you must press the
'Sign Out' button on the admin panel.
8.Random Quote - This is a small feature which upon click of the
button generates a random quote every time you click 'Get Quote' which
I feel is a nice feature for a business environment for the user to
see when they see the dashboard, sort of like a quote of the day kind
of thing. To use this, click 'Get Quote' each time to change quote.
9.Background Colour - There is a ability to choose the background colour
from a drop down menu which can be chosen as proffered by the company.
They can choose to keep it one colour or alternate to however they wish.
If I would develop the dashboard for future use I would include background
image use so that the company can have there company logo as the background
if they wish to do so. You can change the background colour by going into
the admin panel and selecting the dropdown menu for the background colour
and changing it to the desired background colour and clicking apply changes.
10.Drag & Drop - All of the widgets/panels are able to be dragged and
dropped as desired by the admin and placed as they would like to view their
dashboard. This can be achieved by holding the left mouse button and moving
the mouse around to there desired location within the browser and letting
go where they wish to drop the item and place it there.
Design
My design section has been split into 2 in terms of description of the
design. The two sections are layout/frontend and system/backend design.
Layout design/Frontend - As mentioned before, I've created my dashboard for
a business use for all businesses of all types. This is very generic. So, I
have decided to go for a very simple yet effective design which works for
all works places, not just fancy ones. This is very good for usability
as I have tried to keep it so that users of all types can use it without
a problem with a classical look to it. I have made the website responsive
for all types of browsers on all screens and made it very easy to use with
very simple features. I've also included a drag and drop to rearrange the
panels/widget as the admin pleases. I've gone for a very classical and simple
look which I intend to give most users satisfaction for what they receive.
System design/Backend - For my backend I have decided to use a very simple
approach, the server.js file will be in the main directory and a new folder
called dashboard has been made for the actual dashboard. Within dashboard
we have all our html files which include both the settings page and the
unattended display, alongside all CSS files. Also within this I have included
the app.js file which includes all the relevant APIs that use the get and
post functions. Also a folder called js has been created which is essentially
for all the APIs that don't use keys or don't necessarily need keys. Certain
items are not APIs either such as the responsive of the dashboard which is
all included in the js file. I have used this format as this is the format
I have used throughout both first and second year so far.
The majority of my work is my own. I used external sources such as YouTube,
StackOverFlow and OpenClassrooms to get familiar with both Theoretical and
Coding functionality side of things. Most of this will be explained in the
reflection as I had to redo my dashboard 3 times because of misunderstanding
and problems I should have taken care of before it got deep into backend
coding. Overall, I mainly used express and rest and did not opt for a database
such as mysql, I attempted to make the application using node localStorage
which allows me to store data on the server and means that running the project
is as simple as installing npm and then running npm.
Implementation rationale
Overall, I am more than satisfied with the outcome of the weather as I
wanted a 5 day forecast format rather than just a daily format. As
personally I like to see the next few days and would see that of more
use for the businesses as well over just on the day weather format. The
design I went for was a bit of a unique one as I was able to show a
different yet ordered style for my weather API.
The news API was another thing I was happy with. Initially when looking
for an API for the news I found many but when I began the project my
JavaScript knowledge was not up to scratch and therefore a lot of issues
arises. This news had one problem on the unattended display, which was
having to scroll. Through rigorous research on how to solve this, I
came across an auto-scroll which I could change to a speed of my choice.
I found this useful as I was then able to display news with a scrollbar,
but not actually having to scroll, rather its done for you, which I think
was a nice touch over other news panels which would display top 3 headlines
for example, This way that I implemented allowed a lot more news to be
shown.
With my to-do List, I had to change it a couple of times and that was based
on my own learning phases of this teaching year. For this, I used a simple
to-do list at the end as I found adding too many features where causing issues,
so I would rather have a simple to-do list that works as best as it can and
store data on the server than one that is full of features but doesn't store
data on the server or work that well with the rest of my dashboard.
A final thing I really liked and developed into my dashboard was something
I learned towards the end of the teaching year in our lecture where, we
were taught how to implement Google Sign in API into our dashboard without
the use of passwords which was something to avoid in this dashboard as a
requirement given by our teachers. The way I adapted this was to combine the
sign in button with my settings so that once the admin signs in, they are then
redirected to the page with the admin panel to make their necessary changes.
Same way I implemented the sign out button from the admin panel so that when
the admin has made their changes they are redirected back to the unattended
display and logged out.
Conclusion
In conclusion, I hope you have found my dashboard of use. I made it with
the intent to develop it further after the deadline with more features
and better code quality. This would be perfect for myself and I feel as
for someone or a collective amount of people in a business which is the
purpose of this dashboard. I have made errors along the way, but again
they are learning curves and I hope to learn from the feedback given from
this coursework. This coursework alone has really helped my ability to code
JavaScript in specific NodeJS. I would have started at the start of the year
had I known the intensity and difficulty of this coursework and maybe would
been able to fix a lot of things that I could've had I not limited myself
to time.
|
Go
|
UTF-8
| 1,508 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
package bytecode
import (
"encoding/binary"
"io"
)
// Writer is used to serialize as3 bytecode
type Writer interface {
io.Writer
WriteU8(uint8) error
WriteU16(uint16) error
WriteS24(int32) error
WriteU30(uint32) error
WriteU32(uint32) error
WriteS32(int32) error
WriteD64(float64) error
}
type writer struct {
io.Writer
}
// NewWriter provides a simple way to create an as3 bytecode writer
func NewWriter(w io.Writer) Writer {
return &writer{w}
}
func (w *writer) write(data interface{}) error {
return binary.Write(w.Writer, binary.LittleEndian, data)
}
func (w *writer) WriteU8(x uint8) error {
return w.write(x)
}
func (w *writer) WriteU16(x uint16) error {
return w.write(x)
}
func (w *writer) WriteS24(x int32) error {
var bytes [3]byte
bytes[0] = byte(x & 0xff)
bytes[1] = byte((x >> 8) & 0xff)
bytes[2] = byte((x >> 16) & 0xff)
return w.write(bytes)
}
func (w *writer) writeVariableLength(x uint32) error {
var bytes [5]byte
var n uint32
// always write at least 1 byte
bytes[n] = byte(x & 0x7f)
n++
for (x >> (n * 7)) != 0 {
// set previous byte as not last
bytes[n-1] |= 0x80
bytes[n] = byte((x >> (n * 7)) & 0x7f)
n++
}
return w.write(bytes[0:n])
}
func (w *writer) WriteU30(x uint32) error {
return w.WriteU32(x)
}
func (w *writer) WriteU32(x uint32) error {
return w.writeVariableLength(x)
}
func (w *writer) WriteS32(x int32) error {
return w.writeVariableLength(uint32(x))
}
func (w *writer) WriteD64(x float64) error {
return w.write(x)
}
|
C#
|
UTF-8
| 848 | 2.6875 | 3 |
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WalkAction : Actions
{
Actor actorWalking;
public override void Initialise(Actor actorActingThisAction)
{
actorWalking = actorActingThisAction;
}
public override bool Perform()
{
if (actorWalking == null)
{
Debug.Log("actor not set");
return false;
}
if (actorWalking.completedMotionToMovePoint)
{
return false;
}
MoveActorToMovePointCell();
return true;
}
public void MoveActorToMovePointCell()
{
actorWalking.actorTransform.position = Vector3.MoveTowards(actorWalking.actorTransform.position, actorWalking.movePoint.position, actorWalking.walkSpeed * Time.fixedDeltaTime);
}
}
|
Markdown
|
UTF-8
| 2,431 | 3.015625 | 3 |
[] |
no_license
|
## Introduction
Lychee was originally developed by [electerious][1] ([Tobias Reich][2]). Lychee aims to be a great looking and easy-to-use photo-management-system that nearly anyone can use on their web server.
Since April 1st, 2018 this project has moved to it's own Organisation (LycheeOrg) where people are able to submit their fixes to it. We, the Organisation owners, want to thank electerious (Tobias Reich) for the opportunity to make this project live on.
## Schedule releases & Roadmap
We do not have schedule for releases such as every 6 months. Our releases should never contain breaking changes. That being said, we do not provide backward compatibility or hotfix for older versions. The `master` branch is the bleeding edge of Lychee. It contains the latest bugfixes and newest features. Once a sufficient number of hotfixes or new features has been merged into `master` we create a new release.
Generally, we follow semantic versioning: Major.minor.patch.
- Major releases provide a breaking change or significant refactoring of the full project (_e.g._, migration to a new front-end).
- minor releases have a database structural update or provide a notable change.
- patches for the rest.
## Security
In order to ensure maximum security some actions on Lychee are restricted by an admin authentication. The username and password are stored hashed with bcrypt in the database.
However as precaution, we provide a server-side command to easily erase those two data from the database in order to recover admin access. We consider this command safe as it requires a command line access to the server. A user gaining such rights is outside of our security scope as the server would be compromised.
## LycheeOrg
LycheeOrg is a GitHub organization of enthusiast developers determined to keep this project alive.
There is no commitment in time to the project. We understand that each member has their personal life and dedicate time as they see fit to the project.
If you start to contribute by opening multiple Pull Requests and adding more code to the database, it is likely you will be asked to join us.
There is no governance model. We currently have three admins: [d4715][3], [ildyria][4], [LudovicRousseau][5]. Decisions are made after discussions.
[1]: https://github.com/electerious
[2]: https://electerious.com
[3]: https://github.com/d7415
[4]: https://github.com/ildyria
[5]: https://github.com/LudovicRousseau
|
JavaScript
|
UTF-8
| 3,124 | 4.0625 | 4 |
[
"MIT"
] |
permissive
|
var student = {
"name": "Bob",
"pizzaPreference": "black olives and mushrooms",
"grades": {
"html": [90, 77],
"css": [82],
"js": [91, 90, 89]
},
"languages": [
"html", "css", "js"
],
"cars": [
{
"make": "honda",
"model": "civic",
"parkingPermits": [
{"name": "Travis Park Garage", "isActive": true},
{"name": "Apartment Complex", "isAvcive": false}
]
},
{
"make": "honda",
"model": "accord",
"parkingPermits": []
}
]
};
// Task Output
// ---- ------
// student.cars[1].make to get the second item in the array
//get Bob's name .............................................. 'Bob'
console.log(student.name)
// get Bob's pizzaPreference ................................... 'black olives and mushrooms'
console.log(student.pizzaPreference)
// get Bob's 2nd language ...................................... 'css'
console.log(student.languages[1])
// get Bob's grades for html ................................... [90, 77]
console.log(student.grades.html)
// get Bob's last grade for javascript ......................... 89
console.log(student.grades.js[student.grades.js.length-1])
//this is how we get the last grade even if his grade changes, it will always work on the last one
// get Bob's first language .................................... 'html'
console.log(student.languages[0])
// get the make of Bob's second car ............................ 'honda'
console.log(student.cars[1].make)
// number of parking permits for Bob's civic ................... 2
console.log(student.cars[0].parkingPermits.length)
// for Bob's accord .................. 0
console.log(student.cars[1].parkingPermits.length)
// find out if Bob's parking permit for travis park is active .. true
console.log(student.cars[0].parkingPermits[0].isActive)
// find the average of Bob's grades for html (your solution should not break if more items are added to the grades.html array)
var studentGrade = 0;
for (var i = 0; i <= student.grades.html.length-1 ; i += 1){
var studentGrade = studentGrade + student.grades.html[i];
}
var htmlGradeAverage = ((studentGrade )/ student.grades.html.length)
console.log(htmlGradeAverage)
//arrays are great with lists but objects are great with lists with identifiers of what that actual value is
//or if I want to use a forEach loop
var htmlGrades = student.grades.html;
var total = 0;
htmlGrades.forEach(function(grade){
total = total + grade;
});
console.log(student.name + " made the folllowing grade in HTML: " + (total/ htmlGrades.length) + "!" );
//or
function getAverageGrade(arrayOfNumbers){
var numberofGrades = arrayOfNumbers.length;
var total = 0;
var average;
arrayOfNumbers.forEach(function(grade){
total += grade;
});
average = total / numberofGrades;
return average
}
|
Markdown
|
UTF-8
| 5,364 | 2.96875 | 3 |
[] |
no_license
|
# Instalación
Existe dos versiones de Docker, una libre y otra que no lo es. Nos ocuparemos exclusivamente de la primera: [Docker CE (Community Edition)](https://docs.docker.com/install/).
## Disponibilidad
Docker CE está disponible para los siguientes sistemas GNU/Linux: CentOS, Debian, Fedora y Ubuntu. No todas están en múltiples arquitecturas, pero sí todas soportan _x86\_64/amd64_. Si tienes otra arquitectura u otro sistema es mejor que uses una máquina virtual para arrancar una distribución compatible.
Para más información sobre sistemas privativos soportados, leer la sección de [plataformas soportadas](https://docs.docker.com/install/#supported-platforms) de la documentación oficial.
## Instalación
Debido a que, dependiendo de la distribución, la forma de instalarlo difiere, es mejor consultar la documentación oficial para saber como instalar Docker en tu máquina.
* Ubuntu: [https://docs.docker.com/install/linux/docker-ce/ubuntu/](https://docs.docker.com/install/linux/docker-ce/ubuntu/)
* Debian: [https://docs.docker.com/install/linux/docker-ce/debian/](https://docs.docker.com/install/linux/docker-ce/debian/)
* CentOS: [https://docs.docker.com/install/linux/docker-ce/centos/](https://docs.docker.com/install/linux/docker-ce/centos/)
* Fedora: [https://docs.docker.com/install/linux/docker-ce/fedora/](https://docs.docker.com/install/linux/docker-ce/fedora/)
Si quieres instalar y probar Linux por primera vez, te recomendamos que uses una [versión LTS de Ubuntu](https://www.ubuntu.com/download/desktop), por ser fácil de instalar y tener un ciclo de mantenimiento de seguridad ampliado. Obviamente necesitas tener conexión a Internet para instalar y probar Docker.
Para saber si tienes Docker bien instalado, los tutoriales oficiales siempre te indican inicies un contenedor de ejemplo. Esto es lo que sucede:
!!! example
Los códigos de ejemplo irán acompañados de una caja como esta para poder copiar y pegar los comandos.
sudo docker run hello-world
El resultado es el siguiente:
:::bash hl_lines="1 2 6"
$ sudo docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
d1725b59e92d: Pull complete
Digest: sha256:0add3ace90ecb4adbf7777e9aacf18357296e799f81cabc9fde470971e499788
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
En la línea 1 estamos ejecutando el cliente de Docker, y estamos indicando que queremos ejecutar un contenedor a partir de la imagen [hello-world](https://hub.docker.com/_/hello-world/) del registro público de Docker.
Si es la primera vez que hemos ejecutado esa imagen, nos aparecerá la línea 2, que indica que la imagen no puede ser encontrada y va a proceder a buscarla, por defecto, en el registro público. Si tenemos conexión a Internet se descargará la imagen (línea 6) y automáticamente creará un contenedor.
Tanto si se ha descargado la imagen o ya estaba descargada, el contenedor se ejecutará, obteniendo el texto de bienvenida que se ve en el cuadro anterior.
## Configuración del usuario
Si estamos usando _Docker_ en nuestro ordenador personal, podemos configurar nuestro usuario para usar el cliente sin tener que poner _sudo_ delante. Para ello ejecuta lo siguiente:
!!! example
Añade tu usuario al grupo de docker.
sudo usermod -aG docker $USER
Para que los nuevos permisos surtan efecto, debes cerrar y volver a abrir la sesión. Para problemas relacionados con los permisos visitad [la página del manual oficial](https://docs.docker.com/install/linux/linux-postinstall/#manage-docker-as-a-non-root-user).
## Requisitos del curso
### Imágenes
Es necesario traer ya instaladas ciertas imágenes de contenedores. Ejecuta los siguientes comandos en tu equipo (si te da error de permisos asegúrate que has hecho el apartado anterior y abierto y cerrado la sesión).
!!! example
Instalar _WordPress_:
docker pull wordpress:latest
!!! example
Instalar _MariaDB_:
docker pull mariadb:latest
### Herramientas
También es necesario traer una herramienta llamada `Docker Compose`. Puedes instalarla con las instrucciones que hay en la página de [Instalación de Docker Compose](https://docs.docker.com/compose/install/).
Sin embargo, si usas _Ubuntu_ o _Debian_ puedes instalarlo de forma más fácil con _apt_:
!!! example
Instalación de _Docker Compose_:
sudo apt install docker-compose
|
Shell
|
UTF-8
| 1,368 | 3.109375 | 3 |
[
"Apache-2.0"
] |
permissive
|
pkg_name=sudo
pkg_origin=core
pkg_version=1.9.8p2
pkg_maintainer="The Habitat Maintainers <humans@habitat.sh>"
pkg_description="Execute a command as another user"
pkg_upstream_url=https://www.sudo.ws/
pkg_license=('ISC')
pkg_source="https://www.sudo.ws/dist/${pkg_name}-${pkg_version}.tar.gz"
pkg_shasum=9e3b8b8da7def43b6e60c257abe80467205670fd0f7c081de1423c414b680f2d
pkg_build_deps=(
core/diffutils
core/file
core/gcc
core/make
)
pkg_deps=(
core/coreutils
core/glibc
core/vim
)
pkg_bin_dirs=(
bin
sbin
)
pkg_include_dirs=(include)
do_prepare() {
if [[ ! -r /usr/bin/file ]]; then
ln -sv "$(pkg_path_for file)/bin/file" /usr/bin/file
_clean_file=true
fi
# Export variables to the direct path of executables
MVPROG="$(pkg_path_for coreutils)/bin/mv"
export MVPROG
VIPROG="$(pkg_path_for vim)/bin/vi"
export VIPROG
}
do_build() {
./configure --prefix="${pkg_prefix}" --with-editor="${VIPROG}" --with-env-editor
make
}
do_check() {
# Due to how file permissions are preserved during packaging, we must
# set a particular file to be owned by root for the `testsudoers/test3`
# regression test, which compares sudo permissions against a file with
# root ownership.
chown root:root plugins/sudoers/regress/testsudoers/test3.d/root
make check
}
do_end() {
if [[ -n "$_clean_file" ]]; then
rm -fv /usr/bin/file
fi
}
|
PHP
|
UTF-8
| 8,078 | 2.640625 | 3 |
[] |
no_license
|
<?php
class calendar {
protected $_db;
protected $_global;
protected $_reminderText = array("0" => "At Time of Start", "5" => '5 Minute before start', "15" => '15 Minute before start', "30" => '30 Minute before start', "60" => '1 Hour before start', "120" => '2 Hours before start', "1440" => '1 Day before start', "2880" => '2 Days before start');
protected $_email;
protected $_admin;
protected $_history;
public function __construct() {
global $userData;
// $this->_db = new db();
$this->_db = db::getInstance();
// print_r($this->_db);
$this->_global = $userData;
}
public function getSetting($user_id) {
$this->_db->where('user_id', $user_id);
$res = $this->_db->get('acd_calendar_settings');
return $res;
}
public function getcolor($type, $user_id, $own_id, $color_type) {
$user = $this->getSetting($own_id);
if (sizeof($user) != 0) {
$json = json_decode($user[0]['value'], true);
if (isset($json['users'])) {
$keys = array_keys($json['users']);
if ($type == 'users') {
$keys = array_keys($json['users']);
if (in_array($user_id, $keys)) {
return $json['users'][$user_id][$color_type];
} else {
return '#ff0000';
}
} else {
return $json['own'][$color_type];
}
} else {
if ($type == 'own') {
return $json['own'][$color_type];
} else {
return '#ff0000';
}
}
} else {
return '#ff0000';
}
}
// GET USER LIST.
public function getUsers($user_id) {
$this->_db->where('user_id !=' . $user_id); // FOR LOGIN USER
$this->_db->where("is_active!=-1"); // GET ONLY ACTIVE USER.
$result = $this->_db->get('acd_users');
$admin = array();
for ($c = 0; $c < sizeof($result); $c++) {
if ($result[$c]['role_id'] == 1) {
$result[$c]['color_event'] = $this->getcolor('users', $result[$c]['user_id'], $user_id, 'event');
$result[$c]['color_task'] = $this->getcolor('users', $result[$c]['user_id'], $user_id, 'task');
$admin[1][] = $result[$c]; // SAVE EXECUTIVE LIST ARRAY.
} else if ($result[$c]['role_id'] == 2) {
$result[$c]['color_event'] = $this->getcolor('users', $result[$c]['user_id'], $user_id, 'event');
$result[$c]['color_task'] = $this->getcolor('users', $result[$c]['user_id'], $user_id, 'task');
$admin[2][] = $result[$c]; // SAVE MANAGER LIST IN ARRAY.
} else if ($result[$c]['role_id'] == 3) {
$result[$c]['color_event'] = $this->getcolor('users', $result[$c]['user_id'], $user_id, 'event');
$result[$c]['color_task'] = $this->getcolor('users', $result[$c]['user_id'], $user_id, 'task');
$admin[3][] = $result[$c]; // SAVE BASIC USERS LIST IN ARRAY.
}
}
// LOGIN USERS EVENT/TASK COLOR.
$admin['own_event'] = $this->getcolor('own', 0, $user_id, 'event');
$admin['own_task'] = $this->getcolor('own', 0, $user_id, 'task');
return $admin;
}
public function getCalendar($value_data, $user_id, $start_date, $end_date) {
$result = array();
// WHEN THERE IS NO CHECKBOX IS SELECTED THEN RETURN BLANK ARRAY
$type = gettype($value_data);
if ($value_data == NULL || $value_data == " ") {
return $result;
}
// WHEN THERE IS ONE OR MORE CHECKBOX IS SELECTED.
$where = ' WHERE 1=1 ';
$where .= ' AND (acd_calendar.start_date BETWEEN "' . gmdate("Y-m-d", $start_date) . '" AND "' . gmdate("Y-m-d", $end_date) . '") ';
// THIS FUNCTION IS FOR SET WHERE CONDITION BASED ON USERS CHECKBOX SELECTED.
$uid = array();
if ($type == 'array') {
for ($i = 0; $i < sizeof($value_data); $i++) {
$users = explode("-", $value_data[$i]);
if ($users[0] != $uid && $users[1] == 2) {
array_push($uid, $users[0]);
}
$field = ($users[1] == 1) ? 'acd_calendar.created_by' : 'acd_calendar.assigned_to';
if ($i == 0) {
$where.=' AND (' . $field . ' = ' . $users[0] . ' AND acd_calendar.calendar_type=' . $users[1];
} else {
$where .= ' OR ' . $field . ' = ' . $users[0] . ' AND acd_calendar.calendar_type=' . $users[1];
}
if ($i == sizeof($value_data) - 1) {
$where .= ')';
}
}
}
// THIS IS THE QUERY.
$query = 'SELECT DISTINCT acd_calendar.calendar_id,acd_calendar.created_by,acd_calendar.calendar_for,CASE WHEN duration =1 THEN true ElSE false END as allDay ,acd_calendar.name as title, acd_calendar.calendar_type as calendar_type,acd_calendar.assigned_to, acd_calendar.start_date as start_date, acd_calendar.end_date as end_date, acd_calendar.due_date,acd_calendar.start_date as utc_strat_date,acd_calendar.end_date as utc_end_date,acd_calendar.status,CONCAT(users.name, " ",users.last_name) as assignedname FROM acd_calendar LEFT JOIN acd_users users on acd_calendar.assigned_to = users.user_id ' . $where;
$result = $this->_db->rawQuery($query);
/* SET COLOR FOR EACH EVENTS/TASKS. */
for ($c = 0; $c < sizeof($result); $c++) {
if ($result[$c]['calendar_type'] == 1) {
$result[$c]['start'] = $result[$c]['start_date'];
$result[$c]['end'] = $result[$c]['end_date'];
if ($result[$c]['allDay']) {
$result[$c]['end'] = date('Y-m-d H:i:s', strtotime($result[$c]['end'] . "+1 days"));
}
} else {
$result[$c]['start'] = $result[$c]['start_date'];
$result[$c]['end'] = $result[$c]['end_date'];
}
$type = ($result[$c]['calendar_type'] == 1) ? 'created_by' : 'assigned_to';
if ($user_id == $result[$c][$type]) {
$c1 = $this->getcolor('own', $result[$c]['created_by'], $user_id, 'event');
$c2 = $this->getcolor('own', $result[$c]['assigned_to'], $user_id, 'task');
} else {
$c1 = $this->getcolor('users', $result[$c]['created_by'], $user_id, 'event');
if (in_array($result[$c]['assigned_to'], $uid)) {
$c2 = $this->getcolor('users', $result[$c]['assigned_to'], $user_id, 'task');
} else {
$c2 = $this->getcolor('users', $result[$c]['created_by'], $user_id, 'task');
}
}
$result[$c]['color'] = ($result[$c]['calendar_type'] == 1) ? $c1 : $c2;
}
return $result;
}
/* SAVE COLOR SETTINGS. */
public function saveSetings($data) {
$insert = json_encode($data['color']);
$arr = $this->getSetting($data['user_id']);
if (sizeof($arr) == 0) {
$array = array("user_id" => $data['user_id'], "value" => $insert, "created_date" => date('Y-m-d H:i:s'));
$id = $this->_db->insert('acd_calendar_settings', $array);
} else {
$array = array("user_id" => $data['user_id'], "value" => $insert, "modified_date" => date('Y-m-d H:i:s'));
$this->_db->where('user_id', $data['user_id']);
$id = $this->_db->update('acd_calendar_settings', $array);
}
if ($id) {
$result['error'] = false;
$result['msg'] = "Successfully Set";
} else {
$result['error'] = true;
$result['msg'] = "error";
}
return $result;
}
}
|
Python
|
UTF-8
| 249 | 3.484375 | 3 |
[] |
no_license
|
def testEqual(output, expected_out):
if output == expected_out:
print("Pass")
return True
else:
print("Wanted this: ", expected_out)
print("Got this crap: ", output)
print("Fail")
return False
|
C++
|
UTF-8
| 5,670 | 3.4375 | 3 |
[] |
no_license
|
#include <iostream>
#include<vector>
#include<queue>
#include<stack>
#include "State.h"
#include "Node.h"
#include<string>
#include <stdlib.h>
#include<time.h>
#include<unordered_set>
#include<map>
State setManualInitialState();
void Astar(Node initNode,State goalState);
pair<State, State> problemGenerator(int, int);
void printSolutionPath(Node* goalState);
using namespace std;
int main(int argc,char* argv[]) {
if (argc != 3) {
cerr << "Please enter 3 arguments: Blocksworld <numBlocks> <numStacks>";
return 1;
}
int numBlocks = atoi(argv[1]);
int numStacks = atoi(argv[2]);
State initState, goalState;
pair<State, State> problemStates;
// initState = setManualInitialState(); //Get user input for initial State
problemStates = problemGenerator(numBlocks, numStacks); //Take inputs from user and generate inital state
goalState = problemStates.second;
initState = problemStates.first;
Node initNode(initState, NULL, goalState);
initNode.goalState = goalState;
Astar(initNode, goalState);
return 0;
}
pair<State,State> problemGenerator(int numBlocks, int numStacks) {
State initState,goalState;
pair<State, State> problemStates;
int blocksRemaining;
vector<char> blockNames;
//cout << "Input the number of Stacks:";
//cin >> numStacks;
vector<stack<char>> initStack(numStacks),goalStack(numStacks);
//cout << "Input the number of Blocks:";
//cin >> numBlocks;
srand(time(NULL)); // initializing random seed
// Random initial state generation
for (int i = 0; i < numBlocks; i++) {
blockNames.push_back(('A' + i));
goalStack[0].push(('A' + i));
}
goalState.set_state(goalStack);
random_shuffle(blockNames.begin(), blockNames.end()); // shuffling the blocks in place
//filling stacks [0 , numStacks-2]
blocksRemaining = numBlocks;
int ptr_start = 0,ptr_end=0;
for (int i = 0; i < numStacks-1; i++)
{
ptr_start = ptr_end;
ptr_end = ptr_start + rand() % blocksRemaining;
for (int j = ptr_start; j <ptr_end; j++)
initStack[i].push(blockNames[j]);
blocksRemaining = numBlocks - ptr_end;
}
// filling the last stack.
for (int j = ptr_end; j < numBlocks; j++)
initStack[numStacks-1].push(blockNames[j]);
initState.set_state(initStack);
problemStates.first = initState;
problemStates.second = goalState;
return problemStates;
}
State setManualInitialState() {
State initState;
vector<stack<char>> st;
int num_stacks;
cout << "Input the number of stacks: \t";
cin >> num_stacks;
for (int i = 0; i < num_stacks; i++)
{
int num_elements;
cout << "Enter number of elements in stack" << i<<":\t";
cin >> num_elements;
cout << "\n Enter the elements in the stack" << i<<":\t";
stack<char> temp_stack;
for (int j = 0; j < num_elements; j++)
{
char elem;
cin >> elem;
temp_stack.push(elem);
}
st.push_back(temp_stack);
}
initState.set_state(st);
return initState;
}
void Astar(Node initNode,State goalState) {
Node* iterNode;
unordered_set<string> discoveredStates;
map<string, Node*> inQueue;
long totalGoalTests=0;
// Building the frontier
auto cmp = [](Node* left, Node* right) {return (left->totalCost) > (right->totalCost);};
priority_queue<Node*, vector<Node*>, decltype(cmp)> frontier(cmp);
frontier.push(&initNode); // pushing the initial Node (root)
discoveredStates.insert(initNode.get_state().stateToString()); //updating the discoveredStates
inQueue[initNode.get_state().stateToString()] = &initNode;
iterNode = frontier.top();
cout << "Goal State:" << endl;
goalState.print_state();
cout << endl;
cout << "Initial State:" << endl;
iterNode->get_state().print_state();
cout << endl;
int iterNum = 0;
cout << "Starting Astar!"<<endl;
while (!(iterNode->get_state().isEqualState(goalState))) {
vector<Node*> children;
//poping the top element and removing from the inQueue map
frontier.pop();
auto it = inQueue.find(iterNode->get_state().stateToString());
if(it!=inQueue.end())
inQueue.erase(it);
iterNode->generate_children(iterNode);
children = iterNode->get_children();
for (int i = 0; i < children.size(); i++) {
auto got = discoveredStates.find(children[i]->get_state().stateToString());
if (got == discoveredStates.end()) {
frontier.push((children[i]));
inQueue[children[i]->get_state().stateToString()] = children[i];
} else {
auto iter = inQueue.find(children[i]->get_state().stateToString());
if( (iter!=inQueue.end())&& (children[i]->totalCost < (iter->second)->totalCost)) {
frontier.push((children[i]));
inQueue[children[i]->get_state().stateToString()] = children[i];
}
}
}
iterNode = frontier.top();
++iterNum;
if(iterNum % 5 == 0)
cout << "iter=" << iterNum << ", " << "queue=" << inQueue.size() << ", " << "f=g+h=" << iterNode->totalCost << ", " << "depth=" << iterNode->gCost<<endl;
}
totalGoalTests = iterNum;
cout << "..." << endl << "success!" << "depth=" << iterNode->gCost << ", total_goal_tests="<<totalGoalTests<<", max_queue_size="<<inQueue.size()<<endl;
//cout << iterNode->gCost <<"\t"<< totalGoalTests << "\t" << inQueue.size() << endl;
printSolutionPath(iterNode);
cout << endl;
}
void printSolutionPath(Node* goalState) {
stack<Node*> solutionPath;
Node* iterNode = goalState;
//pushing into stack to print the path iin reverse order
while (iterNode->parent != NULL) {
solutionPath.push(iterNode);
iterNode = iterNode->parent;
}
solutionPath.push(iterNode); //pushing the root/initial node
//prining the path
for (stack<Node*> dump = solutionPath; !dump.empty(); dump.pop()) {
dump.top()->get_state().print_state();
cout << endl;
}
}
|
JavaScript
|
UTF-8
| 17,428 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
/* first serious attempt at an Isopath AI:
* - based on a negamax search, but cutting down the search space
* by not searching every possibility of tile placement
* - algorithm is mostly as intended, but efficiency is poor
*/
function Sirius(isopath, searchdepth) {
this.isopath = isopath;
this.searchdepth = searchdepth;
this.saved_moves = [];
this.transpos = {nelems: 0};
this.bestmovetype = {};
this.triedmovetype = {};
}
Sirius.piece_score = function(place, colour) {
if (colour == 'black') {
// just invert the location and then score as if it's white
place = place.replace('a', 'G').replace('b', 'F').replace('c', 'E')
.replace('g', 'a').replace('f', 'b').replace('e', 'c')
.toLowerCase();
}
var row = 4 + place.charCodeAt(0) - 'a'.charCodeAt(0);
return 100 + row*row*10;
};
Sirius.maxscore = 100000;
Sirius.prototype.evaluate = function(isopath) {
// one score for tile values for each player
var whitetiles = 0;
// small extra bonus for controlling the centre
whitetiles += isopath.board["d1"]-1; // teleport
whitetiles += isopath.board["d4"]-1; // centre of board
whitetiles += isopath.board["d7"]-1; // teleport
// big bonus for building on home row
for (var col = 1; col <= 4; col++) {
if (isopath.board["a" + col] != 2)
whitetiles -= 2;
if (isopath.board["g" + col] != 0)
whitetiles += 2;
}
// big bonus for approaching home row
for (var col = 1; col <= 5; col++) {
whitetiles -= 5 * (2-isopath.board["b" + col]);
whitetiles += 5 * isopath.board["f" + col];
}
// medium bonus for 1 away from approaching home row
for (var col = 1; col <= 6; col++) {
whitetiles -= 2 * (2-isopath.board["c" + col]);
whitetiles += 2 * isopath.board["e" + col];
}
// small bonus for middle row
for (var col = 1; col <= 7; col++) {
whitetiles += (2-isopath.board["d" + col]);
whitetiles -= isopath.board["d" + col];
}
var tilescore = isopath.curplayer == 'white' ? whitetiles : -whitetiles;
// one score for piece values for each player
var whitepieces = 0;
for (var i = 0; i < isopath.board['white'].length; i++) {
var place = isopath.board['white'][i];
whitepieces += Sirius.piece_score(place, 'white');
// score us some points for ability to move
for (var j = 0; j < isopath.adjacent[place]; j++) {
whitepieces += isopath.board[isopath.adjacent[place][j]];
}
}
for (var i = 0; i < isopath.board['black'].length; i++) {
var place = isopath.board['black'][i];
whitepieces -= Sirius.piece_score(place, 'black');
// score us some points for ability to move
for (var j = 0; j < isopath.adjacent[place]; j++) {
whitepieces -= (2-isopath.board[isopath.adjacent[place][j]]);
}
}
var piecescore = isopath.curplayer == 'white' ? whitepieces : -whitepieces;
// TODO: some extra part of piecescore based on the shortest path for this piece
// to get to a free slot on the enemy's home row, counting number of turns
// combine those 2 scores into an evaluation
var score = tilescore + piecescore;
if (score > Sirius.maxscore || score < -Sirius.maxscore)
console.log("Generated score " + score + " out of range; adjust maxscore?");
return score;
};
// XXX: h should be either [0,1] when placing a tile or [1,2] when removing one
Sirius.prototype.locations_at_heights = function(isopath, h) {
var p = isopath.all_places;
var possible = [];
for (var i = 0; i < p.length; i++) {
// needs to be an allowable height, and can't have a piece on it
if (h.indexOf(isopath.board[p[i]]) == -1 || isopath.piece_at(p[i]) != '')
continue;
// can't touch our own home row
if (isopath.homerow[isopath.curplayer].indexOf(p[i]) != -1)
continue;
if (isopath.playerlevel[isopath.curplayer] == 2) {
// white doesn't want to take off black home row
if (h[0] != 0 && isopath.homerow[isopath.other[isopath.curplayer]].indexOf(p[i]) != -1)
continue;
} else {
// black doesn't want to place on white home row
if (h[0] == 0 && isopath.homerow[isopath.other[isopath.curplayer]].indexOf(p[i]) != -1)
continue;
}
possible.push(p[i]);
}
// XXX: what better can we do here? is this even possible?
if (possible.length == 0)
return 'xx';
return possible;
};
Sirius.prototype.strboard = function(isopath) {
var s = '';
for (var i = 0; i < isopath.all_places.length; i++) {
s += "" + isopath.board[isopath.all_places[i]];
}
s += ";";
for (var i = 0; i < isopath.board['white'].length; i++) {
s += isopath.board['white'][i];
}
s += ";";
for (var i = 0; i < isopath.board['black'].length; i++) {
s += isopath.board['black'][i];
}
s += ";" + isopath.curplayer;
return s;
};
Sirius.prototype.dfs = function(isopath, depth_remaining, alpha, beta) {
// if they've just won, we've lost
if (isopath.winner()) {
throw "game shouldn't have ended";
}
// TODO: instead of re-building these at each invocation of dfs(), just keep
// track of it every time we play or undo a move
var possiblefrom = this.locations_at_heights(isopath, [1,2]);
var possibleto = this.locations_at_heights(isopath, [0,1]);
function randtilefrom() {
return possiblefrom[Math.floor(Math.random() * possiblefrom.length)];
}
function randtileto() {
return possibleto[Math.floor(Math.random() * possibleto.length)];
}
alphaorig = alpha;
// https://en.wikipedia.org/wiki/Negamax#Negamax_with_alpha_beta_pruning_and_transposition_tables
var trans = this.transpos[this.strboard(isopath)];
if (trans && trans.depth_remaining >= depth_remaining) {
if (trans.flag == 'exact') {
return {
score: trans.score,
move: trans.move,
};
} else if (trans.flag == 'lowerbound' && trans.score > alpha) {
alpha = trans.score;
} else if (trans.flag == 'upperboard' && trans.score < beta) {
beta = trans.score;
}
if (alpha >= beta) {
return {
score: trans.score,
move: trans.move,
};
}
}
var me = isopath.curplayer;
var you = isopath.other[me];
// if we can win the game instantly by capturing their final piece, do so
if (isopath.board[you].length == 1) {
var adjacent_men = 0;
var adjs = isopath.adjacent[isopath.board[you][0]];
for (var i = 0; i < adjs.length; i++) {
if (isopath.piece_at(adjs[i]) == me)
adjacent_men++;
}
if (adjacent_men >= 2) {
return {
move: [["capture",isopath.board[you][0]]],
score: Sirius.maxscore - 20 + depth_remaining, // "- 20 + depth_remaining" means we prefer an earlier win over a later one
};
}
}
// if we can win the game instantly by moving onto their home row, do so
for (var i = 0; i < isopath.board[me].length; i++) {
var from = isopath.board[me][i];
var adjs = isopath.adjacent[from];
for (var j = 0; j < adjs.length; j++) {
var to = adjs[j];
if (isopath.homerow[you].indexOf(to) != -1 && isopath.piece_at(to) == '') {
// our piece at 'from' is adjacent to the location 'to' which is an unoccupied tile on our opponent's home row
if (isopath.board[to] == 1) {
// move a tile and then move on to the location
var tileto, tilefrom;
if (isopath.playerlevel[me] == 2) {
tileto = to;
do {
tilefrom = randtilefrom();
} while (tilefrom == tileto);
} else {
tilefrom = to;
do {
tileto = randtileto();
} while (tileto == tilefrom);
}
return {
move: [["tile",tilefrom,tileto],["piece",from,to]],
score: Sirius.maxscore - 20 + depth_remaining, // "- 20 + depth_remaining" means we prefer an earlier win over a later one
};
} else if (isopath.board[to] == isopath.playerlevel[me]) {
// no need to move a tile, step straight there
return {
move: [["piece",from,to]],
score: Sirius.maxscore - 20 + depth_remaining, // "- 20 + depth_remaining" means we prefer an earlier win over a later one
};
}
}
}
}
// if this is the limit of the search depth, just return the score
if (depth_remaining == 0) {
return {
move: [],
score: this.evaluate(isopath),
};
}
// generate candidate moves:
var candidate_moves = [];
// capture moves
// TODO: also consider moving a piece instead of a tile in the second half of the capture move, where possible
for (var i = 0; i < isopath.board[you].length; i++) {
var adjacent_men = 0;
var adjs = isopath.adjacent[isopath.board[you][i]];
for (var j = 0; j < adjs.length; j++) {
if (isopath.piece_at(adjs[j]) == me)
adjacent_men++;
}
// if this man is capturable, consider capturing him, and then move a random 1-level tile to another 1-level place
if (adjacent_men >= 2) {
var tileto, tilefrom;
var m, cnt = 0;
do {
do {
tilefrom = randtilefrom();
tileto = randtileto();
} while (tileto == tilefrom);
m = [["capture",isopath.board[you][i]],["tile",tilefrom,tileto]];
} while (!isopath.isLegalMove(m) && ++cnt < 5);
m.push("capture");
candidate_moves.push(m);
}
}
var piece_moves = [];
var already_valid_piece_moves = [];
// try moving each of our pieces into each adjacent location
for (var i = 0; i < isopath.board[me].length; i++) {
var place = isopath.board[me][i];
for (var j = 0; j < isopath.adjacent[place].length; j++) {
var adjplace = isopath.adjacent[place][j];
if (isopath.piece_at(adjplace) == '') {
piece_moves.push(['piece',place,adjplace]);
if (isopath.board[adjplace] == isopath.playerlevel[me]) {
already_valid_piece_moves.push(['piece',place,adjplace]);
}
}
}
}
for (var i = 0; i < piece_moves.length; i++) {
// move a brick to facilitate the piece move if necessary, or alternatively the best-scoring as decided by some heuristic
var from = piece_moves[i][1];
var to = piece_moves[i][2];
var tile_moves = [];
// TODO: a better heuristic to pick 4 good-looking tile moves instead of choosing 4 at random (i.e. use knowledge of
// the evaluation function to try to pick the best places to put them)
if (isopath.board[to] == 1) {
// need to add/remove a tile in order to move here
if (isopath.playerlevel[me] == 2) {
// place a tile here
tile_moves.push(["tile",randtilefrom(),to]);
} else {
// remove the tile here
tile_moves.push(["tile",to,randtileto()]);
}
} else if (isopath.board[to] == isopath.playerlevel[me]) {
// can move here straight away, need to move a tile elsewhere
var tileto, tilefrom;
do {
tilefrom = randtilefrom();
tileto = randtileto();
} while (tileto == tilefrom);
tile_moves.push(["tile",tilefrom,tileto]);
} else if (already_valid_piece_moves.length > 0) {
var m, cnt = 0;
// can't move here at all
// add/remove a tile so that we might be able to move here next turn
do {
if (isopath.playerlevel[me] == 2) {
// place a tile here
m = [["tile",randtilefrom(),to],already_valid_piece_moves[Math.floor(Math.random() * already_valid_piece_moves.length)]];
} else {
// remove the tile here
m = [["tile",to,randtileto()],already_valid_piece_moves[Math.floor(Math.random() * already_valid_piece_moves.length)]];
}
} while (!isopath.isLegalMove(m) && ++cnt < 5);
m.push("cantmovehere");
candidate_moves.push(m);
}
// add all of our considered tile moves and this piece move to the list of candidate moves
for (var j = 0; j < tile_moves.length; j++) {
candidate_moves.push([tile_moves[j], piece_moves[i],"tilemoveto" + isopath.board[to]]);
}
}
// TODO: track which "generator" the most decisive moves come from, and increase the
// amount of moves that that generator is allowed to generate?
var best = {
move: [],
score: -Sirius.maxscore,
};
//console.log("Got " + candidate_moves.length + " moves to try");
// order moves: we want the best moves to be tried first in order to take most
// advantage of alpha-beta pruning
// (this is a performance improvement rather than a play-style improvement, modulo
// the extent to which improved performance allows deeper search)
candidate_moves.sort(function(a,b) {
// try captures first
if (a[0][0] == 'capture')
return -1;
if (b[0][0] == 'capture')
return 1;
if (a[1] == undefined)
return 1;
if (b[1] == undefined)
return -1;
var quality = {
capture: 10,
tilemoveto1: 9,
cantmovehere: 8,
tilemoveto0: 7, // XXX: to0 and to2 should be swapped if playing as black
tilemoveto2: 6,
};
if (a[3] != b[3])
return quality[b[3]] - quality[a[3]];
// if not a capture, _[0] is a tile move and _[1] is a piece move
// try to advance towards the opponent's home row
if (me == 'white')
return b[1][1].charCodeAt(0) - a[1][1].charCodeAt(0);
else
return a[1][1].charCodeAt(0) - b[1][1].charCodeAt(0);
// how else could we order moves?
return 0;
});
var tried = {};
// now try each of the candidate moves, and return the one that scores best
for (var i = 0; i < candidate_moves.length; i++) {
var movetype = 'unknown';
if (candidate_moves[i].length == 3) {
movetype = candidate_moves[i].pop();
}
// don't test duplicate moves
if (tried[JSON.stringify(candidate_moves[i])])
continue;
tried[JSON.stringify(candidate_moves[i])] = true;
// or illegal moves
if (!isopath.isLegalMove(candidate_moves[i]))
continue;
if (!this.triedmovetype[movetype])
this.triedmovetype[movetype] = 0;
this.triedmovetype[movetype]++;
isopath.playMove(candidate_moves[i], 'no-legality-check');
var response = this.dfs(isopath, depth_remaining-1, -beta, -alpha);
isopath.undoMove();
if (-response.score > best.score || best.move.length == 0) {
best = {
score: -response.score,
move: candidate_moves[i],
type: movetype,
};
}
if (-response.score > alpha)
alpha = -response.score;
if (alpha >= beta)
break;
}
// jescache...
if (this.transpos.nelems > 50000) {
this.transpos = {nelems: 0};
}
// https://en.wikipedia.org/wiki/Negamax#Negamax_with_alpha_beta_pruning_and_transposition_tables
var ttentry = {
score: best.score,
move: best.move,
depth_remaining: depth_remaining,
};
if (best.score <= alphaorig) {
ttentry.flag = 'upperbound';
} else if (best.score >= beta) {
ttentry.flag = 'lowerbound';
} else {
ttentry.flag = 'exact';
}
this.transpos[this.strboard(isopath)] = ttentry;
this.transpos.nelems++;
if (!this.bestmovetype[best.type])
this.bestmovetype[best.type] = 0;
this.bestmovetype[best.type]++;
return best;
}
Sirius.prototype.move = function() {
var best = this.dfs(this.isopath.clone(), this.searchdepth, -Sirius.maxscore, Sirius.maxscore);
console.log(best);
console.log(this.bestmovetype);
console.log(this.triedmovetype);
return best.move;
};
IsopathAI.register_ai('sirius', 'Sirius', function(isopath) {
return new Sirius(isopath, 6);
});
IsopathAI.register_ai('sirius-fast', 'Sirius (weaker)', function(isopath) {
return new Sirius(isopath, 4);
});
|
Java
|
UTF-8
| 4,212 | 2.296875 | 2 |
[] |
no_license
|
package com.modularity.common.base;
import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.readystatesoftware.systembartint.SystemBarTintManager;
public abstract class BaseActivity extends AppCompatActivity {
public final String TAG = this.getClass().getSimpleName();
protected boolean isNormal = true; //适配特殊机型所用-是否正常进入 true表示是正常进入 false表示非正常进入
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {// 非正常关闭
restoreConstants(savedInstanceState);
isNormal = false;
}
setStatuBarStyle(true);
BaseAppManager.getInstance().addActivity(this);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
/**
* 初始化view
*/
protected void initViews() {
}
/**
* 初始化数据
*/
protected void initData() {
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
/**
* 读取数据-->非正常状态下使用
*/
protected void restoreConstants(Bundle savedInstanceState) {
}
@Override
public void finish() {
super.finish();
BaseAppManager.getInstance().removeActivity(this);
}
/**
* 设置沉浸式状态栏颜色
*/
public void setStatusBarTintColor(String barColor) {
// 4.4及以上版本开启
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
// 自定义颜色
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setTintColor(Color.parseColor(barColor));
// enable status bar tint
tintManager.setStatusBarTintEnabled(true);
// enable navigation bar tint
// tintManager.setNavigationBarTintEnabled(true);
}
}
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
public void setStatusBarColor(int colorResId) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(this.getResources().getColor(colorResId));
//底部导航栏
//window.setNavigationBarColor(activity.getResources().getColor(colorResId));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将状态栏颜色变为深色
*
* @param dark true
*/
public void setStatuBarStyle(boolean dark) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View decor = getWindow().getDecorView();
if (dark) {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
} else {
// We want to change tint color to white again.
// You can also record the flags in advance so that you can turn UI back completely if
// you have set other flags before, such as translucent or full screen.
decor.setSystemUiVisibility(0);
}
// getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
}
}
|
C++
|
ISO-8859-1
| 3,069 | 3 | 3 |
[] |
no_license
|
#pragma once
#include "ceMath.h"
namespace ceEngineSDK
{
class CE_UTILITY_EXPORT ceVector2D
{
public:
float X;
float Y;
/************************************************************************************************************************/
/* Constructores y Destructores */
/************************************************************************************************************************/
ceVector2D();
ceVector2D(float InX, float InY);
~ceVector2D();
/************************************************************************************************************************/
/* Declaracin de operadores aritmticos */
/************************************************************************************************************************/
ceVector2D operator+(const ceVector2D& V) const; //Suma
ceVector2D operator-(const ceVector2D& V) const; //Resta
ceVector2D operator*(float Scale) const; //Multiplicacin (escalar)
ceVector2D operator*(const ceVector2D& V) const; //Multiplicacin (vector)
ceVector2D operator/(float Scale) const; //Divisin (escalar)
ceVector2D operator/(const ceVector2D& V) const; //Divisin (vector)
/************************************************************************************************************************/
/* Declaracin de operadores lgicos */
/************************************************************************************************************************/
bool operator==(const ceVector2D& V) const; //Igual a
bool operator!=(const ceVector2D& V) const; //Diferente a
bool operator<(const ceVector2D& Other) const; //Menor que
bool operator>(const ceVector2D& Other) const; //Mayor que
bool operator<=(const ceVector2D& Other) const; //Menor o igual a
bool operator>=(const ceVector2D& Other) const; //Mayor o igual a
bool Equals(const ceVector2D& V, float Tolerance) const; //Compara si son "iguales" manejando una toleracia
/************************************************************************************************************************/
/* Declaracin de operadores de asignacin compuesta */
/************************************************************************************************************************/
ceVector2D& operator+=(const ceVector2D& V);
ceVector2D& operator-=(const ceVector2D& V);
ceVector2D& operator*=(float Scale);
ceVector2D& operator/=(float Scale);
ceVector2D& operator*=(const ceVector2D& V);
ceVector2D& operator/=(const ceVector2D& V);
float operator|(const ceVector2D& V) const; //Dot Product
float operator^(const ceVector2D& V) const; //Cross Product
float Magnitud(const ceVector2D& V);
ceVector2D Normalize(const ceVector2D& V);
float DotProduct(const ceVector2D& A, const ceVector2D& B);
};
}
|
Python
|
UTF-8
| 5,019 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
import argparse
from pathlib import Path
from typing import Dict
import pandas as pd
from emotion_recognition.stats import alpha
emotion_map = {
'A': 'anger',
'D': 'disgust',
'F': 'fear',
'H': 'happy',
'S': 'sad',
'N': 'neutral',
}
def write_labelset(name: str, labels: Dict[str, str]):
with open('labels_{}.csv'.format(name), 'w') as label_file:
label_file.write("Name,Emotion\n")
for name, emo in labels.items():
if name == '1076_MTI_SAD_XX':
# This one has no audio signal
continue
label_file.write("{},{}\n".format(name, emotion_map[name[9]]))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=Path, help="Location of CREMA-D data.")
args = parser.parse_args()
files = sorted(args.input.glob('AudioWAV/*.wav'))
# Write default clipset and annotationset using acted emotion
with open('clips2.csv', 'w') as clip_file, \
open('labels2.csv', 'w') as label_file:
clip_file.write("Name,Path,Speaker\n")
label_file.write("Name,Emotion\n")
for path in files:
name = path.stem
if name == '1076_MTI_SAD_XX':
# This one has no audio signal
continue
speaker = name[:4]
clip_file.write("{0},AudioWAV/{0}.wav,{1}\n".format(name, speaker))
label_file.write("{},{}\n".format(name, emotion_map[name[9]]))
summaryTable = pd.read_csv('processedResults/summaryTable.csv',
low_memory=False, index_col=0)
summaryTable['ActedEmo'] = summaryTable['FileName'].apply(lambda x: x[9])
for mode in ['VoiceVote', 'FaceVote', 'MultiModalVote']:
# Proportion of majority vote equivalent to acted emotion
accuracy = (summaryTable[mode] == summaryTable['ActedEmo'].sum()
/ len(summaryTable))
print("Acted accuracy using {}: {:.3f}".format(mode, accuracy))
# Majority vote annotations from other modalities
valid = summaryTable['MultiModalVote'].isin(list('NHDFAS'))
multiModal = summaryTable[valid]
labels = dict(zip(multiModal['FileName'],
multiModal['MultiModalVote']))
write_labelset('multimodal', labels)
valid = summaryTable['FaceVote'].isin(list('NHDFAS'))
face = summaryTable[valid]
labels = dict(zip(face['FileName'],
face['FaceVote']))
write_labelset('face', labels)
valid = summaryTable['VoiceVote'].isin(list('NHDFAS'))
voice = summaryTable[valid]
labels = dict(zip(voice['FileName'],
voice['VoiceVote']))
write_labelset('voice', labels)
finishedResponses = pd.read_csv('finishedResponses.csv', low_memory=False,
index_col=0)
finishedResponses['respLevel'] = pd.to_numeric(
finishedResponses['respLevel'], errors='coerce')
# Remove these two duplicates
finishedResponses = finishedResponses.drop([137526, 312184],
errors='ignore')
finishedEmoResponses = pd.read_csv('finishedEmoResponses.csv',
low_memory=False, index_col=0)
finishedEmoResponses = finishedEmoResponses.query(
'clipNum != 7443 and clipNum != 7444')
distractedResponses = finishedEmoResponses.query('ttr > 10000')
uniqueIDs = (finishedResponses['sessionNums'] * 1000
+ finishedResponses['queryType'] * 100
+ finishedResponses['questNum'])
distractedIDs = (distractedResponses['sessionNums'] * 1000
+ distractedResponses['queryType'] * 100
+ distractedResponses['questNum'])
# Get all annotations not defined to be distracted
goodResponses = finishedResponses[~uniqueIDs.isin(distractedIDs)]
# Responses based on different modalities
voiceResp = goodResponses.query('queryType == 1')
faceResp = goodResponses.query('queryType == 2')
multiModalResp = goodResponses.query('queryType == 3')
for mode in [voiceResp, faceResp, multiModalResp]:
# Proportion of human responses equal to acted emotion
accuracy = (mode['respEmo'] == mode['dispEmo']).sum() / len(mode)
print("Human accuracy: {:.3f}".format(accuracy))
dataTable = (mode.set_index(['sessionNums', 'clipNum'])['respEmo']
.astype('category').cat.codes.unstack() + 1)
dataTable[dataTable.isna()] = 0
data = dataTable.astype(int).to_numpy()
print("Krippendorf's alpha: {:.3f}".format(alpha(data)))
tabulatedVotes = pd.read_csv('processedResults/tabulatedVotes.csv',
low_memory=False, index_col=0)
tabulatedVotes['mode'] = tabulatedVotes.index // 100000
print("Average vote agreement per annotation mode:")
print(tabulatedVotes.groupby('mode')['agreement'].describe())
if __name__ == "__main__":
main()
|
C
|
UTF-8
| 927 | 3.546875 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
void printid(int space,int tata);
void tab(int num);
int main()
{
int i;
int parent;
printid(0,getpid());
for(i=0;i<3;i++)
{
parent=fork();
switch (parent)
{
case -1:
perror("Fork error");exit(1);//obsluga bledow funkcji fork
case 0:
sleep(1);//czekanie az skonczy sie proces macierzysty
printid(i,getpid());//wypisanie id
break;
default:
break;
}
}
return 0;
}
void printid(int space,int tata)//funkcja wypisujaca id
{
tab(space); printf("UID : %i ",getuid());
printf("GID : %i ",getgid());
printf("PID : %i ",getpid());
printf("PPID: %i ",getppid());
printf("PGID: %i\n",getpgid(tata));
}
void tab(int num)//funkcja do tabulacji
{
int k;
for (k=0;k<num;k++)
printf("\t");
}
|
C++
|
UTF-8
| 2,838 | 3.515625 | 4 |
[] |
no_license
|
// Шаблоны: класс размерной величины
// !!! ВЫПОЛЕНЫ ВСЕ УПРАЖНЕНИЯ !!!
#include <iostream>
//Упражнение 1
// метр килограмм секунда ампер кельвин моль кандела
//Упражнение 3,4,5
//Перегрузка операторов
template<int L, int M, int T, int I, int K, int N, int J>
class DimQ {
double value;
public:
DimQ(double data) { value = data; }
double get() {
return value;
}
//Перегрузка операторов
DimQ<L, M, T, I, K, N, J> operator-() {
return DimQ<L, M, T, I, K, N, J>(-value);
}
DimQ<L, M, T, I, K, N, J> operator+(DimQ<L, M, T, I, K, N, J> &other) {
return DimQ<L, M, T, I, K, N, J>(value + other.get());
}
DimQ<L, M, T, I, K, N, J> operator-(DimQ<L, M, T, I, K, N, J> &other) {
return DimQ<L, M, T, I, K, N, J>(value - other.get());
}
template<int L1, int M1, int T1, int I1, int K1, int N1, int J1>
DimQ<L + L1, M + M1, T + T1, I + I1, K + K1, N + N1, J + J1> operator*(DimQ<L1, M1, T1, I1, K1, N1, J1> other) {
return DimQ<L + L1, M + M1, T + T1, I + I1, K + K1, N + N1, J + J1>(value + other.get());
}
template<int L1, int M1, int T1, int I1, int K1, int N1, int J1>
DimQ<L - L1, M - M1, T - T1, I - I1, K - K1, N - N1, J - J1> operator/(DimQ<L1, M1, T1, I1, K1, N1, J1> other) {
return DimQ<L - L1, M - M1, T - T1, I - I1, K - K1, N - N1, J - J1>(value / other.get());
}
friend std::ostream &operator<<(std::ostream &os, DimQ<L, M, T, I, K, N, J> &object) {
os << object.get() << " " << " метр^" << L << " килограмм^" << M << " секунда^" << T << " ампер^" << I
<< " кельвин^" << K << " моль^" << N << " кандела^" << J;
return os;
}
};
//Упражнение 2
//Создайте псевдонимы типов для скорости, ускорения, а так же безразмерной величины.
typedef DimQ<1,0,0,0,0,0,0> Length;
typedef DimQ<1,0,-1,0,0,0,0> Velocity;
typedef DimQ<1,0,-2,0,0,0,0> Acceleration;
typedef DimQ<0,0,0,0,0,0,0> Nondim;
typedef DimQ<0,0,1,0,0,0,0> Time;
int main() {
//Упражнение 6 и 7
//Проверка работы программы
// Длина
Length l = {100};
// Время
Time t = {20};
// Скорость
Velocity v = l / t;
// Ускорение
Acceleration a = v / t;
std::cout << a << std::endl;
// Размерная величина
auto smth = v*a*a/t;
// Безразмерная величина
auto dimensionless = v/v;
// Ошибка компиляции!
// Dimensionless d = v;
// Mass m = v;
// Amount a = d;
std::cout << smth << std::endl;
std::cout << dimensionless << std::endl;
return 0;
};
|
C++
|
UTF-8
| 666 | 2.90625 | 3 |
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
#define lli long long int
lli maxSubArraySum(lli a[], lli size)
{
lli max_so_far = INT_MIN, max_ending_here = 0;
for (lli i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
int main()
{
lli t;
cin >> t;
while(t--){
lli n;
cin >> n;
lli a[n];
for (lli i = 0; i < n; ++i)
{
cin >> a[i];
}
lli max_sum = maxSubArraySum(a, n);
cout << max_sum << '\n';
}
// int n = sizeof(a)/sizeof(a[0]);
return 0;
}
|
Java
|
UTF-8
| 583 | 1.710938 | 2 |
[] |
no_license
|
package com.cyriii.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.cyriii.entity.OutStoreInfo;
import com.cyriii.entity.OutStoreInfoVO;
import com.cyriii.entity.PageVO;
public interface OutStoreInfoService extends IService<OutStoreInfo> {
boolean saveOutStoreInfo(OutStoreInfo entity) throws Exception;
boolean updateOutStoreInfoById(OutStoreInfo entity) throws Exception;
boolean removeOutStoreInfoById(String id) throws Exception;
IPage<OutStoreInfoVO> page(PageVO page);
}
|
Go
|
UTF-8
| 1,343 | 2.828125 | 3 |
[] |
no_license
|
package main
import (
"context"
"log"
"strings"
"time"
)
// AuthEvent is the payload of a Firestore Auth event.
type AuthEvent struct {
Email string `json:"email"`
Metadata struct {
CreatedAt time.Time `json:"createdAt"`
} `json:"metadata"`
UID string `json:"uid"`
}
// HelloAuth is triggered by Firestore Auth events.
func HelloAuth(ctx context.Context, e AuthEvent) error {
log.Printf("Function triggered by creation or deletion of user: %q", e.UID)
log.Printf("Created at: %v", e.Metadata.CreatedAt)
if e.Email != "" {
log.Printf("Email: %q", e.Email)
}
var claims = make(map[string]interface{})
customClaimsAdmin := map[string]interface{}{
"x-hasura-default-role": "admin",
"x-hasura-allowed-roles": []string{"user", "admin"},
"x-hasura-user-id": e.UID,
}
customClaimsUser := map[string]interface{}{
"x-hasura-default-role": "admin",
"x-hasura-allowed-roles": []string{"user", "admin"},
"x-hasura-user-id": e.UID,
}
if strings.Contains(e.UID, "@hasura.io") {
claims["https://hasura.io/jwt/claims"] = customClaimsAdmin
} else {
claims["https://hasura.io/jwt/claims"] = customClaimsUser
}
// Set admin privilege on the user corresponding to uid.
err := client.SetCustomUserClaims(ctx, e.UID, claims)
if err != nil {
log.Fatalf("error setting custom claims %v\n", err)
}
return nil
}
|
SQL
|
UTF-8
| 652 | 3.125 | 3 |
[
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
# chromAlias.sql was originally generated by the autoSql program, which also
# generated chromAlias.c and chromAlias.h. This creates the database representation of
# an object which can be loaded and saved from RAM in a fairly
# automatic way.
#correspondence of UCSC chromosome names to refseq, genbank, and ensembl names
CREATE TABLE chromAlias (
alias varchar(255) not null, # external name
chrom varchar(255) not null, # UCSC genome browser chromosome name
source varchar(255) not null, # comma separated list, when available: refseq,genbank,ensembl
#Indices
PRIMARY KEY(alias),
KEY(chrom),
KEY(source)
);
|
Java
|
UTF-8
| 1,258 | 2.6875 | 3 |
[] |
no_license
|
package com.packtpub.springhibernate.ch06.list.xml;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class UnitTest {
@Test
public void testComponent () {
SessionFactory factory = new Configuration()
.configure("/com/packtpub/springhibernate/ch06/hibernate.cfg.xml")
.addClass(Student.class)
.buildSessionFactory();
Session session = factory.openSession();
// --------------------------------------------------------
Student actual = (Student) session.load(Student.class, 1);
assertThat(actual.getFirstName(), is("John"));
List<String> papers = actual.getPapers();
String s = papers.get(1); // position : 1
assertThat(s, is("Paper1.doc"));
// --------------------------------------------------------
Student actual2 = (Student) session.load(Student.class, 2);
assertThat(actual2.getFirstName(), is("Robert"));
List<String> papers2 = actual2.getPapers();
assertThat(papers2.get(2), is("Paper2.html")); // position : 2
assertThat(papers2.get(3), is("Paper3.doc")); // position : 3
session.close();
}
}
|
Java
|
UTF-8
| 12,876 | 1.742188 | 2 |
[] |
no_license
|
package com.example.chatbase;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.chatbase.Chat.ChatObject;
import com.example.chatbase.Message.MediaAdapter;
import com.example.chatbase.Message.MessageCustomAdapter;
import com.example.chatbase.Message.MessageListAdapter;
import com.example.chatbase.Message.MessageObject;
import com.example.chatbase.User.UserObjects;
import com.example.chatbase.Utils.SendNotification;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.onesignal.OneSignal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import static com.example.chatbase.LoginActivity.PERF_NAME;
import static com.example.chatbase.Message.MessageCustomAdapter.MESSAGE_TYPE_IN;
import static com.example.chatbase.Message.MessageCustomAdapter.MESSAGE_TYPE_OUT;
public class MessageActivity extends AppCompatActivity {
private static final int MEDIA_INTENT_CODE = 1;
RecyclerView messageRecyclerView, mediaRecyclerView;
RecyclerView.Adapter messageAdapter, mediaAdapter;
RecyclerView.LayoutManager messageLayout, mediaLayout;
ArrayList<MessageObject> messageList;
ArrayList<String> mediaList;
ChatObject mChatObject;
DatabaseReference mChatMessagesDB;
String userName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
mChatObject = (ChatObject) getIntent().getSerializableExtra("chatObject");
mChatMessagesDB = FirebaseDatabase.getInstance().getReference().child("chat").child(mChatObject.getChatId()).child("messages");
FloatingActionButton sendBtn = findViewById(R.id.sendBtn);
mMessage = findViewById(R.id.chatmessage);
mMessage.setOnTouchListener(new View.OnTouchListener() {
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if(event.getAction() == MotionEvent.ACTION_UP) {
if(event.getRawX() >= (mMessage.getRight() - mMessage.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
getMediaGalary();
return true;
}
}
return false;
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
getUSerName();
initializeRecyclerView();
initializeMediaRecyclerView();
getChatMessages();
}
private void getUSerName() {
SharedPreferences sharedPreferences = getSharedPreferences(PERF_NAME, MODE_PRIVATE);
userName = sharedPreferences.getString("userName", "UserName");
}
ArrayList<String> mediaIDList = new ArrayList<>();
int totalMediaUrls = 0;
EditText mMessage;
String creatorName;
private void sendMessage() {
String messageID = mChatMessagesDB.push().getKey();
DatabaseReference chatDB = mChatMessagesDB.child(messageID);
final Map<String, Object> newMessageMap = new HashMap<>();
if (!mMessage.getText().toString().isEmpty())
newMessageMap.put("text", mMessage.getText().toString());
newMessageMap.put("creator", FirebaseAuth.getInstance().getUid());
newMessageMap.put("creatorName", userName);
if (!mediaList.isEmpty()){
for (String mediaUrl : mediaList){
String mediaId = chatDB.child("media").push().getKey();
mediaIDList.add(mediaId);
final StorageReference filePath = FirebaseStorage.getInstance().
getReference().child("chat").child(mChatObject.getChatId()).child(messageID).child(mediaId);
UploadTask uploadTask = filePath.putFile(Uri.parse(mediaUrl));
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
newMessageMap.put("/media/"+mediaIDList.get(totalMediaUrls)+"/", uri.toString());
totalMediaUrls++;
if (totalMediaUrls == mediaList.size()){
updateDatabaseWithNewMessage(chatDB, newMessageMap);
}
}
});
}
});
}
}else{
if (!mMessage.getText().toString().isEmpty()){
updateDatabaseWithNewMessage(chatDB, newMessageMap);
}
}
}
private void updateDatabaseWithNewMessage(DatabaseReference newMessageID, Map<String, Object> newMessageMap) {
newMessageID.updateChildren(newMessageMap);
mMessage.setText(null);
mediaIDList.clear();
mediaList.clear();
mediaAdapter.notifyDataSetChanged();
String message;
if (newMessageMap.get("text") != null){
message = newMessageMap.get("text").toString();
}else{
message = "send Media";
}
for (UserObjects mUser : mChatObject.getUserObjectsArrayList()){
if (!mUser.getUid().equals(FirebaseAuth.getInstance().getUid())){
new SendNotification(message, "new Message", mUser.getNotificationKey());
}
}
}
private void initializeMediaRecyclerView() {
mediaList = new ArrayList<>();
mediaRecyclerView = findViewById(R.id.mediaRecyclerView);
mediaRecyclerView.setHasFixedSize(false);
mediaRecyclerView.setNestedScrollingEnabled(false);
mediaLayout = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
mediaRecyclerView.setLayoutManager(mediaLayout);
mediaAdapter = new MediaAdapter(getApplicationContext(), mediaList);
mediaRecyclerView.setAdapter(mediaAdapter);
}
private void getChatMessages(){
mChatMessagesDB.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
if (snapshot.exists()){
String text = "",
creator = "",
creatorName = "";
int messageNumber = 0;
ArrayList<String> mediaUrlList = new ArrayList<>();
if (snapshot.child("text").getValue() != null){
text = snapshot.child("text").getValue().toString();
}if (snapshot.child("creator").getValue() != null){
creator = snapshot.child("creator").getValue().toString();
}
if (snapshot.child("creatorName").getValue() != null){
creatorName = snapshot.child("creatorName").getValue().toString();
}
if (snapshot.child("media").getChildrenCount() > 0)
for (DataSnapshot dataSnapshot : snapshot.child("media").getChildren())
mediaUrlList.add(dataSnapshot.getValue().toString());
Log.i("messagenumber", "creator: "+creator);
Log.i("messagenumber", "uid: "+FirebaseAuth.getInstance().getUid());
if (creator.equals(FirebaseAuth.getInstance().getUid())){
messageNumber = MESSAGE_TYPE_OUT;
}else {
messageNumber = MESSAGE_TYPE_IN;
}
Log.i("messagenumber", "onChildAdded: "+messageNumber);
MessageObject mMessage = new MessageObject(messageNumber, snapshot.getKey(), creator, creatorName, text, mediaUrlList);
messageList.add(mMessage);
messageLayout.scrollToPosition(messageList.size() - 1);
messageAdapter.notifyDataSetChanged();
}
}
@Override
public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot snapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
private void initializeRecyclerView(){
messageList = new ArrayList<>();
messageRecyclerView = findViewById(R.id.messageRecyclerView);
messageRecyclerView.setHasFixedSize(false);
messageRecyclerView.setNestedScrollingEnabled(false);
messageLayout = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
messageRecyclerView.setLayoutManager(messageLayout);
messageAdapter = new MessageCustomAdapter(this, messageList);
messageRecyclerView.setAdapter(messageAdapter);
}
private void getMediaGalary() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose Image(s)"), MEDIA_INTENT_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
if (requestCode == MEDIA_INTENT_CODE){
Log.i("media", "onActivityResult: ");
if (data.getClipData() == null){
mediaList.add(data.getData().toString());
}else{
for (int i = 0; i < data.getClipData().getItemCount(); i++){
mediaList.add(data.getClipData().getItemAt(i).getUri().toString());
}
}
mediaAdapter.notifyDataSetChanged();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.logout_item){
logOut();
return true;
}
return false;
}
public void logOut(){
OneSignal.setSubscription(false);
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
|
SQL
|
UTF-8
| 575 | 3.84375 | 4 |
[] |
no_license
|
-- ORIGINAL TO ALTER:
-- DROP PROCEDURE IF EXISTS legsCount;
-- CREATE PROCEDURE legsCount()
-- SELECT [..] as summary_legs
-- FROM creatures
-- ORDER BY id;
-- SOLUTION:
DROP PROCEDURE IF EXISTS legsCount;
CREATE PROCEDURE legsCount()
SELECT SUM(CASE WHEN type='human' THEN 2 ELSE 4 END) as summary_legs
FROM creatures
ORDER BY id;
-- ANOTHER CLEVER SOLUTION USING ONLY IF:
-- DROP PROCEDURE IF EXISTS legsCount;
-- CREATE PROCEDURE legsCount()
-- SELECT SUM( IF(type='human', 2, 4) ) as summary_legs
-- FROM creatures
-- ORDER BY id;
|
C
|
UTF-8
| 2,007 | 4.09375 | 4 |
[] |
no_license
|
#include<stdio.h>
#include<math.h>
int sum();
double div();
int mult();
int subs();
int power();
int main(){
printf("\nPlease Enter two number for sum\n");
printf("Sum\n");
sum();
printf("Multiply\n");
mult();
printf("Division\n");
div();
printf("Substraction\n");
subs();
printf("Power\n");
power();
return 0;
}
int sum(){
int a, b;
int result;
printf("Enter the First no.\n");
scanf("%d", &a);
printf("Enter the Second no.\n");
scanf("%d", &b);
result = a + b;
printf("\nThere Sum is \t");
printf("%d\n\n", result);
return result;
}
int mult(){
int a, b;
int result;
printf("Enter the First no.\n");
scanf("%d", &a);
printf("Enter the Second no.\n");
scanf("%d", &b);
printf("\nThere Multiplication is \t");
result = a * b;
printf("%d\n\n", result);
return result;
}
double div(){ // Its not necessarly to change the function into double it just to show that it works fine
double a, b; // The input value has to be a double
double result; //It has to be double
printf("Enter the First no.\n");
scanf("%lf", &a);
printf("Enter the Second no.\n");
scanf("%lf", &b);
result = a / b;
printf("\nThere Duvision is \t");
printf("%lf\n\n", result);
return result;
}
int power(){
double a, b;
double result;
printf("Enter the First no.\n");
scanf("%lf", &a);
printf("Enter the Second no.\n");
scanf("%lf", &b);
result = pow(a,b);
printf("\nThere power is \t");
printf("%lf\n\n", result);
return result;
}
int subs(){
int a, b;
int result;
printf("Enter the First no.\n");
scanf("%d", &a);
printf("Enter the Second no.\n");
scanf("%d", &b);
result = a - b;
printf("\nThere Substraction is \t");
printf("%d\n\n", result);
return result;
}
|
C++
|
UTF-8
| 704 | 2.765625 | 3 |
[] |
no_license
|
#pragma once
#include <string>
using namespace std;
struct autor
{
int id;
string imie;
string nazwisko;
string data;
bool books;
autor* kolejny{};
void drukuj_a();
};
using Autor = autor * ;
struct ksiazka
{
int id_a;
string tytul;
string data;
string wydawnictwo;
ksiazka* kolejna{};
};
using Ksiazka = ksiazka * ;
struct Lista_Autorow
{
autor *pierwszy{};
void dodaj_a(string imie, string nazwisko, string data);
void drukuj_la(int x, int y);
void save_a();
void usun(int nr);
int ilosc();
};
struct ksiegozbior
{
Ksiazka pierwsza{};
void dodaj(int id_a, string tytul, string data, string wydawnictwo);
void usun(int);
int licz_b();
void save_b();
};
|
Java
|
UTF-8
| 3,199 | 2.203125 | 2 |
[] |
no_license
|
package cn.believeus.admin.controller;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.believeus.model.Admin;
import cn.believeus.model.Authority;
import cn.believeus.model.Role;
import cn.believeus.service.IService;
@Controller
public class AdminPowerController {
@Resource
private IService mysqlService;
@RequestMapping(value="/admin/addRoleLogic")
public String addRoleLogic(ServletRequest request){
Role role = new Role();
String roleName = request.getParameter("roleName");
String description = request.getParameter("description");
role.setRoleName(roleName);
role.setDescription(description);
mysqlService.saveOrUpdate(role);
// 获取被选中的checkbook 并且name="authority"
String[] parameterValues = request.getParameterValues("authority");
if(parameterValues !=null){
for (String permission : parameterValues) {
Authority authority = new Authority();
authority.setPermission(permission);
authority.setRole(role);
mysqlService.saveOrUpdate(authority);
}
}
return "redirect:/admin/roleList.jhtml";
}
@RequestMapping(value="/admin/updateRole")
public String editRoleLogic(ServletRequest request){
String roleId = request.getParameter("roleId");
String roleName=request.getParameter("roleName");
String description = request.getParameter("description");
Role role=(Role)mysqlService.findObject(Role.class, Integer.parseInt(roleId));
role.setRoleName(roleName);
role.setDescription(description);
mysqlService.saveOrUpdate(role);
List<Authority> authoritys = role.getAuthoritys();
List<Integer> idList=new ArrayList<Integer>();
if(authoritys!=null){
for (Authority authority : authoritys) {
idList.add(authority.getId());
}
}
// 更新权限之前首先删除之前的权限
mysqlService.delete(Authority.class, idList);
// 获取被选中的checkbook 并且name="authority"
String[] parameterValues = request.getParameterValues("authority");
if(parameterValues!=null){
for (String permission : parameterValues) {
Authority authority = new Authority();
authority.setPermission(permission);
authority.setRole(role);
mysqlService.saveOrUpdate(authority);
}
}
return "redirect:/admin/roleList.jhtml";
}
@RequestMapping(value="/admin/updateRoleForAdmin")
public String updateRoleForAdmin(ServletRequest request){
String adminId = request.getParameter("adminId");
String adminName = request.getParameter("adminName");
String description = request.getParameter("description");
String roleId=request.getParameter("roleId");
String repass = request.getParameter("repass");
Role role=(Role)mysqlService.findObject(Role.class, Integer.parseInt(roleId));
Admin admin=(Admin)mysqlService.findObject(Admin.class, Integer.parseInt(adminId));
admin.setUsername(adminName);
admin.setPassword(repass);
admin.setDescription(description);
role.setAdmin(admin);
mysqlService.saveOrUpdate(role);
return "redirect:/admin/adminList.jhtml";
}
}
|
Go
|
UTF-8
| 948 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
package player
import (
"fgame/fgame/game/player"
playertypes "fgame/fgame/game/player/types"
welfaretemplate "fgame/fgame/game/welfare/template"
"time"
)
const (
taskRefreshTime = time.Second * 20
)
//运营活动刷新数据
type RefreshActivityTask struct {
pl player.Player
}
func (t *RefreshActivityTask) Run() {
welfareManager := t.pl.GetPlayerDataManager(playertypes.PlayerWelfareDataManagerType).(*PlayerWelfareManager)
timeList := welfaretemplate.GetWelfareTemplateService().GetAllActivityTimeTemplate()
for _, timeTemp := range timeList {
welfareManager.RefreshActivityDataByGroupId(timeTemp.Group)
// welfareManager.RefreshActivityData(timeTemp.GetOpenType(), timeTemp.GetOpenSubType())
}
}
//间隔时间
func (t *RefreshActivityTask) ElapseTime() time.Duration {
return taskRefreshTime
}
func CreateRefreshActivityTask(pl player.Player) *RefreshActivityTask {
t := &RefreshActivityTask{
pl: pl,
}
return t
}
|
Java
|
UTF-8
| 14,018 | 1.953125 | 2 |
[] |
no_license
|
package com.app.hci.flyhigh;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.graphics.Color.rgb;
import static com.app.hci.flyhigh.R.string.status;
/**
* Created by Gaston on 19/06/2017.
*/
public class FlightFragment extends Fragment{
int mCurrentPosition = -1;
final static String ARG_POSITION = "position";
private Flight flight;
private static String[] ids = { "departure_airport",
"arrival_airport",
"departure_city",
"arrival_city",
"duration",
"airline_logo",
"airline",
"week_days",
"departure_hour",
"departure_airport_name",
"arrival_hour",
"arrival_airport_name",
"flight_number",
"subscription_status",
"departure_gate",
"departure_terminal",
"arrival_gate",
"arrival_terminal",
"json_representation"};
public static FlightFragment newInstance(Context context, Flight flight) {
Bundle args = prepareBundle(context, flight);
FlightFragment fragment = new FlightFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState){
try {
this.flight = new Flight(new JSONObject(getArguments().getString(ids[18])));
}catch(Exception e){
e.printStackTrace();
}
super.onCreate(savedInstanceState);
}
private void switchSubscriptionStatus(boolean subscribing, View view){
FloatingActionButton fab;
if(view != null)
fab = (FloatingActionButton)view.findViewById(R.id.flight_info_suscriptionButton);
else
fab = (FloatingActionButton) getView().findViewById(R.id.flight_info_suscriptionButton);
if(subscribing){
fab.setBackgroundTintList(ColorStateList.valueOf(rgb(196, 196, 196)));
fab.setImageResource(R.drawable.ic_favorite_black_24dp);
}else{
fab.setBackgroundTintList(ColorStateList.valueOf(rgb(196, 196, 196)));
fab.setImageResource(R.drawable.ic_favorite_empty_border_black_24dp);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// If activity recreated (such as from screen rotate), restore
// the previous article selection set by onSaveInstanceState().
// This is primarily necessary when in the two-pane layout.
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
final View view = inflater.inflate(R.layout.flight_fragment, container, false);
FloatingActionButton button = (FloatingActionButton) view.findViewById(R.id.flight_info_suscriptionButton);
if(DataManager.isSubscribed(getActivity(), flight))
switchSubscriptionStatus(true, view);
else
switchSubscriptionStatus(false, view);
button.setColorFilter(Color.rgb(255, 30, 41));
if (button != null) {
button.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
if(!DataManager.isSubscribed(getActivity(), flight)){
switchSubscriptionStatus(true, null);
DataManager.subscribeToFlight(getActivity(), flight);
}else{
switchSubscriptionStatus(false, null);
DataManager.unsubscribe(getActivity(), flight);
}
}
});
}
new LoadImage(flight.getLogURL(), (ImageView) view.findViewById(R.id.image_view)).execute();
return view;
}
@Override
public void onStart() {
super.onStart();
// During startup, check if there are arguments passed to the fragment.
// onStart is a good place to do this because the layout has already been
// applied to the fragment at this point so we can safely call the method
// below that sets the article text.
Bundle args = getArguments();
if (args != null) {
// Set article based on argument passed in
updateFlightFragment(args);
} else if (mCurrentPosition != -1) {
// Set article based on saved instance state defined during onCreateView
updateFlightFragment(mCurrentPosition);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current article selection in case we need to recreate the fragment
outState.putInt(ARG_POSITION, mCurrentPosition);
}
private void updateFlightFragment(int position){
updateFlightFragment(FlightsHolder.subscriptionFlights.get(position));
mCurrentPosition = position;
}
private void updateFlightFragment(Bundle args){
((TextView) getActivity().findViewById(R.id.flight_info_departureAirport)).setText(args.getString(ids[0]));
((TextView) getActivity().findViewById(R.id.flight_info_departureAirportBig)).setText(args.getString(ids[0]));
((TextView) getActivity().findViewById(R.id.flight_info_arrivalAirport)).setText(args.getString(ids[1]));
((TextView) getActivity().findViewById(R.id.flight_info_arrivalAirportBig)).setText(args.getString(ids[1]));
((TextView) getActivity().findViewById(R.id.flight_info_departureCity)).setText(args.getString(ids[2]));
((TextView) getActivity().findViewById(R.id.flight_info_arrivalCity)).setText(args.getString(ids[3]));
//((ImageView) getActivity().findViewById(R.id.flight_info_airline_logo)).setImage(extras.getString(ids[5]));
((TextView) getActivity().findViewById(R.id.flight_info_airline)).setText(args.getString(ids[6]));
((TextView) getActivity().findViewById(R.id.flight_info_departureHour)).setText(args.getString(ids[8]));
((TextView) getActivity().findViewById(R.id.flight_info_departureCityAndAirport)).setText(getString(R.string.airport_city, args.getString(ids[2]), args.getString(ids[9])));
((TextView) getActivity().findViewById(R.id.flight_info_arrivalHour)).setText(args.getString(ids[10]));
((TextView) getActivity().findViewById(R.id.flight_info_arrivalCityAndAirport)).setText(getString(R.string.airport_city, args.getString(ids[3]) ,args.getString(ids[11])));
((TextView) getActivity().findViewById(R.id.flight_info_number)).setText(args.getString(ids[12]));
((TextView) getActivity().findViewById(R.id.flight_info_status)).setText(args.getString(ids[13]));
setStatusColor(args.getString(ids[13]), (TextView) getActivity().findViewById(R.id.flight_info_status));
((TextView) getActivity().findViewById(R.id.flight_info_departure_gate)).setText(getString(R.string.gate, args.getString(ids[14])));
((TextView) getActivity().findViewById(R.id.flight_info_departure_terminal)).setText(getString(R.string.terminal, args.getString(ids[15])));
((TextView) getActivity().findViewById(R.id.flight_info_arrival_gate)).setText(getString(R.string.gate, args.getString(ids[16])));
((TextView) getActivity().findViewById(R.id.flight_info_arrival_terminal)).setText(getString(R.string.terminal, args.getString(ids[17])));
}
public void updateFlightFragment(Flight flight){
((TextView) getActivity().findViewById(R.id.flight_info_departureAirport)).setText(flight.getDepartureAirport());
((TextView) getActivity().findViewById(R.id.flight_info_departureAirportBig)).setText(flight.getDepartureAirport());
((TextView) getActivity().findViewById(R.id.flight_info_arrivalAirport)).setText(flight.getArrivalAirport());
((TextView) getActivity().findViewById(R.id.flight_info_arrivalAirportBig)).setText(flight.getArrivalAirport());
((TextView) getActivity().findViewById(R.id.flight_info_departureCity)).setText(flight.getDepartureCity());
((TextView) getActivity().findViewById(R.id.flight_info_arrivalCity)).setText(flight.getArrivalCity());
((TextView) getActivity().findViewById(R.id.flight_info_departure_gate)).setText(getString(R.string.gate, flight.getDepartureGate()));
((TextView) getActivity().findViewById(R.id.flight_info_arrival_gate)).setText(getString(R.string.gate, flight.getArrivalGate()));
((TextView) getActivity().findViewById(R.id.flight_info_departure_terminal)).setText(getString(R.string.terminal, flight.getDepartureTerminal()));
((TextView) getActivity().findViewById(R.id.flight_info_arrival_terminal)).setText(getString(R.string.terminal, flight.getArrivalTerminal()));
//((ImageView) getActivity().findViewById(R.id.flight_info_airline_logo)).setImage(extras.getString(ids[5]));
((TextView) getActivity().findViewById(R.id.flight_info_airline)).setText(flight.getAirlineName());
((TextView) getActivity().findViewById(R.id.flight_info_departureHour)).setText(flight.getDepartureHour());
((TextView) getActivity().findViewById(R.id.flight_info_departureCityAndAirport)).setText(getString(R.string.airport_city, flight.getDepartureCity(), flight.getDepartureAirportName()));
((TextView) getActivity().findViewById(R.id.flight_info_arrivalHour)).setText(flight.getArrivalHour());
((TextView) getActivity().findViewById(R.id.flight_info_arrivalCityAndAirport)).setText(getString(R.string.airport_city, flight.getArrivalCity() , flight.getArrivalAirportName()));
((TextView) getActivity().findViewById(R.id.flight_info_number)).setText(flight.getFlightNumber());
((TextView) getActivity().findViewById(R.id.flight_info_status)).setText(flight.getStatus(getContext()));
}
private static Bundle prepareBundle(Context context, Flight flight){
Bundle args = new Bundle();
args.putString(ids[0],flight.getDepartureAirport());
args.putString(ids[1],flight.getArrivalAirport());
args.putString(ids[2],flight.getDepartureCity());
args.putString(ids[3],flight.getArrivalCity());
// args.putString(ids[4],flight.getDuration());
args.putString(ids[6],flight.getAirlineName());
// args.putString(ids[7],flight.getWeekDays());
args.putString(ids[8],flight.getDepartureHour());
args.putString(ids[9],flight.getDepartureAirportName());
args.putString(ids[10],flight.getArrivalHour());
args.putString(ids[11],flight.getArrivalAirportName());
args.putString(ids[12],flight.getFlightNumber());
args.putString(ids[13],flight.getStatus(context));
args.putString(ids[14],flight.getDepartureGate());
args.putString(ids[15],flight.getDepartureTerminal());
args.putString(ids[16],flight.getArrivalGate());
args.putString(ids[17],flight.getArrivalTerminal());
args.putString(ids[18],flight.getJsonRepresentation());
return args;
}
private void setStatusColor(String status, TextView statusTextView){
if(status.equals(getString(R.string.stat_l)) || status.equals(getString(R.string.stat_s))) {
//noinspection ResourceType
statusTextView.setTextColor(Color.parseColor(getContext().getResources().getString(R.color.green)));
}else if(status.equals(getString(R.string.stat_a))) {
//noinspection ResourceType
statusTextView.setTextColor(Color.parseColor(getContext().getResources().getString(R.color.lightblue)));
}else if(status.equals(getString(R.string.stat_r))) {
//noinspection ResourceType
statusTextView.setTextColor(Color.parseColor(getContext().getResources().getString(R.color.orange)));
}else if(status.equals(getString(R.string.stat_c))) {
//noinspection ResourceType
statusTextView.setTextColor(Color.RED);
}
}
public class LoadImage extends AsyncTask<String, Void, Bitmap> {
private String targetURL;
private ImageView imageView;
public LoadImage (String url, ImageView imageView) {
this.targetURL = url;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... params) {
try {
HttpURLConnection urlConnection = null;
URL url = new URL(targetURL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
return BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
imageView.setImageBitmap(result);
}
}
}
}
|
Python
|
UTF-8
| 2,559 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""
mysql数据库连接配置
"""
import pymysql.cursors
from os.path import abspath, dirname
import configparser as cparser
# ======== Reading db_config.ini setting ===========
base_dir = dirname(dirname(abspath(__file__)))
base_dir = base_dir.replace('\\', '/')
file_path = base_dir + "/Config/db_config.ini"
cf = cparser.ConfigParser()
cf.read(file_path)
host = cf.get("mysqlconf", "host")
port = cf.get("mysqlconf", "port")
db = cf.get("mysqlconf", "db_name")
user = cf.get("mysqlconf", "user")
password = cf.get("mysqlconf", "password")
# ======== MySql base operating ===================
class DB:
def __init__(self):
try:
# Connect to the database
self.connection = pymysql.connect(host=host,
port=int(port),
user=user,
password=password,
db=db,
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
except pymysql.err.OperationalError as e:
print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
# clear table data
def clear(self, table_name):
# real_sql = "truncate table " + table_name + ";"
real_sql = "delete from " + table_name + ";"
with self.connection.cursor() as cursor:
cursor.execute("SET FOREIGN_KEY_CHECKS=0;")
cursor.execute(real_sql)
self.connection.commit()
# insert sql statement
def insert(self, table_name, table_data):
for key in table_data:
table_data[key] = "'" + str(table_data[key]) + "'"
key = ','.join(table_data.keys())
value = ','.join(table_data.values())
real_sql = "INSERT INTO " + table_name + " (" + key + ") VALUES (" + value + ")"
# print(real_sql)
with self.connection.cursor() as cursor:
cursor.execute(real_sql)
self.connection.commit()
# close database
def close(self):
self.connection.close()
# init data
def init_data(self, datas):
for table, data in datas.items():
self.clear(table)
for d in data:
self.insert(table, d)
self.close()
if __name__ == '__main__':
db = DB()
table_name = "student2"
data = {'id': 1, 'name': '测试1', 'age': 1}
db.clear(table_name)
db.insert(table_name, data)
db.close()
|
C++
|
UTF-8
| 8,859 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <functional>
#include <vector>
#include <string>
#include "CUtilJson.h"
#include "SCueSheet.h"
class CDbDiscogsElem : protected CUtilJson
{
friend class CDbDiscogs;
public:
CDbDiscogsElem(const std::string &data, const int disc=1, const int offset=0);
CDbDiscogsElem(const std::string &data, const int disc, const std::vector<int> &tracklengths);
virtual ~CDbDiscogsElem() {}
/**
* @brief Exchanges the content with another CDbDiscogsElem object
* @param Another CDbDiscogsElem object
*/
void Swap(CDbDiscogsElem &other);
/** Return a unique release ID string
*
* @return id string if Query was successful.
*/
std::string ReleaseId() const;
/** Get album title
*
* @return Title string (empty if title not available)
*/
std::string AlbumTitle() const;
/** Get album artist
*
* @return Artist string (empty if artist not available)
*/
SCueArtists AlbumArtist() const;
/** Get album composer
*
* @return Composer/songwriter string (empty if artist not available)
*/
SCueArtists AlbumComposer() const;
/** Get genre
*
* @return Genre string (empty if genre not available)
*/
std::string Genre() const;
/** Get release date
*
* @return Date string (empty if genre not available)
*/
std::string Date() const;
/** Get release country
*
* @return Countery string (empty if genre not available)
*/
std::string Country() const;
/**
* @brief Get disc number
* @return Disc number or -1 if unknown
*/
int DiscNumber() const;
/**
* @brief Get total number of discs in the release
* @return Number of discs or -1 if unknown
*/
int TotalDiscs() const;
/** Get label name
*
* @return Label string (empty if label not available)
*/
std::string AlbumLabel() const;
/** Get catalog number
*
* @return Catalog Number string (empty if not available)
*/
std::string AlbumCatNo() const;
/** Get album UPC
*
* @return UPC string (empty if UPC not available)
*/
std::string AlbumUPC() const;
/** Get number of tracks
*
* @return number of tracks
* @throw runtime_error if CD record id is invalid
*/
int NumberOfTracks() const;
/** Get track title
*
* Track title is intelligently obtained.
* Case 1. main track - track title
* Case 2. sub_track - parent index track title + ": " + [index#] + ". " sub_track title
* Exception 1. If only 1 sub_track is given under an index track, index# and sub_track
* title are omitted.
* Exception 2. If sub_track index# is found in its title (either as an Arabic or Roman number)
* [index#] is omitted. Note that inclusion of movement # is discouraged by Discogs.
* Case Unaccounted: Some submitters use heading track to provide the main title of the
* work and subsequent toplevel tracks for its movements. This function ignores all the heading
* tracks, thus only movement names will be added to the cuesheet. Discogs entry must be fixed
* to fix this case.
*
* @param[in] Track number (1-99)
* @return Title string (empty if title not available)
* @throw runtime_error if track number is invalid
*/
std::string TrackTitle(int tracknum) const;
/** Get track artist
*
* @param[in] Track number (1-99)
* @return Artist string (empty if artist not available)
* @throw runtime_error if track number is invalid
*/
SCueArtists TrackArtist(int tracknum) const;
/** Get track composer
*
* @param[in] Track number (1-99)
* @return Composer string (empty if artist not available)
* @throw runtime_error if track number is invalid
*/
SCueArtists TrackComposer(int tracknum) const;
/** Get track ISRC
*
* @param[in] Track number (1-99)
* @return ISRC string
* @throw runtime_error if track number is invalid
*/
std::string TrackISRC(int tracknum) const;
std::string Identifier(const std::string type) const;
private:
int disc; // in the case of multi-disc set, indicate the disc # (zero-based)
int track_offset; // starting track of the CD (always 0 if single disc release)
int number_of_tracks; // number of tracks on the CD (-1 to use all tracks of the release)
bool various_performers; // false if album has unique set of performing artists
bool various_composers; // false if album has a single composer
json_t *album_credits; // fixed link to the release's extraartists
/**
* @brief Traverses tracklist array and calls Callback() for every track-type element
* @param[in] Callback function
*
* Callback (lambda) function:
* - Called on every JSON object under tracklist" with its "type_"=="track"
* - Input arguments:
* track: Pointer to the current JSON "track" object
* parent: Pointer to the parent JSON "index track" object if track is a sub_track. Or
* NULL if track is not a sub_track
* pidx: sub_track index if parent is not NULL. Otherwise, unknown
* heading: Pointer to the last seen JSON "heading track" object. NULL if there has been none.
* hidx: track index (only counting the main tracks) w.r.t. heading. Unknonwn if heading is NULL,
*/
void TraverseTracks_(
std::function<bool (const json_t *track,
const json_t *parent, size_t pidx,
const json_t *heading, size_t hidx)> Callback) const;
/**
* @brief Find JSON object for the specified track
* @param[in] track number counting over multiple discs
* @param[out] if not NULL and track is found in sub_tracks listing, returns its parent index track JSON object
* @return pointer to a track JSON object
*/
const json_t* FindTrack_(const size_t trackno, const json_t **index=NULL, size_t *suboffset=NULL,
const json_t **header=NULL, size_t *headoffset=NULL) const;
/**
* @brief Determine track offset for multi-disc release
*
* This function fills track_offset & number_of_tracks member variables.
*
* @param[in] vector of lengths of CD tracks in seconds
* @return false if Discogs release is invalid
*/
bool SetDiscOffset_(const std::vector<int> &tracklengths);
/**
* @brief Fill number_of_tracks
*/
void SetDiscSize_();
/**
* @brief return the total number of sub_tracks listed under an index track
* @param[in] pointer to the index track JSON object
* @return number of sub_tracks or 0 if failed
*/
static size_t NumberOfSubTracks_(const json_t *track);
/**
* @brief Get title of album/track
* @param[in] pointer to either album or track JSON object
* @return the title of album or track
*/
static std::string Title_(const json_t* data); // maybe release or track json_t
/**
* @brief Get a string of performer names associated with album or track. It excludes
* composer names
* @param[in] pointer to album or track JSON object
* @return string of performers
*/
static SCueArtists Performer_(const json_t* data); // maybe release or track json_t
/**
* @brief Get a string of performer names associated with album or track. It excludes
* composer names
* @param[in] pointer to album or track JSON object
* @return composer
*/
SCueArtists Composer_(const json_t* data) const; // maybe release or track json_t
/**
* @brief Analyze Artists lists to fill various_performers, various_composers, and album_credits
*/
void AnalyzeArtists_();
static bool IsComposer_(const json_t* artist, const json_t* extraartists,
const std::vector<std::string> &keywords
= {"Composed", "Written", "Adapted",
"Arranged", "Lyrics", "Music", "Songwriter",
"Words", "Orchestrated"});
/**
* @brief Get artist's Discogs ID
* @param artist JSON object (an element of artists or extraartists arrays)
* @return integer ID
*/
static json_int_t ArtistId_(const json_t* artist);
/**
* @brief Look for the artist with the ID in the array of artists
* @param id
* @param artists
* @return JSON object corresponds to the artist under search or NULL if not found
*/
static json_t *FindArtist_(const json_int_t id, const json_t* artists);
};
|
JavaScript
|
UTF-8
| 3,362 | 2.734375 | 3 |
[] |
no_license
|
$(document).ready(function () {
$("#btnExit").click(function () {
$("#page").fadeOut(2000);
$("#goodbye").delay(1000).show(2000);
function convertToC() {
var far = parseFloat(document.getElementById('far').value);
var cel = (fTempVal - 32) * (5 / 9);
document.getElementById('cel').value = cel;
return false;
}
function convertToF() {
var cTempVal = parseFloat(document.getElementById('c').value);
var fTempVal = (cTempVal * (9 / 5)) + 32;
console.log(f);
document.getElementById('f').value = f;
return false;
}
console.reset = function () {
return getElementById();
}
function convertToC() {
try {
var c = (fTempVal - 32) * (5 / 9);
if (!isNaN(g) && document.getElementById('Celsius').checked === true) {
return value g; document.getElementByID("Temp").innerHTML = "Must be an integer";
return false;
} else {
throw new Error('Response is not a number')
}
catch (ex) { }
finally {
log(c.name + '' + c.message);
return 'We are unable to get you the correct temperature value. Please use numbers insteas of letters';
function convertToF() {
try {
var f = (cTempVal * (9 / 5)) + 32;
if (!isNaN(f)) {
return f;
} else {
throw new Error('Response is not a number');
} try { f }
finally {
log(f.name + '' + f.message);
return 'We are unable to get you the correct temperature value. Please use numbers instead of letters';
form; action_page.php
type; reset, value = "Try Again";
if ('button onclick = myFunction() Exit')
return null;
}else{
throw new error('Action events are not correct')
} try { onmouseover } finally {
var console = f, string = '' + f.message
;
return 'We are unable to give you a value. Please try again';
}
try { fadeTarget } finally { '' };
var fadeEffect = '',
try {
if (try) { opacity < 10 }
return opacity > 10;
}
finally { opacity < 10 };
return (opacity > 10);
} else (opacity > 10);
throw new Error('The parameters that have been used do not go with the equation. Please re-evaluate script.')
$('#submit').on('click', function () {
if ($('#container').css('opacity') == 0) {
$('#container').css('opacity', 1);
}
else {
$('#container').css('opacity', 0);
}
});
}
/* not sure on this one.. The fade out is not working so I am not sure what to write the error codes about.*/
result; { };
clearSelection()
|
Python
|
UTF-8
| 571 | 3.8125 | 4 |
[] |
no_license
|
"""Problem 34: Improve the above program to print the words in the descending order of the number of occurrences."""
def word_frequency(words):
frequency = dict()
for w in words:
frequency[w] = frequency.get(w, 0) + 1
return frequency
def read_words(filename):
return open(filename).read().split()
def sortfunc(x):
return x[1]
def main(filename):
frequency = sorted(word_frequency(read_words(filename)).items(),key=sortfunc,reverse=True)
for word, count in frequency:
print word, count
if __name__ == '__main__':
from sys import argv
main(argv[1])
|
C++
|
UTF-8
| 1,728 | 3.78125 | 4 |
[] |
no_license
|
// CPS 271 Machine Problem 4
// Name: Amy Calliham
// Student ID: 00683394
// Purpose of Program: Create point, circle, and cylinder classes to demonstrate knowledge of inheritance and composition.
// Allow user to input data about each object, calculate and print data
#include <iostream>
#include <string>
#include "circleType.h"
#include "cylinderType.h"
#include "pointType.h"
using namespace std;
int main()
{
// ***** Testing classes *****
double circ, area, vol, surf_area;
cout << "\n\nTesting of constant Point, Circle, Cylinder objects..." << endl;
// create and print out a const Point object
cout << "\nPoint info..." << endl;
const pointType center1(2, 3);
center1.getData();
// create and print out a const Circle object
cout << "\nCircle info..." << endl;
const circleType cir1(center1, 5.5);
cir1.getData();
circ = cir1.calcCircumference();
cout << "Circumference: " << circ << endl;
area = cir1.calcArea();
cout << "Area: " << area << endl;
// create and print out a const Cylinder object
cout << "\nCylinder info..." << endl;
const cylinderType cyl1(cir1, 10);
cyl1.getData();
circ = cyl1.calcCircumference();
cout << "Cyl Circumference: " << circ << endl;
area = cyl1.calcArea();
cout << "Cyl Circle Area: " << area << endl;
surf_area = cyl1.calcSurfaceArea();
cout << "Cyl Surface Area: " << surf_area << endl;
vol = cyl1.calcVolume();
cout << "Cyl Volume: " << vol << endl;
// ***** User-entered input *****
cout << "\n\nEnter in Point, Circle, Cylinder info..." << endl;
pointType point;
point.putData();
circleType circle(point);
circle.putData();
cylinderType cylinder(circle);
cylinder.putData();
point.getData();
circle.getData();
cylinder.getData();
}
|
Python
|
UTF-8
| 1,121 | 3.71875 | 4 |
[] |
no_license
|
def auto_fill_column(rows, column_name):
"""
Take a column name (for exm: 'Title')
and list of columns that follows this pattern:
Title Actor ...
The Huge Wave John Doe ...
Alice Doe ...
Karl Muller ...
Titanic Leonardo Di Caprio ...
John Doe ...
And fills it up in-place (the original list gets modified), like this:
Title Actor ...
The Huge Wave John Doe ...
The Huge Wave Alice Doe ...
The Huge Wave Karl Muller ...
Titanic Leonardo Di Caprio ...
Titanic John Doe ...
Precondition: first row is not "" nor None
:param rows: list of rows in the csv file
:param column_name: string indicating the name of the field to update
:return: None,
"""
for row in rows:
if row[column_name] in ["", None]:
row[column_name] = last[column_name]
last = row
|
Python
|
UTF-8
| 4,761 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
import argparse
import torchvision
from torchvision.models.alexnet import alexnet
import Model
import data_loader
import torch
import torchvision
parser = argparse.ArgumentParser(
description='This for training a network you choose.\n First, you need an existing available architecture to load such as VGG16 or VGG13, etc.\n Some layer will be freezed, whereas the last layers are dropped and replaced by hidden layers from your choice.'
)
#Taking the dataset directory as input from the user
parser.add_argument('--data_dir', metavar = '', type = str, default='flowers', help = 'Specify the root directory of the dataset')
#Taking the dataset directory as input from the user
parser.add_argument('--save_dir', metavar = '', type = str, default='./', help = 'Specify the root directory including the file name with .pth extension')
# Taking the learning rate from the user as float variable from the user
parser.add_argument('--learning_rate', metavar = '', type = float, default = 0.005, help = 'Specify the learning rate of the SGD optimizer that will be used')
# Take the model name architecture for more information about these architectures visit pytorch.org
parser.add_argument('--arch', metavar = '', type = str, default = 'vgg16', help = "Specify the neural network architecture that will be used. Choose either 'vgg13', 'vgg16', or 'alexnet'. The default is vgg16")
# Take the hidden layer dimensions as inputs
parser.add_argument('--hidden_layers', metavar = '', type = int, nargs = '+', default = [4096], help = 'Specify the dimensions of the hidden layers as list. The default has only a single element with 4096 neurons')
# Take the number of epochs as inputs
parser.add_argument('--epochs', metavar= '', type = int, default = 1, help ='The number of training epochs the default value is 10')
# Take the device type you wish to train your model on
parser.add_argument('--gpu', action = 'store_true', help = 'Specifiy whether you want to train your model on a CPU or a GPU by just writing --gpu. It chooses the GPU by default if it is available')
# Specify the dropout rate
parser.add_argument('--dropout', metavar = '', type = float, default = 0.2, help = 'Specify the dropout rate that will be used for the fully connected layers, which you will specify their dimensions. The default value is 0.2')
#parser.add_argument('--save_checkpoint', metavar = '', type = str, default = './', help = 'Specify the dicrectory in which you wish to save your trained model parameters')
args = parser.parse_args()
# Load the training and validation datasets
(train_images, _, _), (train_data, valid_data, _) = data_loader.load_image_dataset(args.data_dir)
# Load one batch the training data as it will help later for knowing the output of the convolution layers
batch_images, _ = next(iter(train_data))
# Load the model architecture based on the inputs. If
if args.arch =='vgg16':
loaded_model = torchvision.models.vgg16(pretrained=True)
elif args.arch =='vgg13':
loaded_model = torchvision.models.vgg13(pretrained=True)
elif args.arch =='alexnet':
loaded_model = torchvision.models.alexnet(pretrained=True)
else:
print('The provided model architecture is not available.\n The vgg16 model has been assigned')
loaded_model = torchvision.models.vgg16(pretrained=True)
# Display the model architecture
print('Here is the model architecture', loaded_model)
# Define the input_dims
features_out = loaded_model.features(batch_images).view(batch_images.shape[0], -1).shape[-1]
# Define the fully connected (classifier) model and print it
model = Model.Network(input_dims = features_out, hidden_layers=args.hidden_layers, dropout=args.dropout)
print('Here is the model to be attached\n', model)
# Remove the classifier of the loaded network, freeze its conv layers, and add the new classifier defined above
model = Model.Extend(loaded_model, model)
print('Here is the new model\n', model)
#Now it is time for training the new model
if torch.cuda.is_available() and args.gpu:
device = torch.device('cuda')
torch.cuda.manual_seed_all(42)
model.cuda()
else:
device = torch.device('cpu')
model.cpu()
print('{} is in use.'.format(device))
trained_model = Model.train_model(model = model,
train_data = train_data,
valid_data = valid_data,
epochs = args.epochs,
lr = args.learning_rate,
device = device)
#
trained_model.class_to_idx = train_images.class_to_idx
trained_model.to(torch.device('cpu'))
params_dict = {'model_state_dict': trained_model.state_dict(),
'model': trained_model
}
torch.save(params_dict, args.save_dir+'my_model.pth')
|
Java
|
UTF-8
| 1,774 | 2.28125 | 2 |
[] |
no_license
|
package net.castelluciv.asynchttpsample.controller;
import net.castelluciv.asynchttpsample.controller.handler.MovieHandler;
import net.castelluciv.asynchttpsample.model.Movie;
import net.castelluciv.asynchttpsample.repository.MovieRepository;
import java.util.concurrent.CompletableFuture;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.Dsl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class MovieController {
@Value("${omdbapi.apikey}")
private String apiKey;
private final MovieRepository repository;
private final AsyncHttpClient client = Dsl.asyncHttpClient();
@Autowired
public MovieController(final MovieRepository repository) {
this.repository = repository;
}
@GetMapping("/{imdbId}")
public CompletableFuture<ResponseEntity<Movie>> getById(@PathVariable final String imdbId) {
return repository.findByImdbId(imdbId)
.map(movie -> CompletableFuture.completedFuture(ResponseEntity.ok(movie)))
.orElseGet(() -> client
.executeRequest(Dsl.get(String.format("http://www.omdbapi.com/?i=%s&apikey=%s",
imdbId,
apiKey))
.build(),
new MovieHandler(repository))
.toCompletableFuture());
// Here we can do some other heavy computation or register action on completable completion (using thenXXXAsync)
}
}
|
Python
|
UTF-8
| 4,134 | 2.9375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 16:07:39 2018
@author: Sabya
"""
from __future__ import print_function, division
from builtins import range
import numpy as np
import matplotlib.pyplot as plt
class Hidden(object):
def __init__(self,fanin,fanout):
self.W = np.random.randn(fanin,fanout)/np.sqrt(fanin+fanout)
self.B = np.zeros(fanout)
def relu(self,a):
return a*(a>0)
def forward(self,x):
lin = x.dot(self.W)+self.B
yhat = self.relu(lin)
self.out = yhat
return yhat
class ANN(object):
def __init__(self,hiddenlayers):
self.hidden = hiddenlayers
self.hiddenlayerObj = []
def cost(self,yhat,y):
return -(y*np.log(yhat)).sum()
def softmax(self,x):
ex = np.exp(x)/np.exp(x).sum(axis=1,keepdims=True)
return ex
def hiddeninit(self,x_in):
fanin = x_in.shape[1]
for fanout in self.hidden:
h = Hidden(fanin,fanout)
self.hiddenlayerObj.append(h)
fanin = fanout
def forward(self,x_in):
out = x_in
for hid in self.hiddenlayerObj:
out = hid.forward(out)
outlin = out.dot(self.W)+self.B
yhat = self.softmax(outlin)
return yhat
def grad(self,x_in,yhat,y,learning_rate,reg):
delta = yhat - y
gwo = self.hiddenlayerObj[-1].out.T.dot(delta)
gdwo = gwo + (reg*self.W)
gbo = delta.sum(axis=0)
gdbo = gbo + (reg*self.B)
self.W = self.W - (learning_rate*gdwo)
self.B = self.B - (learning_rate*gdbo)
for i in range(len(self.hiddenlayerObj)):
i = i+1
if i==1:
delta = delta.dot(self.W.T)*(self.hiddenlayerObj[0-i].out>0)
else:
delta = delta.dot(self.hiddenlayerObj[0-(i-1)].W.T)*(self.hiddenlayerObj[0-i].out>0)
if i == len(self.hiddenlayerObj):
gwi = x_in.T.dot(delta)
else:
gwi = self.hiddenlayerObj[0-(i+1)].out.T.dot(delta)
gbi = delta.sum(axis=0)
gdwi = gwi + (reg*self.hiddenlayerObj[0-i].W)
self.hiddenlayerObj[0-i].W = self.hiddenlayerObj[0-i].W - (learning_rate*gdwi)
gdbi = gbi + (reg*self.hiddenlayerObj[0-i].B)
self.hiddenlayerObj[0-i].B = self.hiddenlayerObj[0-i].B - (learning_rate*gdbi)
def fit(self,x_train,y_train,x_test,y_test,learning_rate,reg,epochs=100):
self.hiddeninit(x_train)
self.W = np.random.randn(self.hidden[-1],y_train.shape[1])/np.sqrt(self.hidden[-1]+y_train.shape[1])
self.B = np.zeros(y_train.shape[1])
traincost = []
testcost = []
for epoch in range(epochs):
yhat = self.forward(x_train)
self.grad(x_train,yhat,y_train,learning_rate,reg)
yhtest = self.forward(x_test)
trainc = self.cost(yhat,y_train)
testc = self.cost(yhtest,y_test)
traincost.append(trainc)
testcost.append(testc)
print("Epoch No :- ",epoch," Train Cost :- ",trainc," Test Cost :- ",testc)
plt.plot(traincost,label='Train cost')
plt.plot(testcost,label='Test cost')
plt.legend()
plt.show()
def predict(self,x_in):
yhat = self.forward(x_in)
return np.argmax(yhat,axis=1)
###########################################
#Testing Code
##########################################
#from process import get_data
#def y2indicator(y, K):
# N = len(y)
# ind = np.zeros((N, K))
# for i in range(N):
# ind[i, y[i]] = 1
# return ind
#Xtrain, Y, Xtest, Yt = get_data()
#K = len(set(Y) | set(Yt))
#Ytrain = y2indicator(Y, K)
#Ytest = y2indicator(Yt, K)
#ann = ANN([20,30,15])
#ann.fit(Xtrain,Ytrain,Xtest,Ytest,learning_rate=0.0001,reg=0.01,epochs=6000)
#yhat = ann.predict(Xtest)
#print("Score :- ",np.mean(yhat==Yt))
#yhattr = ann.predict(Xtrain)
#print("TrainScore :-",np.mean(yhattr==Y))
|
C
|
UTF-8
| 10,968 | 2.640625 | 3 |
[] |
no_license
|
/*
* file : ftp_curl.c
* desc : ftp functions based on libcurl, modified from libcurl examples
* author : Peter Xu
* time : 2009.10.11
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <stdarg.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include "ftp_curl.h"
#define LOGHEAD "[ftp-curl] "
#define BUF_LEN 256
struct FtpFile {
const char *filename;
FILE *stream;
};
int init_curl_options(FTP_CURL_OPTIONS *options_p, int timeout, int debug)
{
if (options_p == NULL)
return -1;
options_p->timeout = timeout;
options_p->debug = debug;
options_p->total_time = 0;
options_p->speed = 0;
options_p->bytes_done = 0;
options_p->last_response = 0L;
return 0;
}
const char *ftp_curl_error_str(int err_no)
{
return curl_easy_strerror((CURLcode) err_no);
}
struct curl_info {
double speed_download;//CURLINFO_SPEED_DOWNLOAD
double speed_upload;//CURLINFO_SPEED_UPLOAD
double total_time;//CURLINFO_TOTAL_TIME
long last_response;//CURLINFO_RESPONSE_CODE
} s_curl_info ;
int progress_callback(void *clientp, double dltotal, double dlnow,
double ultotal, double ulnow)
{
double *bytes = (double *)clientp;
if (dltotal) // in download progress
*bytes = dlnow;
else // in upload progress
*bytes = ulnow;
return 0;
}
int get_curl_info(CURL *curl)
{
int ret;
ret = curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD,
&s_curl_info.speed_download);
if (ret != CURLE_OK)
return -1;
ret = curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD,
&s_curl_info.speed_upload);
if (ret != CURLE_OK)
return -1;
ret = curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME,
&s_curl_info.total_time);
if (ret != CURLE_OK)
return -1;
ret = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE,
&s_curl_info.last_response);
if (ret != CURLE_OK)
return -1;
printf(LOGHEAD "download speed \t: %f.\n", s_curl_info.speed_download);
printf(LOGHEAD "upload speed \t: %f.\n", s_curl_info.speed_upload);
printf(LOGHEAD "total time \t\t: %f.\n", s_curl_info.total_time);
printf(LOGHEAD "last respose \t: %ld.\n:", s_curl_info.last_response);
return 0;
}
static size_t ftp_curl_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
struct FtpFile *out=(struct FtpFile *)stream;
if(out && !out->stream) {
/* open file for writing */
out->stream=fopen(out->filename, "wb");
if(!out->stream)
return -1; /* failure, can't open file to write */
}
return fwrite(buffer, size, nmemb, out->stream);
}
int ftp_download_resumable(char *local_file, char *remote_file,
FTP_CURL_OPTIONS *option_p)
{
CURL *curl;
CURLcode res;
long file_len = 0;
double downloaded = 0;
struct stat mystat;
int ret;
if(local_file == NULL || remote_file == NULL) {
printf(LOGHEAD "download file cannot be empty.\n");
return -1;
}
struct FtpFile ftpfile={
local_file,
NULL
};
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
// get the file size, for resuming the download
bzero((void *)&mystat, sizeof(mystat));
if(access(local_file, W_OK) == 0 && stat(local_file, &mystat) == 0 && mystat.st_size > 0) {
file_len = mystat.st_size;
printf(LOGHEAD "file %s exists, size %ld, using appending mode.\n",
local_file, file_len);
ftpfile.stream = fopen(local_file, "ab+");
fseek(ftpfile.stream, file_len, SEEK_SET);
}
curl_easy_setopt(curl, CURLOPT_RESUME_FROM, file_len);
curl_easy_setopt(curl, CURLOPT_URL, remote_file);
/* Define our callback to get called when there's data to be written */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ftp_curl_fwrite);
/* Set a pointer to our struct to pass to the callback */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
/* Switch on full protocol/debug output */
curl_easy_setopt(curl, CURLOPT_VERBOSE, (long)option_p->debug);
// trace transfer progress
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &downloaded);
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback);
// set timeout
if (option_p->timeout)
curl_easy_setopt(curl, CURLOPT_FTP_RESPONSE_TIMEOUT, option_p->timeout);
res = curl_easy_perform(curl);
// how many bytes downloaded ?
option_p->bytes_done = downloaded;
/* always cleanup */
curl_easy_cleanup(curl);
// get curl info
if ( ret = get_curl_info(curl) ) {
printf(LOGHEAD "error in getting curl info, ret is %d.\n", ret);
} else {
// return the aver speed
option_p->speed = s_curl_info.speed_download;
option_p->total_time = s_curl_info.total_time;
}
if(CURLE_OK != res) {
/* we failed */
printf(LOGHEAD "curl told us %d\n", res);
curl_global_cleanup();
return res;
}
} else {
printf(LOGHEAD "cannot do the curl_easy_init().\n");
return -1;
}
if(ftpfile.stream)
fclose(ftpfile.stream); /* close the local file */
curl_global_cleanup();
return 0;
}
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
/* in real-world cases, this would probably get this data differently
as this fread() stuff is exactly what the library already would do
by default internally */
size_t retcode = fread(ptr, size, nmemb, stream);
printf(LOGHEAD "*** We read %d bytes from file\n", retcode);
return retcode;
}
/* parse headers for Content-Length */
size_t getcontentlengthfunc(void *ptr, size_t size, size_t nmemb, void *stream) {
int r;
long len = 0;
/* _snscanf() is Win32 specific */
//r = _snscanf(ptr, size * nmemb, "Content-Length: %ld\n", &len);
r = sscanf(ptr, "Content-Length: %ld\r\n", &len);
if (r) /* Microsoft: we don't read the specs */ {
// added by xzpeter for debugging
printf(LOGHEAD "remote file length updated to %ld.\n", len);
*((long *) stream) = len;
}
return size * nmemb;
}
int ftp_upload_resumable(char *remote_file, char *local_file,
FTP_CURL_OPTIONS *option_p)
{
int ret;
CURL *curl;
CURLcode res;
FILE *hd_src;
struct stat file_info;
curl_off_t uploaded_len = 0;
curl_off_t fsize;
double uploaded = 0;
/* get the file size of the local file */
if(stat(local_file, &file_info)) {
printf(LOGHEAD "Couldnt open '%s': %s\n", local_file, strerror(errno));
return -1;
}
fsize = (curl_off_t)file_info.st_size;
printf(LOGHEAD "Local file size: %ld bytes.\n", (long)fsize);
/* get a FILE * of the same file */
hd_src = fopen(local_file, "rb");
/* In windows, this will init the winsock stuff */
curl_global_init(CURL_GLOBAL_ALL);
/* get a curl handle */
curl = curl_easy_init();
if(curl) {
// basic option settings
// set the read function
curl_easy_setopt(curl, CURLOPT_READDATA, hd_src);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
// set the process function of the headers
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, getcontentlengthfunc);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &uploaded_len);
// set the remote url
curl_easy_setopt(curl,CURLOPT_URL, remote_file);
// set verbose or not
curl_easy_setopt(curl, CURLOPT_VERBOSE, (long)option_p->debug);
// set timeout
if (option_p->timeout)
curl_easy_setopt(curl, CURLOPT_FTP_RESPONSE_TIMEOUT,
option_p->timeout);
// settings for the first attempt, to get the remote file size
// add these 2 opt to send a SIZE cmd in order to get the remote file size
curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
curl_easy_setopt(curl, CURLOPT_HEADER, 1L);
// do not upload for the first attempt
curl_easy_setopt(curl, CURLOPT_UPLOAD, 0L);
// do the first attempt
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
printf(LOGHEAD "something wrong during curl_easy_perform()[1].\n");
goto easy_curl_quit;
}
// now get the size of the remote file in uploaded_len
if(fsize < uploaded_len) {
// should not get in here ...
printf(LOGHEAD "local file size is %ld, remote file size is %ld, something wrong.\n",
(long)fsize, (long)uploaded_len);
goto easy_curl_quit;
}
// maybe the file has been uploaded ok
if(fsize == uploaded_len) {
printf(LOGHEAD "remote file is equal size of the local file, maybe upload is done before.\n");
goto easy_curl_quit;
}
fseek(hd_src, uploaded_len, SEEK_SET);
printf(LOGHEAD "fseek to %ld now, preparing for resuming upload.\n", (long)uploaded_len);
// then upload
curl_easy_setopt(curl, CURLOPT_NOBODY, 0L);
curl_easy_setopt(curl, CURLOPT_HEADER, 0L);
// set upload and append attribute
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl, CURLOPT_APPEND, 1L);
// trace transfer progress
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &uploaded);
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback);
res = curl_easy_perform(curl);
// how many bytes uploaded ?
option_p->bytes_done = uploaded;
if(res != CURLE_OK) {
printf(LOGHEAD "something wrong during curl_easy_perform()[2].\n");
goto easy_curl_quit;
}
printf(LOGHEAD "transfer done.\n");
// if success, get the upload speed
if (get_curl_info(curl)) {
printf(LOGHEAD "error to get_curl_info().");
} else {
option_p->speed = s_curl_info.speed_upload;
option_p->total_time = s_curl_info.total_time;
}
/* always cleanup */
easy_curl_quit:
curl_easy_cleanup(curl);
} else {
printf(LOGHEAD "cannot do the curl_easy_init().\n");
}
fclose(hd_src); /* close the local file */
curl_global_cleanup();
return res;
}
#define FTP_UNLINK_STR "DELE "
int ftp_unlink(char *remote_url, FTP_CURL_OPTIONS *options_p)
{
CURL *curl;
int ret, n;
struct curl_slist *headerlist=NULL;
char tmp_buf[BUF_LEN] = FTP_UNLINK_STR;
char *pch;
char *file_name;
if (remote_url == NULL)
return -1;
file_name = strrchr(remote_url, '/');
if (file_name == NULL)
return -2;
// copy the filename to the cmd list
file_name++;
strncat(tmp_buf, file_name, BUF_LEN - strlen(FTP_UNLINK_STR) - 1);
// remove the filename from remote url
*file_name = 0x00;
curl_global_init(CURL_GLOBAL_ALL);
/* get a curl handle */
curl = curl_easy_init();
if(curl) {
/* build a list of commands to pass to libcurl */
headerlist = curl_slist_append(headerlist, tmp_buf);
/* specify target */
curl_easy_setopt(curl, CURLOPT_URL, remote_url);
/* pass in that last of FTP commands to run after the transfer */
curl_easy_setopt(curl, CURLOPT_POSTQUOTE, headerlist);
// set verbose or not
curl_easy_setopt(curl, CURLOPT_VERBOSE, (long)options_p->debug);
// set timeout
if (options_p->timeout)
curl_easy_setopt(curl, CURLOPT_FTP_RESPONSE_TIMEOUT,
options_p->timeout);
/* Now run off and do what you've been told! */
ret = curl_easy_perform(curl);
/* clean up the FTP commands list */
curl_slist_free_all (headerlist);
/* always cleanup */
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return ret;
}
|
Python
|
UTF-8
| 23,942 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
# -*- encoding:utf-8 -*-
"""封装常用的分析方式及流程模块"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import matplotlib.cbook as cbook
import matplotlib.pyplot as plt
import numpy as np
from scipy import interp
from sklearn import metrics
from sklearn import tree
from sklearn.base import ClusterMixin, clone
from sklearn.metrics import roc_curve, auc
from ..CoreBu.ABuFixes import KFold, learning_curve
from ..UtilBu.ABuDTUtil import warnings_filter
# noinspection PyUnresolvedReferences
from ..CoreBu.ABuFixes import range
from ..UtilBu.ABuFileUtil import file_exist
__author__ = '阿布'
__weixin__ = 'abu_quant'
__all__ = [
'run_silhouette_cv_estimator',
'run_prob_cv_estimator',
'run_cv_estimator',
'plot_learning_curve',
'plot_decision_boundary',
'plot_confusion_matrices',
'plot_roc_estimator',
'graphviz_tree',
'visualize_tree'
]
# noinspection PyUnresolvedReferences
def run_silhouette_cv_estimator(estimator, x, n_folds=10):
"""
只针对kmean的cv验证,使用silhouette_score对聚类后的结果labels_
进行度量使用silhouette_score,kmean的cv验证只是简单的通过np.random.choice
进行随机筛选x数据进行聚类的silhouette_score度量,并不涉及训练集测试集
:param estimator: keman或者支持estimator.labels_, 只通过if not isinstance(estimator, ClusterMixin)进行过滤
:param x: x特征矩阵
:param n_folds: int,透传KFold参数,切割训练集测试集参数,默认10
:return: eg: array([ 0.693 , 0.652 , 0.6845, 0.6696, 0.6732, 0.6874, 0.668 ,
0.6743, 0.6748, 0.671 ])
"""
if not isinstance(estimator, ClusterMixin):
print('estimator must be ClusterMixin')
return
silhouette_list = list()
# eg: n_folds = 10, len(x) = 150 -> 150 * 0.9 = 135
choice_cnt = int(len(x) * ((n_folds - 1) / n_folds))
choice_source = np.arange(0, x.shape[0])
# 所有执行fit的操作使用clone一个新的
estimator = clone(estimator)
for _ in np.arange(0, n_folds):
# 只是简单的通过np.random.choice进行随机筛选x数据
choice_index = np.random.choice(choice_source, choice_cnt)
x_choice = x[choice_index]
estimator.fit(x_choice)
# 进行聚类的silhouette_score度量
silhouette_score = metrics.silhouette_score(x_choice, estimator.labels_, metric='euclidean')
silhouette_list.append(silhouette_score)
return silhouette_list
def run_prob_cv_estimator(estimator, x, y, n_folds=10):
"""
通过KFold和参数n_folds拆分训练集和测试集,使用
np.zeros((len(y), len(np.unique(y))))初始化prob矩阵,
通过训练estimator.fit(x_train, y_train)后的分类器使用
predict_proba将y_prob中的对应填数据
:param estimator: 支持predict_proba的有监督学习, 只通过hasattr(estimator, 'predict_proba')进行过滤
:param x: 训练集x矩阵,numpy矩阵
:param y: 训练集y序列,numpy序列
:param n_folds: int,透传KFold参数,切割训练集测试集参数,默认10
:return: eg: y_prob
array([[ 0.8726, 0.1274],
[ 0.0925, 0.9075],
[ 0.2485, 0.7515],
...,
[ 0.3881, 0.6119],
[ 0.7472, 0.2528],
[ 0.8555, 0.1445]])
"""
if not hasattr(estimator, 'predict_proba'):
print('estimator must has predict_proba')
return
# 所有执行fit的操作使用clone一个新的
estimator = clone(estimator)
kf = KFold(len(y), n_folds=n_folds, shuffle=True)
y_prob = np.zeros((len(y), len(np.unique(y))))
"""
根据y序列的数量以及y的label数量构造全是0的矩阵
eg: y_prob
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
..............
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
"""
for train_index, test_index in kf:
x_train, x_test = x[train_index], x[test_index]
y_train = y[train_index]
# clf = clone(estimator)
estimator.fit(x_train, y_train)
# 使用predict_proba将y_prob中的对应填数据
y_prob[test_index] = estimator.predict_proba(x_test)
return y_prob
def run_cv_estimator(estimator, x, y, n_folds=10):
"""
通过KFold和参数n_folds拆分训练集和测试集,使用
y.copy()初始化y_pred矩阵,迭代切割好的训练集与测试集,
不断通过 estimator.predict(x_test)将y_pred中的值逐步替换
:param estimator: 有监督学习器对象
:param x: 训练集x矩阵,numpy矩阵
:param y: 训练集y序列,numpy序列
:param n_folds: int,透传KFold参数,切割训练集测试集参数,默认10
:return: y_pred序列
"""
if not hasattr(estimator, 'predict'):
print('estimator must has predict')
return
# 所有执行fit的操作使用clone一个新的
estimator = clone(estimator)
kf = KFold(len(y), n_folds=n_folds, shuffle=True)
# 首先copy一个一摸一样的y
y_pred = y.copy()
"""
eg: y_pred
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
"""
for train_index, test_index in kf:
x_train, x_test = x[train_index], x[test_index]
y_train = y[train_index]
estimator.fit(x_train, y_train)
# 通过 estimator.predict(x_test)将y_pred中的值逐步替换
y_pred[test_index] = estimator.predict(x_test)
return y_pred
# warnings_filter针对多标签使用OneVsRestClassifier出现的版本警告
@warnings_filter
def plot_learning_curve(estimator, x, y, cv=5, n_jobs=1,
train_sizes=np.linspace(.05, 1., 20)):
"""
绘制学习曲线,train_sizes使用np.linspace(.05, 1., 20)即训练集从5%-100%递进
np.linspace(.05, 1., 20)
array([ 0.05, 0.1 , 0.15, 0.2 , 0.25, 0.3 , 0.35, 0.4 , 0.45,
0.5 , 0.55, 0.6 , 0.65, 0.7 , 0.75, 0.8 , 0.85, 0.9 ,
0.95, 1. ])
套接sklern中learning_curve函数,传递estimator,cv等参数
:param estimator: 学习器对象,透传learning_curve
:param x: 训练集x矩阵,numpy矩阵
:param y: 训练集y序列,numpy序列
:param cv: 透传learning_curve,cv参数,默认5,int
:param n_jobs: 透传learning_curve,并行进程数,默认1,即使用单进程执行
:param train_sizes: train_sizes使用np.linspace(.05, 1., 20)即训练集从5%-100%递进
"""
# 套接learning_curve,返回训练集和测试集的score和对应的size
train_sizes, train_scores, test_scores = learning_curve(
estimator, x, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
"""
eg: train_scores shape = (20, 5)
array([[ 0.8571, 0.9143, 0.9143, 0.9143, 0.9143],
[ 0.8169, 0.8732, 0.8732, 0.8732, 0.8732],
[ 0.8208, 0.8396, 0.8396, 0.8396, 0.8396],
[ 0.8028, 0.8099, 0.8099, 0.8099, 0.8099],
[ 0.8146, 0.8202, 0.8146, 0.8146, 0.8146],
[ 0.8263, 0.8263, 0.8216, 0.8216, 0.8216],
[ 0.8153, 0.8273, 0.8112, 0.8112, 0.8112],
[ 0.8063, 0.8169, 0.7993, 0.7993, 0.7993],
[ 0.8156, 0.8281, 0.8063, 0.8063, 0.8063],
[ 0.8169, 0.8254, 0.8254, 0.8254, 0.8254],
[ 0.8184, 0.8235, 0.8261, 0.8312, 0.8312],
[ 0.815 , 0.822 , 0.8197, 0.822 , 0.822 ],
[ 0.816 , 0.8203, 0.8203, 0.8182, 0.8182],
[ 0.8133, 0.8173, 0.8173, 0.8253, 0.8253],
[ 0.8109, 0.8127, 0.8146, 0.8202, 0.8221],
[ 0.8155, 0.819 , 0.8172, 0.8207, 0.8225],
[ 0.8149, 0.8248, 0.8231, 0.8248, 0.8198],
[ 0.8187, 0.8281, 0.825 , 0.8328, 0.8219],
[ 0.8254, 0.8299, 0.8284, 0.8343, 0.8166],
[ 0.8272, 0.8315, 0.8301, 0.8343, 0.8174]])
"""
train_scores_mean = np.mean(train_scores, axis=1)
"""
eg: train_scores_mean
array([ 0.9029, 0.862 , 0.8358, 0.8085, 0.8157, 0.8235, 0.8153,
0.8042, 0.8125, 0.8237, 0.8261, 0.8201, 0.8186, 0.8197,
0.8161, 0.819 , 0.8215, 0.8253, 0.8269, 0.8281])
"""
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
"""
eg: test_scores_std
array([ 0.0751, 0.0607, 0.0314, 0.0059, 0.0047, 0.0066, 0.0074,
0.0051, 0.0107, 0.0115, 0.0107, 0.012 , 0.0142, 0.018 ,
0.0134, 0.0167, 0.0167, 0.0127, 0.0128, 0.0113])
"""
# 开始可视化学习曲线
plt.figure()
plt.title('learning curve')
plt.xlabel("train sizes")
plt.ylabel("scores")
plt.gca().invert_yaxis()
plt.grid()
# 对train_scores的均值和方差区域进行填充
plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std,
alpha=0.1, color="g")
# 对test_scores的均值和方差区域进行填充
plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std,
alpha=0.1, color="r")
# 把train_scores_mean标注圆圈
plt.plot(train_sizes, train_scores_mean, 'o-', color="g", label="train scores")
# 把ttest_scores_mean标注圆圈
plt.plot(train_sizes, test_scores_mean, 'o-', color="r", label="test scores")
plt.legend(loc="best")
plt.draw()
plt.gca().invert_yaxis()
plt.show()
def graphviz_tree(estimator, features, x, y):
"""
绘制决策树或者core基于树的分类回归算法的决策示意图绘制,查看
学习器本身hasattr(fiter, 'tree_')是否有tree_属性,内部clone(estimator)学习器
后再进行训练操作,完成训练后使用sklearn中tree.export_graphvizd导出graphviz.dot文件
需要使用第三方dot工具将graphviz.dot进行转换graphviz.png,即内部实行使用
运行命令行:
os.system("dot -T png graphviz.dot -o graphviz.png")
最后读取决策示意图显示
:param estimator: 学习器对象,透传learning_curve
:param x: 训练集x矩阵,numpy矩阵
:param y: 训练集y序列,numpy序列
:param features: 训练集x矩阵列特征所队员的名称,可迭代序列对象
"""
if not hasattr(estimator, 'tree_'):
logging.info('only tree can graphviz!')
return
# 所有执行fit的操作使用clone一个新的
estimator = clone(estimator)
estimator.fit(x, y)
# TODO out_file path放倒cache中
tree.export_graphviz(estimator.tree_, out_file='graphviz.dot', feature_names=features)
os.system("dot -T png graphviz.dot -o graphviz.png")
'''
!open $path
要是方便用notebook直接open其实显示效果好,plt,show的大小不好调整
'''
graphviz = os.path.join(os.path.abspath('.'), 'graphviz.png')
# path = graphviz
# !open $path
if not file_exist(graphviz):
logging.info('{} not exist! please install dot util!'.format(graphviz))
return
image_file = cbook.get_sample_data(graphviz)
image = plt.imread(image_file)
image_file.close()
plt.imshow(image)
plt.axis('off') # clear x- and y-axes
plt.show()
def visualize_tree(estimator, x, y, boundaries=True):
"""
需要x矩阵特征列只有两个维度,根据x,y,通过meshgrid构造训练集平面特征
通过z = estimator.predict(np.c_[xx.ravel(), yy.ravel()])对特征平面
进行predict生成z轴,可视化meshgrid构造训练集平面特征使用生成的z生成
pcolormesh进行可视化
:param estimator: 学习器对象,内部clone(estimator)
:param x: 训练集x矩阵,numpy矩阵,需要特征列只有两个维度
:param y: 训练集y序列,numpy序列
:param boundaries: 是否绘制决策边界
"""
if x.shape[1] != 2:
logging.info('be sure x shape[1] == 2!')
return
# 所有执行fit的操作使用clone一个新的
estimator = clone(estimator)
estimator.fit(x, y)
xlim = (x[:, 0].min() - 0.1, x[:, 0].max() + 0.1)
ylim = (x[:, 1].min() - 0.1, x[:, 1].max() + 0.1)
x_min, x_max = xlim
y_min, y_max = ylim
# 通过训练集中x的min和max,y的min,max构成meshgrid
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
np.linspace(y_min, y_max, 100))
# 摊平xx,yy进行z轴的predict
z = estimator.predict(np.c_[xx.ravel(), yy.ravel()])
# z的shape跟随xx
z = z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, z, alpha=0.2, cmap='rainbow')
plt.clim(y.min(), y.max())
# 将之前的训练集中的两个特征进行scatter绘制,颜色使用y做区分
plt.scatter(x[:, 0], x[:, 1], c=y, s=50, cmap='rainbow')
plt.axis('off')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.clim(y.min(), y.max())
def plot_boundaries(i, p_xlim, p_ylim):
"""
针对有tree_属性的学习器绘制决策边界
:param i: 内部递归调用使用ree_inner.children_left[i]和tree_inner.children_right[i]
:param p_xlim: 原始参数使用plt.xlim()
:param p_ylim: 原始参数使用plt.ylim()
"""
if i < 0:
return
# 拿到tree_使用plot_boundaries继续递归绘制
tree_inner = estimator.tree_
if tree_inner.feature[i] == 0:
# 绘制0的边界
plt.plot([tree_inner.threshold[i], tree_inner.threshold[i]], p_ylim, '-k')
# 即x轴固定p_ylim,xlim=[p_xlim[0], tree_inner.threshold[i]], [tree_inner.threshold[i], p_xlim[1]]
plot_boundaries(tree_inner.children_left[i],
[p_xlim[0], tree_inner.threshold[i]], p_ylim)
plot_boundaries(tree_inner.children_right[i],
[tree_inner.threshold[i], p_xlim[1]], p_ylim)
elif tree_inner.feature[i] == 1:
# 绘制1的边界
plt.plot(p_xlim, [tree_inner.threshold[i], tree_inner.threshold[i]], '-k')
# 即y轴固定p_xlim,ylim=[p_ylim[0], tree_inner.threshold[i]], [tree_inner.threshold[i], p_ylim[1]]
plot_boundaries(tree_inner.children_left[i], p_xlim,
[p_ylim[0], tree_inner.threshold[i]])
plot_boundaries(tree_inner.children_right[i], p_xlim,
[tree_inner.threshold[i], p_ylim[1]])
if boundaries and hasattr(estimator, 'tree_'):
# 简单决策树才去画决策边界
plot_boundaries(0, plt.xlim(), plt.ylim())
def plot_decision_boundary(pred_func, x, y):
"""
通过x,y以构建meshgrid平面区域,要x矩阵特征列只有两个维度,在区域中使用外部传递的
pred_func函数进行z轴的predict,通过contourf绘制特征平面区域,最后使用
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Spectral)在平面区域上填充原始特征
点
:param pred_func: callable函数,eg:pred_func: lambda p_x: fiter.predict(p_x), x, y
:param x: 训练集x矩阵,numpy矩阵,需要特征列只有两个维度
:param y: 训练集y序列,numpy序列
"""
xlim = (x[:, 0].min() - 0.1, x[:, 0].max() + 0.1)
ylim = (x[:, 1].min() - 0.1, x[:, 1].max() + 0.1)
x_min, x_max = xlim
y_min, y_max = ylim
# 通过训练集中x的min和max,y的min,max构成meshgrid
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 200),
np.linspace(y_min, y_max, 200))
# 摊平xx,yy进行z轴的predict, pred_func: lambda p_x: fiter.predict(p_x), x, y
z = pred_func(np.c_[xx.ravel(), yy.ravel()])
# z的shape跟随xx
z = z.reshape(xx.shape)
# 使用contourf绘制xx, yy, z,即特征平面区域以及z的颜色区别
# noinspection PyUnresolvedReferences
plt.contourf(xx, yy, z, cmap=plt.cm.Spectral)
# noinspection PyUnresolvedReferences
# 在特征区域的基础上将原始,两个维度使用scatter绘制以y为颜色的点
plt.scatter(x[:, 0], x[:, 1], c=y, cmap=plt.cm.Spectral)
plt.show()
def plot_roc_estimator(estimator, x, y, pos_label=None):
"""
固定n_folds=10通过kf = KFold(len(y), n_folds=10, shuffle=True)拆分
训练测试集,使用estimator.predict_proba对测试集数据进行概率统计,直接使用
sklearn中的roc_curve分别对多组测试集计算fpr, tpr, thresholds,并计算roc_auc
最后绘制roc_auc曲线进行可视化操作
:param estimator: 分类器对象,内部clone(estimator)
:param x: 训练集x矩阵,numpy矩阵
:param y: 训练集y序列,numpy序列
:param pos_label: 对y大于2个label的数据,roc_curve需要指定pos_label,如果不指定,默认使用y的第一个label值
"""
if not hasattr(estimator, 'predict_proba'):
# 分类器必须要有predict_proba方法
logging.info('estimator must has predict_proba!')
return
# 所有执行fit的操作使用clone一个新的
estimator = clone(estimator)
estimator.fit(x, y)
# eg: y_unique = [0, 1]
y_unique = np.unique(y)
kf = KFold(len(y), n_folds=10, shuffle=True)
y_prob = np.zeros((len(y), len(y_unique)))
"""
eg: y_prob
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
...,
[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
"""
mean_tpr = 0.0
# 0-1分布100个
mean_fpr = np.linspace(0, 1, 100)
for i, (train_index, test_index) in enumerate(kf):
x_train, x_test = x[train_index], x[test_index]
y_train = y[train_index]
estimator.fit(x_train, y_train)
y_prob[test_index] = estimator.predict_proba(x_test)
"""
eg: y_prob[test_index]
array([[ 0.8358, 0.1642],
[ 0.4442, 0.5558],
[ 0.1351, 0.8649],
[ 0.8567, 0.1433],
[ 0.6953, 0.3047],
..................
[ 0.1877, 0.8123],
[ 0.8465, 0.1535],
[ 0.1916, 0.8084],
[ 0.8421, 0.1579]])
"""
if len(y_unique) != 2 and pos_label is None:
# 对y大于2个label的数据,roc_curve需要指定pos_label,如果不指定,默认使用y的第一个label值
pos_label = y_unique[0]
logging.info('y label count > 2 and param pos_label is None, so choice y_unique[0]={} for pos_label!'.
format(pos_label))
fpr, tpr, thresholds = roc_curve(y[test_index], y_prob[test_index, 1], pos_label=pos_label)
"""
eg:
fpr
array([ 0. , 0.0169, 0.0169, 0.0339, 0.0339, 0.0508, 0.0508,
0.0847, 0.0847, 0.1017, 0.1017, 0.1186, 0.1186, 0.2034,
0.2034, 0.2542, 0.2542, 0.5254, 0.5254, 0.5763, 0.5763, 1. ])
tpr
array([ 0.0323, 0.0323, 0.4839, 0.4839, 0.5484, 0.5484, 0.6452,
0.6452, 0.7419, 0.7419, 0.7742, 0.7742, 0.8387, 0.8387,
0.9032, 0.9032, 0.9355, 0.9355, 0.9677, 0.9677, 1. , 1. ])
thresholds
array([ 0.9442, 0.9288, 0.8266, 0.8257, 0.8123, 0.8122, 0.8032,
0.7647, 0.7039, 0.5696, 0.5558, 0.4854, 0.4538, 0.2632,
0.2153, 0.2012, 0.1902, 0.1616, 0.1605, 0.1579, 0.1561,
0.1301])
"""
# interp线性插值计算
mean_tpr += interp(mean_fpr, fpr, tpr)
# 把第一个值固定0,最后会使用mean_tpr[-1] = 1.0把最后一个固定1.0
mean_tpr[0] = 0.0
# 直接使用 sklearn中的metrics.auc计算
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc))
mean_tpr /= len(kf)
# 最后一个固定1.0
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
plt.plot(mean_fpr, mean_tpr, 'k--', label='Mean ROC (area = %0.2f)' % mean_auc, lw=2)
plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Random')
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
def plot_confusion_matrices(estimator, x, y, n_folds=10):
"""
套接run_cv_estimator进行通过参数n_folds进行训练集测试集拆封
使用y_pred和y做为参数,透传给metrics.confusion_matrix函数
进行混淆矩阵的计算,通过ax.matshow可视化混淆矩阵
:param estimator: 分类器对象,内部clone(estimator)
:param x: 训练集x矩阵,numpy矩阵
:param y: 训练集y序列,numpy序列
:param n_folds: 透传KFold参数,切割训练集测试集参数
"""
y_pred = run_cv_estimator(estimator, x, y, n_folds=n_folds)
"""
eg: y_pred
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
"""
y_unique = np.unique(y)
confusion_matrix = metrics.confusion_matrix(y, y_pred)
"""
eg: confusion_matrix
[[50 0 0]
[ 0 47 3]
[ 0 1 49]]
"""
logging.info(confusion_matrix)
fig = plt.figure()
# 颜色条的颜色数量设置使用len(y_unique) * len(y_unique),即如果y是3个label->9颜色。2->4
cmap = plt.get_cmap('jet', len(y_unique) * len(y_unique))
cmap.set_under('gray')
ax = fig.add_subplot(111)
# ax.matshow可视化化混淆矩阵
cax = ax.matshow(confusion_matrix, cmap=cmap,
vmin=confusion_matrix.min(),
vmax=confusion_matrix.max())
plt.title('Confusion matrix for %s' % estimator.__class__.__name__)
# 辅助颜色边bar显示
fig.colorbar(cax)
# noinspection PyTypeChecker
ax.set_xticklabels('x: '.format(y_unique))
# noinspection PyTypeChecker
ax.set_yticklabels('y: '.format(y_unique))
plt.xlabel('Predicted')
plt.ylabel('True')
plt.show()
|
TypeScript
|
UTF-8
| 1,411 | 2.546875 | 3 |
[] |
no_license
|
import { Injectable } from '@angular/core';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
@Injectable()
export class DbProvider {
db : SQLiteObject = null;
constructor( public sqlite: SQLite ) {
console.log('Hello DbProvider Provider');
}
public openDb(){
return this.sqlite.create({
name: 'data.db',
location: 'default' // el campo location es obligatorio
})
.then((db: SQLiteObject) => {
this.db =db;
})
}
public createTableCarros(){
return this.db.executeSql("create table if not exists carros( id INTEGER PRIMARY KEY AUTOINCREMENT, lat FLOAT, lng FLOAT, address TEXT, description TEXT, foto TEXT )",{})
}
public addCarro(carro){
let sql = "INSERT INTO carros (lat, lng, address, description, foto) values (?,?,?,?,?)";
return this.db.executeSql(sql,[carro.lat,carro.lng,carro.address,carro.description,carro.foto]);
}
public getCarros(){
let sql = "SELECT * FROM carros";
return this.db.executeSql(sql,{});
}
public modificaCarro(carro){
let sql = "UPDATE carros SET lat = ?, lng = ?, address = ?, description = ?, foto = ? WHERE id = ? ";
return this.db.executeSql(sql,[carro.lat,carro.lng,carro.address,carro.description,carro.foto, carro.id]);
}
public borrarCarro(id){
let sql = "DELETE FROM carros WHERE id= ? ";
return this.db.executeSql(sql,[id]);
}
}
|
Shell
|
UTF-8
| 2,591 | 2.546875 | 3 |
[] |
no_license
|
#!/bin/bash
# chemin vers les fichiers muxa pour se connecter aux cartes
PATH_XML_MUXA_FSP_ECU=/home/ft055062/prog/4g/all_hyper/HYPER-FSP-ECU/muxa-FSP-ECU-V01R03.xml
PATH_XML_MUXA_SSM_ECU=/home/ft055062/prog/4g/all_hyper/HYPER-SSM-ECU/HYPER-SSM-ECU-V01R05/muxa-SSM-ECU-V01R05.xml
PATH_XML_MUXA_MB_SPU=/home/ft055062/prog/4g/all_hyper/HYPER-MB-SPU/muxa-SPU-V01R02.xml
PATH_XML_MUXA_SSM_GPA=/home/ft055062/prog/4g/all_hyper/HYPER-SCA-GPA/HYPER-SCA-GPA-V01R03/muxa-SCA-GPA-V01R03.xml
# nom des sessions
S_DEV=DEV
S_SSM_ECU=SSM-ECU
S_FSP_ECU=FSP-ECU
S_MB_SPU=MB-SPU
S_SSM_GPA=SSM-GPA
tmux new-session -d -s $S_DEV
tmux new-session -d -s $S_SSM_ECU "muxa -f $PATH_XML_MUXA_SSM_ECU; exec bash"
sleep 1 # Wait for muxa to be connected to target.
tmux rename-window -t $S_SSM_ECU:1 'muxa'
tmux new-window -t $S_SSM_ECU:2 -n 'hyper-1715' "telnet localhost 1715; exec bash"
tmux new-window -t $S_SSM_ECU:3 -n 'posix-1704' "telnet localhost 1704; exec bash"
tmux new-window -t $S_SSM_ECU:4 -n 'linux-1709' "telnet localhost 1709; exec bash"
tmux split-window -h 'exec bash'
tmux select-pane -t $S_SSM_ECU:4 -lL
tmux new-session -d -s $S_FSP_ECU "muxa -f $PATH_XML_MUXA_FSP_ECU; exec bash"
sleep 1 # Wait for muxa to be connected to target.
tmux rename-window -t $S_FSP_ECU:1 'muxa'
tmux new-window -t $S_FSP_ECU:2 -n 'hyper-1815' "telnet localhost 1815; exec bash"
tmux new-window -t $S_FSP_ECU:3 -n 'posix-1804' "telnet localhost 1804; exec bash"
tmux new-window -t $S_FSP_ECU:4 -n 'linux-1809' "telnet localhost 1809; exec bash"
tmux split-window -h 'exec bash'
tmux select-pane -t $S_FSP_ECU:4 -lL
tmux new-session -d -s $S_MB_SPU "muxa -f $PATH_XML_MUXA_MB_SPU; exec bash"
sleep 1 # Wait for muxa to be connected to target.
tmux rename-window -t $S_MB_SPU:1 'muxa'
tmux new-window -t $S_MB_SPU:2 -n 'hyper-1615' "telnet localhost 1615; exec bash"
tmux new-window -t $S_MB_SPU:3 -n 'posix-1604' "telnet localhost 1604; exec bash"
tmux new-window -t $S_MB_SPU:4 -n 'linux-1609' "telnet localhost 1609; exec bash"
tmux split-window -h 'exec bash'
tmux select-pane -t $S_MB_SPU:4 -lL
tmux new-session -d -s $S_SSM_GPA "muxa -f $PATH_XML_MUXA_SSM_GPA; exec bash"
sleep 1 # Wait for muxa to be connected to target.
tmux rename-window -t $S_SSM_GPA:1 'muxa'
tmux new-window -t $S_SSM_GPA:2 -n 'hyper-1515' "telnet localhost 1515; exec bash"
tmux new-window -t $S_SSM_GPA:3 -n 'posix-1504' "telnet localhost 1504; exec bash"
tmux new-window -t $S_SSM_GPA:4 -n 'linux-1509' "telnet localhost 1509; exec bash"
tmux split-window -h 'exec bash'
tmux select-pane -t $S_SSM_GPA:4 -lL
tmux -2 a -t $S_DEV
|
Go
|
UTF-8
| 669 | 3.0625 | 3 |
[] |
no_license
|
package main
import (
"../utils"
"fmt"
)
func maxPoints(points [][]int) int {
n := len(points)
if n < 3 {
return n
}
res := 0
for i,point1 := range points {
hash := make(map[float64]int)
for j, point2 := range points {
if i != j {
hash[lineSlope(point1,point2)]++
}
}
for _, v := range hash {
if v > res{
res = v
}
}
}
return res+1
}
func lineSlope(a, b []int) float64 {
return float64(a[1]-b[1]) / float64(a[0]-b[0])
}
func main() {
ite := utils.NewITE("[[1,1],[2,2],[3,3]]")
fmt.Println(maxPoints(ite.ToIntInt()))
ite = utils.NewITE("[[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]")
fmt.Println(maxPoints(ite.ToIntInt()))
}
|
Markdown
|
UTF-8
| 3,139 | 2.78125 | 3 |
[] |
no_license
|
# RDS Relational Database Service
RDS is PARTIALLY MANAGED service, Dynamo is FULLY MANAGED Service
RDS can have public IP Address and be access from the internet.
When deplying to VPC - VPC must have at least one subnet in at least 2 AZ
## Supported Engines
- MySQL
- Postgres
- MariaDB
- Oracle
- SQL Server
- Aurora (AWS MySQL)
## Db Instance
- Should be accessed by DNS (CNAME)
### Parameter Group
Database Engine configuration (cotainer)
You can change parameters of all instances at once by modifying the Parameter Group
### Option Group
Some DB engines offer additional features that make it easier to manage data and databases, and to provide additional security for your database. Amazon RDS uses option groups to enable and configure these features. An option group can specify features, called options, that are available for a particular Amazon RDS DB instance
### Subnet Group
A DB Subnet Group is a collection of subnets that you may want to designate for your RDS DB Instances in a VPC. Each DB Subnet Group should have at least one subnet for every Availability Zone in a given Region. When creating a DB Instance in VPC, you will need to select a DB Subnet Group
## Multi AZ Deployment
- All Databse engines support Mulit-AZ (licence for Enterprise for SQL)
- Synchronous replication between two AZ
- Primary/StandBy mode
- no performance gains
- Snapshots taken from StandBy
- Less time needed for updates during maintenance window
- Use DNS name, automatic flip when primary fails
- Higher latency than Single AZ deployment
- Single AZ can be converted to Multi AZ
## Read Replica
- Supported engines:
- MySQL
- Aurora
- PostgesSQL
- MariaDB
- Asynchronous read only replica
- Can allow creating custom indexes (MySQL only)
- Automatic Backup has to ENABLED to create Read Replica
- You can create Read Replica from Read Replica for Aurora, MySQL and MariaDB
## Maintenance Window
- 30 minutes
- Automatic backups are taken within the window
## Importing Data
- Database Migration Service
## Encryption
- Can only be enabled when DB Instance is created
- You can encrypt db by using Snapshot, copying it and restoring
- Unencrypted Snapshot can't be restored to encrypted db
- Encryption can't be disabled
- Read Replicas encrypted with same key as Source Instance
- When coping encrypted snapshot to different region you have to specify KMS key. KMS keys are regional.
## Security
- Amazon RDS uses VPC security groups only for DB instances launched by recently created AWS accounts. In simple terms, DB security groups only apply to instances used outside of a VPC, which could not apply to any recently created AWS accounts. Let's disqualify that as a security group option. The EC2 security group also applies to only EC2-Classic instances, so let's rule out that option as well. EC2 instances are not available to AWS accounts created in the last several years.
- All engines support SSL connections
|
Rust
|
UTF-8
| 7,426 | 2.84375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use super::util::{
table_is_array, table_is_timestamp, table_to_array, table_to_map, table_to_timestamp,
timestamp_to_table,
};
use crate::event::Value;
use rlua::prelude::*;
impl<'a> ToLua<'a> for Value {
fn to_lua(self, ctx: LuaContext<'a>) -> LuaResult<LuaValue> {
match self {
Value::Bytes(b) => ctx.create_string(b.as_ref()).map(LuaValue::String),
Value::Integer(i) => Ok(LuaValue::Integer(i)),
Value::Float(f) => Ok(LuaValue::Number(f)),
Value::Boolean(b) => Ok(LuaValue::Boolean(b)),
Value::Timestamp(t) => timestamp_to_table(ctx, t).map(LuaValue::Table),
Value::Map(m) => ctx
.create_table_from(m.into_iter().map(|(k, v)| (k, v)))
.map(LuaValue::Table),
Value::Array(a) => ctx.create_sequence_from(a.into_iter()).map(LuaValue::Table),
Value::Null => ctx.create_string("").map(LuaValue::String),
}
}
}
impl<'a> FromLua<'a> for Value {
fn from_lua(value: LuaValue<'a>, _: LuaContext<'a>) -> LuaResult<Self> {
match value {
LuaValue::String(s) => Ok(Value::Bytes(s.as_bytes().into())),
LuaValue::Integer(i) => Ok(Value::Integer(i)),
LuaValue::Number(f) => Ok(Value::Float(f)),
LuaValue::Boolean(b) => Ok(Value::Boolean(b)),
LuaValue::Table(t) => {
if table_is_array(&t)? {
table_to_array(t).map(Value::Array)
} else if table_is_timestamp(&t)? {
table_to_timestamp(t).map(Value::Timestamp)
} else {
table_to_map(t).map(Value::Map)
}
}
other => Err(rlua::Error::FromLuaConversionError {
from: other.type_name(),
to: "Value",
message: Some("Unsupported Lua type".to_string()),
}),
}
}
}
#[cfg(test)]
mod test {
use super::*;
use chrono::{TimeZone, Utc};
#[test]
fn from_lua() {
let pairs = vec![
("'⍺βγ'", Value::Bytes("⍺βγ".into())),
("123", Value::Integer(123)),
("3.14159265359", Value::Float(3.14159265359)),
("true", Value::Boolean(true)),
(
"{ x = 1, y = '2', nested = { other = 2.718281828 } }",
Value::Map(
vec![
("x".into(), 1.into()),
("y".into(), "2".into()),
(
"nested".into(),
Value::Map(
vec![("other".into(), 2.718281828.into())]
.into_iter()
.collect(),
),
),
]
.into_iter()
.collect(),
),
),
(
"{1, '2', 0.57721566}",
Value::Array(vec![1.into(), "2".into(), 0.57721566.into()]),
),
(
"os.date('!*t', 1584297428)",
Value::Timestamp(Utc.ymd(2020, 3, 15).and_hms(18, 37, 8)),
),
(
"{year=2020, month=3, day=15, hour=18, min=37, sec=8}",
Value::Timestamp(Utc.ymd(2020, 3, 15).and_hms(18, 37, 8)),
),
(
"{year=2020, month=3, day=15, hour=18, min=37, sec=8, nanosec=666666666}",
Value::Timestamp(Utc.ymd(2020, 3, 15).and_hms_nano(18, 37, 8, 666666666)),
),
];
Lua::new().context(move |ctx| {
for (expression, expected) in pairs.into_iter() {
let value: Value = ctx.load(expression).eval().unwrap();
assert_eq!(value, expected, "expression: {:?}", expression);
}
});
}
#[test]
fn to_lua() {
let pairs = vec![
(
Value::Bytes("⍺βγ".into()),
r#"
function (value)
return value == '⍺βγ'
end
"#,
),
(
Value::Integer(123),
r#"
function (value)
return value == 123
end
"#,
),
(
Value::Float(3.14159265359),
r#"
function (value)
return value == 3.14159265359
end
"#,
),
(
Value::Null,
r#"
function (value)
return value == ''
end
"#,
),
(
Value::Map(
vec![
("x".into(), 1.into()),
("y".into(), "2".into()),
(
"nested".into(),
Value::Map(
vec![("other".into(), 2.718281828.into())]
.into_iter()
.collect(),
),
),
]
.into_iter()
.collect(),
),
r#"
function (value)
return value.x == 1 and
value['y'] == '2' and
value.nested.other == 2.718281828
end
"#,
),
(
Value::Array(vec![1.into(), "2".into(), 0.57721566.into()]),
r#"
function (value)
return value[1] == 1 and
value[2] == '2' and
value[3] == 0.57721566
end
"#,
),
(
Value::Timestamp(Utc.ymd(2020, 3, 15).and_hms_nano(18, 37, 8, 666666666)),
r#"
function (value)
local expected = os.date("!*t", 1584297428)
expected.nanosec = 666666666
return os.time(value) == os.time(expected) and
value.nanosec == expected.nanosec and
value.yday == expected.yday and
value.wday == expected.wday and
value.isdst == expected.isdst
end
"#,
),
];
Lua::new().context(move |ctx| {
for (value, test_src) in pairs.into_iter() {
let test_fn: LuaFunction = ctx.load(test_src).eval().unwrap_or_else(|_| {
panic!("failed to load {} for value {:?}", test_src, value)
});
assert!(
test_fn
.call::<_, bool>(value.clone())
.unwrap_or_else(|_| panic!(
"failed to call {} for value {:?}",
test_src, value
)),
"test function: {}, value: {:?}",
test_src,
value
);
}
});
}
}
|
Markdown
|
UTF-8
| 683 | 2.578125 | 3 |
[] |
no_license
|
# Styled vs Scss

styled-component
* props에 의해 [변화](https://velog.io/@qksud14/portfolio-05)가 통제
scss
* BEM, OOCSS, ITCSS 등 방법론
#### **정리**
[https://www.reddit.com/r/reactjs/comments/my6dnw/styled\_components\_vs\_sass\_sheets/](https://www.reddit.com/r/reactjs/comments/my6dnw/styled_components_vs_sass_sheets/gvvt95i?utm_source=share&utm_medium=web2x&context=3)
#### **참고**
* [https://velog.io/@qksud14/portfolio-05](https://velog.io/@qksud14/portfolio-05)
* [https://blueshw.github.io/2020/09/14/why-css-in-css/](https://blueshw.github.io/2020/09/14/why-css-in-css/)
|
Python
|
UTF-8
| 492 | 3.578125 | 4 |
[] |
no_license
|
companies = {}
while True:
command = input()
if 'End' in command:
break
company, employee = command.split(' -> ')
if company not in companies:
companies[company] = []
if employee not in companies[company]:
companies[company].append(employee)
ordered_companies = dict(sorted(companies.items(), key=lambda x: x[0]))
for curr_company in ordered_companies:
print(curr_company)
[print(f'-- {comp}') for comp in ordered_companies[curr_company]]
|
Java
|
UTF-8
| 4,182 | 1.976563 | 2 |
[] |
no_license
|
package me.osm.tools.translator.rest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Calendar;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import me.osm.tools.translator.ESNodeHodel;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.json.JSONObject;
import org.restexpress.Request;
import org.restexpress.Response;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ExportREST {
@SuppressWarnings("unchecked")
public void read(Request request, Response response) throws Exception {
Client client = ESNodeHodel.getClient();
SearchRequestBuilder search = client.prepareSearch("translator").setTypes("location");
search.setQuery(QueryBuilders.filteredQuery(
QueryBuilders.matchAllQuery(), FilterBuilders.termFilter("updated", true)));
search.addSort("osmid", SortOrder.ASC);
SearchResponse result = search.execute().actionGet();
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("osmChange");
doc.appendChild(rootElement);
rootElement.setAttribute("version", "0.1");
rootElement.setAttribute("generator", "translator.osm.me");
Element modify = doc.createElement("modify");
rootElement.appendChild(modify);
for(SearchHit hit : result.getHits().getHits()) {
JSONObject hitJSON = new JSONObject(hit.getSource());
JSONObject tags = hitJSON.getJSONObject("tags");
JSONObject names = hitJSON.getJSONObject("names");
for(String key : (Set<String>)names.keySet()) {
tags.put(key, names.optString(key));
}
String osmID = hitJSON.getString("osmid");
Element osmElemement = null;
if(osmID.charAt(0) == 'n') {
osmElemement = doc.createElement("node");
}
if(osmID.charAt(0) == 'w') {
osmElemement = doc.createElement("way");
}
if(osmID.charAt(0) == 'r') {
osmElemement = doc.createElement("relation");
}
osmElemement.setAttribute("id", osmID.substring(1));
String timestamp = currentTimestampString();
osmElemement.setAttribute("timestamp", timestamp);
modify.appendChild(osmElemement);
for(String key : (Set<String>)tags.keySet()) {
String value = StringUtils.stripToNull(tags.optString(key));
if(value != null) {
Element tag = doc.createElement("tag");
tag.setAttribute("k", key);
tag.setAttribute("v", value);
osmElemement.appendChild(tag);
}
}
}
response.setContentType("text/xml; charset=utf8");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream baStream = new ByteArrayOutputStream();
StreamResult outStrem = new StreamResult(baStream);
transformer.transform(source, outStrem);
response.setBody(new String(baStream.toByteArray(), "utf-8"));
}
private String currentTimestampString() {
// 1) create a java calendar instance
Calendar calendar = Calendar.getInstance();
// 2) get a java.util.Date from the calendar instance.
// this date will represent the current instant, or "now".
java.util.Date now = calendar.getTime();
// 3) a java current time (now) instance
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
String timestamp = currentTimestamp.toString();
return timestamp;
}
}
|
Java
|
UTF-8
| 5,605 | 2 | 2 |
[] |
no_license
|
package br.com.sicredi.backendtest.service;
import br.com.sicredi.backendtest.entity.Discussion;
import br.com.sicredi.backendtest.entity.Session;
import br.com.sicredi.backendtest.entity.Summary;
import br.com.sicredi.backendtest.exception.ConflictException;
import br.com.sicredi.backendtest.exception.ExpectationException;
import br.com.sicredi.backendtest.repository.SessionRepository;
import br.com.sicredi.backendtest.service.fixture.DiscussionFixture;
import br.com.sicredi.backendtest.service.fixture.SessionFixture;
import br.com.sicredi.backendtest.service.fixture.SummaryFixture;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
class SessionServiceTest {
@Mock
private SessionRepository sessionRepository;
@Mock
private DiscussionService discussionService;
@Mock
private SummaryService summaryService;
@InjectMocks
private SessionService sessionService;
@Test
public void shouldSuccessWhenCreateSession() {
Session session = SessionFixture.getSession();
Discussion discussion = DiscussionFixture.getDiscussion();
given(sessionRepository.save(session)).willReturn(Mono.just(session));
given(sessionRepository.findByDiscussionId(discussion.getId())).willReturn(Mono.empty());
given(discussionService.findById(discussion.getId())).willReturn(Mono.just(discussion));
Mono<Session> sessionSaved = sessionService.createSession(discussion.getId(), session);
verify(sessionRepository, times(1)).save(session);
StepVerifier
.create(sessionSaved)
.assertNext(value -> {
assertEquals(session.getId(), value.getId());
assertEquals(session.getDiscussionId(), value.getDiscussionId());
assertEquals(session.getTimer(), value.getTimer());
assertEquals(session.getOpen(), value.getOpen());
assertEquals(session.getCpfCreator(), value.getCpfCreator());
assertNotNull(value.getCreated());
assertNotNull(value.getClosed());
})
.expectComplete()
.verify();
}
@Test
public void shouldErrorWhenDiscussionNotFound() {
Session session = SessionFixture.getSession();
Discussion discussion = DiscussionFixture.getDiscussion();
given(sessionRepository.save(session)).willReturn(Mono.just(session));
given(discussionService.findById(discussion.getId())).willReturn(Mono.empty());
Mono<Session> sessionSaved = sessionService.createSession(discussion.getId(), session);
StepVerifier
.create(sessionSaved)
.expectErrorMatches(throwable ->
throwable instanceof ExpectationException
&& throwable.getMessage().equals("A pauta de discussão informada não foi encontrada.")
)
.verify();
}
@Test
public void shouldErrorWhenHasASession4Discussion() {
Session session = SessionFixture.getSession();
Discussion discussion = DiscussionFixture.getDiscussion();
given(sessionRepository.save(session)).willReturn(Mono.just(session));
given(sessionRepository.findByDiscussionId(discussion.getId())).willReturn(Mono.just(session));
given(discussionService.findById(discussion.getId())).willReturn(Mono.just(discussion));
Mono<Session> sessionSaved = sessionService.createSession(discussion.getId(), session);
StepVerifier
.create(sessionSaved)
.expectErrorMatches(throwable ->
throwable instanceof ConflictException
&& throwable.getMessage().equals("Já existe uma sessão criada para pauta de discussão.")
)
.verify();
}
@Test
public void shouldSuccessWhenCloseSessions() {
Session session = SessionFixture.getExpiredession();
Summary summary = SummaryFixture.getSummary();
given(sessionRepository.findByOpen(Boolean.TRUE)).willReturn(Flux.just(session));
given(sessionRepository.save(session)).willReturn(Mono.just(session));
given(summaryService.createSummary(any())).willReturn(Mono.empty());
Flux<Session> sessionsClosed = sessionService.closeSessions();
StepVerifier
.create(sessionsClosed)
.expectNextCount(1)
.expectComplete()
.verify();
}
@Test
public void shouldSuccessWhenNoSessions2Close() {
Session session = SessionFixture.getCreatedSession();
given(sessionRepository.findByOpen(Boolean.TRUE)).willReturn(Flux.just(session));
Flux<Session> sessionsClosed = sessionService.closeSessions();
StepVerifier
.create(sessionsClosed)
.expectNextCount(0)
.expectComplete()
.verify();
}
}
|
Swift
|
UTF-8
| 1,914 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
//
// DLFlowLayoutCollectionNode.swift
// NodeExtension
//
// Created by Daniel Lin on 08/09/2017.
// Copyright (c) 2017 Daniel Lin. All rights reserved.
//
import AsyncDisplayKit
open class DLFlowLayoutCollectionNode: ASCollectionNode {
public var numberOfColumns = 2
public init(collectionViewFlowLayout: UICollectionViewFlowLayout) {
super.init(frame: .zero, collectionViewLayout: collectionViewFlowLayout, layoutFacilitator: nil)
self.delegate = self
self.backgroundColor = .clear
}
}
// MARK: - ASCollectionDelegateFlowLayout
extension DLFlowLayoutCollectionNode: ASCollectionDelegateFlowLayout {
open func collectionNode(_ collectionNode: ASCollectionNode, didSelectItemAt indexPath: IndexPath) {
}
public func collectionNode(_ collectionNode: ASCollectionNode, constrainedSizeForItemAt indexPath: IndexPath) -> ASSizeRange {
let flowLayout = collectionNode.collectionViewLayout as! UICollectionViewFlowLayout
let columns = CGFloat(numberOfColumns)
if flowLayout.scrollDirection == .vertical {
let spacing = flowLayout.sectionInset.left + flowLayout.sectionInset.right + flowLayout.minimumInteritemSpacing * (columns - 1)
let width = ((collectionNode.view.bounds.size.width - spacing) / columns).rounded(.down)
return ASSizeRangeMake(CGSize(width: width, height: 0), CGSize(width: width, height: CGFloat.greatestFiniteMagnitude))
} else {
let spacing = flowLayout.sectionInset.top + flowLayout.sectionInset.bottom + flowLayout.minimumInteritemSpacing * (columns - 1)
let height = ((collectionNode.view.bounds.size.height - spacing) / columns).rounded(.down)
return ASSizeRangeMake(CGSize(width: 0, height: height), CGSize(width: CGFloat.greatestFiniteMagnitude, height: height))
}
}
}
|
C
|
UTF-8
| 7,420 | 2.671875 | 3 |
[] |
no_license
|
#include "token.h"
#include "dynstring.h"
#include "dynarray.h"
#include "hash.h"
#include "stream.h"
#include "log.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char ch;
int token;
struct TkWord *tk_hashtable[MAXKEY];
struct DynArray tktable;
struct DynString tkstr;
struct TkWord *tkword_direct_insert(struct TkWord *tp) {
int keyno;
dynArray_add(&tktable, tp);
keyno = elf_hash(tp->spelling);
tp->next = tk_hashtable[keyno];
tk_hashtable[keyno] = tp;
return tp;
}
struct TkWord *tkword_find(char *spelling, int keyno) {
struct TkWord *itr = NULL;
for (itr = tk_hashtable[keyno]; itr; itr = itr->next){
if (strcmp(spelling, itr->spelling) == 0) {
return itr;
}
}
return NULL;
}
struct TkWord *tkword_insert(char *p) {
struct TkWord *tp;
int keyno;
int length;
keyno = elf_hash(p);
tp = tkword_find(p, keyno);
if (!tp) {
length = strlen(p);
tp = calloc(1, sizeof(struct TkWord) + length + 1);
tp->next = tk_hashtable[keyno];
tk_hashtable[keyno] = tp;
dynArray_add(&tktable, tp);
tp->tkcode = tktable.count - 1;
tp->spelling = ((char*)tp) + sizeof(struct TkWord);
strncpy(tp->spelling, p, length);
}
return tp;
}
void init_lex()
{
struct TkWord *tp;
static struct TkWord keywords[] = {
{ TOK_PLUS, NULL, "+", NULL, NULL},
{ TOK_MINUS, NULL, "-", NULL, NULL },
{ TOK_MULTI, NULL, "*", NULL, NULL },
{ TOK_DIV, NULL, "/", NULL, NULL },
{ TOK_MOD, NULL, "%", NULL, NULL },
{ TOK_EQ, NULL, "==", NULL, NULL },
{ TOK_NEQ, NULL, "!=", NULL, NULL },
{ TOK_LT, NULL, "<", NULL, NULL },
{ TOK_LEQ, NULL, "<=", NULL, NULL },
{ TOK_GT, NULL, ">", NULL, NULL },
{ TOK_GEQ, NULL, ">=", NULL, NULL },
{ TOK_ASSIGN, NULL, "=", NULL, NULL },
{ TOK_POINTSTO, NULL, "->", NULL, NULL },
{ TOK_DOT, NULL, ".", NULL, NULL },
{ TOK_AND, NULL, "&", NULL, NULL },
{ TOK_OR, NULL, "|", NULL, NULL },
{ TOK_CROSS_OR, NULL, "||", NULL, NULL },
{ TOK_OPENPA, NULL, "(", NULL, NULL },
{ TOK_CLOSEPA,NULL, ")", NULL, NULL },
{ TOK_OPENBR, NULL, "[", NULL, NULL },
{ TOK_CLOSEBR,NULL, "]", NULL, NULL },
{ TOK_BEGIN, NULL, "{", NULL, NULL },
{ TOK_END, NULL, "}", NULL, NULL },
{ TOK_SEMICOLON, NULL, ";", NULL, NULL },
{ TOK_COMMA, NULL, ",", NULL, NULL },
{ TOK_ELLIPSIS, NULL, "...", NULL, NULL },
{ TOK_EOF, NULL, "End_Of_File", NULL, NULL },
{ TK_CINT, NULL, "ConstInteger", NULL, NULL },
{ TK_CCHAR, NULL, "ConstChar", NULL, NULL },
{ TK_CSTR, NULL, "ConstString", NULL, NULL },
{ KW_CHAR, NULL, "char", NULL, NULL },
{ KW_SHORT, NULL, "short", NULL, NULL },
{ KW_INT, NULL, "int", NULL, NULL },
{ KW_VOID, NULL, "void", NULL, NULL },
{ KW_STRUCT, NULL, "struct", NULL, NULL },
{ KW_IF, NULL, "if", NULL, NULL },
{ KW_ELSE, NULL, "else", NULL, NULL },
{ KW_FOR, NULL, "for", NULL, NULL },
{ KW_CONTINUE,NULL, "continue", NULL, NULL },
{ KW_BREAK, NULL, "break", NULL, NULL },
{ KW_RETURN, NULL, "return", NULL, NULL },
{ KW_SIZEOF, NULL, "sizeof", NULL, NULL },
{ KW_ALIGN, NULL, "__align", NULL, NULL },
{ KW_CDECL, NULL, "__cdecl", NULL, NULL },
{ KW_STDCALL, NULL, "__stdcall", NULL, NULL },
{NULL, NULL, NULL, NULL, NULL}
};
dynString_init(&tkstr, 8);
dynArray_init(&tktable, 8);
for (tp = keywords; tp->spelling != NULL; ++tp)
tkword_direct_insert(tp);
}
void preprocess() {
while (1)
{
while (isspace(ch)){
getch();
}
if (ch != '/') { break; }
getch();
if (ch == '/') {
while (ch != '\n'){
getch();
}
} else if (ch == '*') {
getch();
while (1) {
if (ch == '*') {
getch();
if (ch == '/') {
getch();
break;
}
else {
continue;
}
}
getch();
}
} else {
ungetch();
ch = '/';
break;
}
}
}
void parse_identifier() {
dynString_reset(&tkstr);
while (isalnum(ch) || ch == '_') {
dynString_cat(&tkstr, ch);
getch();
}
tkstr.data[tkstr.count] = '\0';
}
void parse_number() {
dynString_reset(&tkstr);
while (ch >= '0' && ch <= '9')
{
dynString_cat(&tkstr, ch);
getch();
}
tkstr.data[tkstr.count] = '\0';
}
void parse_string(char sep) {
dynString_reset(&tkstr);
dynString_cat(&tkstr, sep);
for (;;) {
getch();
if (ch == sep)
break;
dynString_cat(&tkstr, ch);
}
dynString_cat(&tkstr, sep);
dynString_cat(&tkstr, '\0');
getch();
}
void get_token()
{
preprocess();
switch (ch)
{
case 'a':case 'b':case 'c':case 'd':case 'e':case 'f':case 'g':case 'h':case 'i':case 'j':case 'k':
case 'l':case 'm':case 'n':case 'o':case 'p':case 'q':case 'r':case 's':case 't':case 'u':case 'v':
case 'w':case 'x':case 'y':case 'z':case 'A':case 'B':case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K':
case 'L':case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V':
case 'W':case 'X': case 'Y': case 'Z':case '_':
{
struct TkWord *tp;
parse_identifier();
tp = tkword_insert(tkstr.data);
token = tp->tkcode;
break;
}
case '0':case '1':case '2':case '3':case '4':case '5':case '6':case '7':case '8':case '9':
{
parse_number();
token = TK_CINT;
break;
}
case '+':
{
getch();
token = TOK_PLUS;
break;
}
case '-':
{
getch();
if (ch == '>') {
getch();
token = TOK_POINTSTO;
} else {
token = TOK_MINUS;
}
break;
}
case '*':
{
getch();
token = TOK_MULTI;
break;
}
case '/':
{
getch();
token = TOK_DIV;
break;
}
case '%':
{
getch();
token = TOK_MOD;
break;
}
case '=':
{
getch();
if (ch == '=') {
getch();
token = TOK_EQ;
} else {
token = TOK_ASSIGN;
}
break;
}
case '!':
{
getch();
if (ch == '=') {
getch();
token == TOK_NEQ;
} else {
error("! not support now\n");
}
break;
}
case '<':
{
getch();
if (ch == '=') {
getch();
token = TOK_LEQ;
} else {
token = TOK_LT;
}
break;
}
case '>':
{
getch();
if (ch == '=') {
getch();
token = TOK_GEQ;
} else {
token = TOK_GT;
}
break;
}
case '.':
{
getch();
if (ch == '.')
{
getch();
if (ch == '.') {
token = TOK_ELLIPSIS;
} else {
error("...");
}
getch();
} else {
token = TOK_DOT;
}
}
case '&':
{
getch();
token = TOK_AND;
break;
}
case '|':
{
getch();
if (ch == '|') {
token = TOK_CROSS_OR;
getch();
} else {
token = TOK_OR;
}
break;
}
case ';':
{
getch();
token = TOK_SEMICOLON;
break;
}
case ']':
{
getch();
token = TOK_CLOSEBR;
break;
}
case '[':
{
getch();
token = TOK_OPENBR;
break;
}
case ')':
{
getch();
token = TOK_CLOSEPA;
break;
}
case '(':
{
getch();
token = TOK_OPENPA;
break;
}
case '{':
{
getch();
token = TOK_BEGIN;
break;
}
case '}':
{
getch();
token = TOK_END;
break;
}
case ',':
{
getch();
token = TOK_COMMA;
break;
}
case '\'':
{
parse_string(ch);
token = TK_CCHAR;
break;
}
case '\"':
{
parse_string(ch);
token = TK_CSTR;
break;
}
case TOK_EOF:
{
token = TOK_EOF;
break;
}
default:
{
getch();
error("unknow character");
}
}
}
|
Java
|
UTF-8
| 495 | 3.375 | 3 |
[] |
no_license
|
public class ConvertSortedArraytoBinarySearchTree {
public TreeNode sortedArrayToBST(int[] nums) {
return buildTree(nums, 0, nums.length-1);
}
private TreeNode buildTree(int[] nums, int start, int end) {
if(start > end) return null;
if(start == end) return new TreeNode(nums[start]);
int mid = start + (end - start) / 2;
TreeNode ret = new TreeNode(nums[mid]);
ret.left = buildTree(nums, start, mid-1);
ret.right = buildTree(nums, mid+1, end);
return ret;
}
}
|
Python
|
UTF-8
| 4,120 | 2.625 | 3 |
[] |
no_license
|
import Distance
import config
from RPi import GPIO
import time
import signal
import sys
config.init()
GPIO.setup(config.left_motor_pwm, GPIO.OUT)
GPIO.setup(config.left_motor_direction, GPIO.OUT)
GPIO.setup(config.left_motor_direction_inv, GPIO.OUT)
GPIO.setup(config.right_motor_pwm, GPIO.OUT)
GPIO.setup(config.right_motor_direction, GPIO.OUT)
GPIO.setup(config.right_motor_direction_inv, GPIO.OUT)
config.drive_left = GPIO.PWM(config.left_motor_pwm, 100)
config.drive_right = GPIO.PWM(config.right_motor_pwm, 100)
GPIO.setup(config.ultrasonic_triggers[config.US_LEFT], GPIO.OUT)
GPIO.setup(config.ultrasonic_triggers[config.US_CENTER], GPIO.OUT)
GPIO.setup(config.ultrasonic_triggers[config.US_RIGHT], GPIO.OUT)
GPIO.setup(config.ultrasonic_pins[config.US_LEFT], GPIO.IN)
GPIO.setup(config.ultrasonic_pins[config.US_CENTER], GPIO.IN)
GPIO.setup(config.ultrasonic_pins[config.US_RIGHT], GPIO.IN)
GPIO.output(config.left_motor_direction, GPIO.HIGH)
GPIO.output(config.left_motor_direction_inv, GPIO.LOW)
GPIO.output(config.right_motor_direction, GPIO.HIGH)
GPIO.output(config.right_motor_direction_inv, GPIO.LOW)
def end_read(signal, frame):
print("\nCtrl+C captured, ending read.")
config.drive_left.stop()
config.drive_right.stop()
GPIO.cleanup()
sys.exit()
def loop():
dist_mid = Distance.measure_distance(config.ultrasonic_triggers[config.US_CENTER], debug=False)
dist_left = Distance.measure_distance(config.ultrasonic_triggers[config.US_LEFT], debug=False)
dist_right = Distance.measure_distance(config.ultrasonic_triggers[config.US_RIGHT], debug=False)
if (dist_mid < 7 and dist_right > dist_left):
config.drive_left.ChangeDutyCycle(0)
config.drive_right.ChangeDutyCycle(0)
GPIO.output(config.left_motor_direction, GPIO.HIGH)
GPIO.output(config.left_motor_direction_inv, GPIO.LOW)
GPIO.output(config.right_motor_direction, GPIO.LOW)
GPIO.output(config.right_motor_direction_inv, GPIO.HIGH)
config.drive_left.ChangeDutyCycle(78)
config.drive_right.ChangeDutyCycle(78)
time.sleep(0.705) # time needed to turn 90° right
config.drive_left.ChangeDutyCycle(0)
config.drive_right.ChangeDutyCycle(0)
GPIO.output(config.left_motor_direction, GPIO.HIGH)
GPIO.output(config.left_motor_direction_inv, GPIO.LOW)
GPIO.output(config.right_motor_direction, GPIO.HIGH)
GPIO.output(config.right_motor_direction_inv, GPIO.LOW)
elif (dist_mid < 7 and dist_left > dist_right):
config.drive_left.ChangeDutyCycle(0)
config.drive_right.ChangeDutyCycle(0)
GPIO.output(config.left_motor_direction, GPIO.LOW)
GPIO.output(config.left_motor_direction_inv, GPIO.HIGH)
GPIO.output(config.right_motor_direction, GPIO.HIGH)
GPIO.output(config.right_motor_direction_inv, GPIO.LOW)
config.drive_left.ChangeDutyCycle(80)
config.drive_right.ChangeDutyCycle(80)
time.sleep(0.7) # time needed to turn 90° left
config.drive_left.ChangeDutyCycle(0)
config.drive_right.ChangeDutyCycle(0)
GPIO.output(config.left_motor_direction, GPIO.HIGH)
GPIO.output(config.left_motor_direction_inv, GPIO.LOW)
GPIO.output(config.right_motor_direction, GPIO.HIGH)
GPIO.output(config.right_motor_direction_inv, GPIO.LOW)
elif (dist_left < 7):
config.drive_left.ChangeDutyCycle(config.max_left_speed + 20)
config.drive_right.ChangeDutyCycle(config.max_right_speed)
elif (dist_right < 7):
config.drive_left.ChangeDutyCycle(config.max_left_speed)
config.drive_right.ChangeDutyCycle(config.max_right_speed + 20)
else:
config.drive_left.ChangeDutyCycle(config.max_left_speed)
config.drive_right.ChangeDutyCycle(config.max_right_speed)
# * * * * * * * * * * * * * * * * * * * * * * * * * *
# Main program
# * * * * * * * * * * * * * * * * * * * * * * * * * *
signal.signal(signal.SIGINT, end_read)
config.drive_left.start(config.walk_speed_left)
config.drive_right.start(config.walk_speed_right)
while True:
loop()
|
Java
|
UTF-8
| 923 | 2.0625 | 2 |
[] |
no_license
|
package com.example.table;
public class Recipe {
private String Rno;
private String Rdate;
private String Mno;
private String Mname;
private String Pno;
private String Dno;
private String Moperator;
public String getRno() {
return Rno;
}
public void setRno(String rno) {
Rno = rno;
}
public String getRdate() {
return Rdate;
}
public void setRdate(String rdate) {
Rdate = rdate;
}
public String getMno() {
return Mno;
}
public void setMno(String mno) {
Mno = mno;
}
public String getMname() {
return Mname;
}
public void setMname(String mname) {
Mname = mname;
}
public String getPno() {
return Pno;
}
public void setPno(String pno) {
Pno = pno;
}
public String getDno() {
return Dno;
}
public void setDno(String dno) {
Dno = dno;
}
public String getMoperator() {
return Moperator;
}
public void setMoperator(String moperator) {
Moperator = moperator;
}
}
|
Python
|
UTF-8
| 1,034 | 3.234375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'sunjiyun'
from collections import defaultdict, OrderedDict
mydefaultDict = defaultdict(lambda: 'sunjiyun')
mydefaultDict["age"] = 31
mydefaultDict["name"] = "sunjiyun2"
print mydefaultDict['age']
print mydefaultDict['name']
print mydefaultDict.keys()
d = dict([("a", 1), ("b", 2), ("c", 3)])
print d
orderDict = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
print orderDict
orderDict["a"] =4
print orderDict
orderDict["z"] = "z1"
orderDict["y"] = "y1"
orderDict["x"] = "x1"
print orderDict
print "OrderedDict的Key会按照插入的顺序排列,不是Key本身排序:"
class LastUpdatedOrderedDict(OrderedDict):
def __init__(self,capacity):
super(LastUpdatedOrderedDict, self).__init__()
self.capacity = capacity
def __setitem__(self, key, value):
containsKey = 1 if key in self else 0
if len(self) - containsKey > self.capacity:
last = self.popitem(last=False)
if containsKey:
del self[key]
|
Markdown
|
UTF-8
| 4,414 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
# Requirements
Aside from a CSV of document identifiers and their OCR'd text, you will need to have the latest versions of Go and Python 3 installed. As well as the python packages for `sqlite3` and `zlib`.
# Running a Signature Method
## Preparations
Given an input CSV file, run the `splitcsv` tool to split it into multiple text documents ready for featurization. Note that this tool will create output files in your *working directory* so be sure that it's the right place for the (perhaps many) source text documents.
## Featurizing documents
For each input text file `input.txt` run `mkgrams 4 <input.txt >output.features` to generate the features for that file.
## Preprocessing hashes + generating random vectors.
For the `minhash`, `topsig`, and `topsig-weighted` methods, a central database containing the hashes, pre-generated random-vectors, global feature counts, and runtimes must be created. To do so,
- Concatenate all the feature files from all of your input features into one global features file `global.features`.
- Run the `features2db.sh` script -- `features2db.sh global.features global.db` to generate a SQLite3 database `global.db` containing the central database.
## Methods
### `minhash`, `topsig`, `topsig-weighted`
These commands take in the central database along with the desired output hash size in bits. They expect the featurized document on standard input. These commands produce on standard output one line formatted as shown:
```<count of features in document> <hash value in base 10> <number of bits set in binary representation of hash> <elapsed time in nanoseconds>```.
To use:
```./<command> path-to-central-database.db hash-bits < input-feature-file.txt > output.txt```.
### `simhash`
`simhash` expects as command line arguments both the path to a file containing a newline-seperated list of featurized documents to process and the number of desired hash bits in the output.
To use:
```./simhash list-of-files.txt hash-bits > concatenated-outputs.txt```.
`simhash` produces output similar to `minhash`, `topsig`, and `topsig-weighted`, except it generates one file with multiple lines, one for each document in `list-of-files.txt`, instead of one file with one line for each document.
## Collecting Statistics
### Pairwise similarity
We have provided a tool `pairwise` to analyze the pairwise similarity of hashes generated by the above signature methods.
To use: ```./pairwise list-of-files.txt d start-offset end-offset```
- `list-of-files.txt` -- list of output hash files produced by the `minhash`, `topsig`, `topsig-weighted`, and `simhash` methods.
- `d` -- Maximum Hamming distance to print similarity statistics for.
- `start-offset` -- Index of first hash to print statistics for. Usually `0`, but can be otherwise if you plan to split the computation of pairwise similarity over multiple `pairwise` invocations.
- `end-offset` -- Index immediately _after_ the last hash to print statistics for. Use `-1` to compute statistics for every hash after and including the hash at `start-offset`.
`pairwise` produces on standard output one line for every hash processed. On that line, it prints the following:
```<hash> <#hashes at distance at most 0> <#hashes at distance at most 0> ... <#hashes at distance at most d>```.
# Getting EDGAR documents
To begin retrieving EDGAR documents, you must first download a particular year's file lists using the SEC's public web frontend.
```bash
!/bin/bash
year=2005
for quarter in 1 2 3 4
do
base="https://www.sec.gov/Archives/edgar/Oldloads/${year}/QTR${quarter}/"
curl $base | egrep -o '[0-9]+\.gz' > files
sed -e "s_^_${base}_" files >> all.files
done
```
For each line in `all.files`, you can download the archive containing documents for a particular day in that quarter.
```bash
#!/bin/bash
for line in $(cat ${all.files})
do
echo $line
wget -P edgar-data $line
sleep 15s # To play nicely with SEC servers
done
```
The resulting files are approximately XML files (with some added cruft), so you will likely need to do some custom parsing. For our purposes, we rendered only the HTML documents into PDF using `wkhtmltopdf` and then running those resulting documents through our internal OCR engine to replicate the user experience. We note that PDFs are present in the XML files and are Uuencoded. The Golang library `uuencode` by `sanylcs` is what we have found to work best.
|
Python
|
UTF-8
| 441 | 3.65625 | 4 |
[] |
no_license
|
#!/usr/bin/python
import sys
OPEN_BRACKET = '('
CLOSED_BRACKET = ')'
def calculate(brackets):
floor = 0
for bracket in brackets:
if bracket == OPEN_BRACKET:
floor += 1
elif bracket == CLOSED_BRACKET:
floor -= 1
return floor
if __name__ == '__main__':
with open(sys.argv[1], 'r') as f:
brackets = f.read().strip("\n")
print brackets
print calculate(brackets)
|
Markdown
|
UTF-8
| 1,189 | 2.609375 | 3 |
[] |
no_license
|
# django-meeting-room-book
Following the Pluralsight https://app.pluralsight.com/library/courses/django-getting-started/table-of-contents
The Github link for course material: https://github.com/codesensei-courses/django_getting_started
## instllation instructions
pip install -r requirements.txt
## Setups
```
django-admin startproject <project name>
python manage.py startapp <new app name>
```
## Run
Run server
```
python manage.py runserver
```
## Auth
Create super user
```
python manage.py createsuperuser
```
## Database
### Migrations workflow
1. Make sure your app is in `INSTALLED_APPS` in `settings.py`
2. Change model code
3. Generate migration script.
```
python manage.py makemigrations
```
4. Check the migration script generated by django
5. (Optional) Check pending migrations
```
python manage.py showmigrations
```
6. (Optional) Get SQL statement for migration
```
python manage.py sqlmigrate <app> <migration number>
```
7. Apply migration
```
python manage.py migrate
```
8. (Optional) Connect to Data base using shell
```
python manage.py dbshell
```
## Format
```
black .
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.