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
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 610 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# ES6 함수의 추가 기능
## 1. 함수의 구분
- arguments는 사용하지 않는 것이 좋다. Rest 파라미터로 사용할 수 있기 때문이다.
## 3. 화살표 함수
- **함수를 만들 때 일반 함수로 만들 것이면 의도적을 화살표 함수를 사용해라.**
- **콜백 함수 사용 시 무조건 화살표 함수 사용해라.**
- 클래스 필드는 constructor{this.name=name;} 처럼 형태를 바꿔서 생각해보면 쉽다.
## 4. Rest 파라미터
- Rest 파라미터는 매개변수 자리에 오고 Spread 연산자는 그 밖에 있다. 정반대로 동작한다.
|
TypeScript
|
UTF-8
| 4,157 | 2.828125 | 3 |
[] |
no_license
|
import { api } from "./api-lib"
import { KultunautDetailedEvent, KultunautEvent } from "./types"
const fieldsList = (page: number) => '&page=' + page + '&fieldlist=Title,Startdate,Enddate,Tags,Image,LocationName,Link,Ticket,LocationAddress,LocationCity,LocationZip,Starttime,Time'
const location = (lat: string, lon: string, radius: number) => 'lat=' + lat + '&lon=' + lon + '&radius=' + radius
const FEED_DEFAULT_LENGTH = 100
/**
* Show event data for a single event
* @param {string} id KultunautEventId
*/
export async function getById(id: string): Promise<KultunautDetailedEvent> {
const params = 'EventId?Id=' + id
return (await api(params))[0] || undefined
}
/**
* Show events data for a list of event id's
* @param {string[]} ids List of KultunautEventIds
*/
export async function getByIds(ids: string[]): Promise<KultunautDetailedEvent[]> {
const params = 'EventId?Id=' + ids.reduce((acc, item) => acc + "," + item)
return await api(params)
}
type ListByLocationParams = {
lat: string
lon: string
viewed: number[]
}
/**
* Search events by longitude and latitude, order by distance, startdate:
*
* The lenght is dynamic, either it is shorter than 2 x FEED_DEFAULT_LENGTH
*
* @param {string} lat Latitude
* @param {string} lon Longitude
* @param {number[]} viewed KultunautEventId list of the already viewed items
*/
export async function listByLocation({ lat, lon, viewed }: ListByLocationParams): Promise<KultunautEvent[]> {
var list: KultunautEvent[] = []
var page = 1
var radius = 1000
while (list.length < FEED_DEFAULT_LENGTH) {
const params = 'EventLonLatDist?' + location(lat, lon, radius) + '&pagesize=' + FEED_DEFAULT_LENGTH + fieldsList(page)
const result: KultunautEvent[] = await api(params)
if (!result || result.length !== FEED_DEFAULT_LENGTH) {
list = []
page = 0
radius = radius + 1000
} else {
const filtered = result.filter(({ Id }) => !viewed.includes(Id))
list = [...list, ...filtered]
page = page + 1
}
}
return list
}
const LIST_MAX_SIZE = 100
type SearchParams = {
lat: string
lon: string
radius: number
enddate?: string
startdate?: string
categories?: string[]
}
/**
* Search events by longitude, latitude, radius, start- and end-date. Order by startdate. Get a list of up to 100 items.
*
* @param {string} lat latitude
* @param {string} lon longitude
* @param {number} radius theradius
* @param {string=} enddate how events starting before date, format: dd-mm-yyyy, default current day + 180 days (OPTIONAL)
* @param {string=} startdate show events ending after date, format: dd-mm-yyyy, default current day (OPTIONAL)
* @param {(string[])=} categories show events only having one or more of these categories (OPTIONAL)
*/
export async function search({ lat, lon, radius, enddate, startdate, categories }: SearchParams): Promise<KultunautEvent[]> {
// Build global params
var params = 'EventLonLatDate?' + location(lat, lon, radius)
if (enddate) params += '&enddate=' + enddate
if (startdate) params += '&startdate=' + startdate
var list: KultunautEvent[] = []
var page = 0
while (list.length < LIST_MAX_SIZE) {
// Build local params
const localParams = params + '&pagesize=' + LIST_MAX_SIZE + fieldsList(page)
const result: KultunautEvent[] = await api(localParams)
const filteredList = result.reduce((acc: KultunautEvent[], item: KultunautEvent) => {
//Some result might have malformed Tags
if (!item.Tags) return acc
var predicate = true
//Check if the event has one or more of the tags we are searching (if we are searching)
if (categories && categories.length > 0) predicate = ((item.Tags.filter((tag) => categories.includes(tag))).length > 0)
if (predicate) return [...acc, item]
else return acc
}, [])
list = [...list, ...filteredList]
if (result.length !== LIST_MAX_SIZE) break;
else page++
}
return list
}
|
C
|
UTF-8
| 800 | 2.75 | 3 |
[] |
no_license
|
#ifndef MATRIX_MATRIXOPTIONS_H
#define MATRIX_MATRIXOPTIONS_H
enum MatrixOptions {
DefaultOptions = 0, // horizontal serpentine layout. first pixel is bottom-left
MatrixHorizontal = 0b0000, // stripe is left to right
MatrixVertical = 0b0001, // stripe is top down
MatrixSerpentine = 0b0000, // rows/cols change direction
MatrixStraight = 0b0010, // all rows/cols follow same direction
MatrixInvertVertical = 0b0100, // first pixel is top instead of bottom
MatrixInvertHorizontal = 0b1000, // first pixel is right instead of left
MatrixRotate_0 = 0b00000000,
MatrixRotate_90 = 0b00010000,
MatrixRotate_180 = 0b00100000,
MatrixRotate_270 = 0b01000000,
};
#endif //MATRIX_MATRIXOPTIONS_H
|
Python
|
UTF-8
| 6,321 | 2.84375 | 3 |
[] |
no_license
|
import filecmp
import os
import unittest
from datetime import datetime
from unittest import TestCase
from rfwtools.feature_set import FeatureSet
import pandas as pd
import numpy as np
import math
import test
def make_dummy_df(n, standard=True):
"""Generates a dummy DataFrame with id as only metadtata column. Optionally use standard (zone, etc.).
Value of columns is not same as real data.
"""
if standard:
df = pd.DataFrame({'zone': pd.Categorical(['1L22'] * n),
"dtime": [datetime(year=2020, month=3, day=13)] * n,
'cavity_label': pd.Categorical(["1"] * n),
'fault_label': pd.Categorical(["Microphonics"] * n),
'cavity_conf': [math.nan] * n,
'fault_conf': [math.nan] * n,
'label_source': ["test_source"] * n,
'id': [x for x in range(n)],
"x1": [x for x in range(n)],
'x2': [1] * n,
'x3': [2] * n,
'x4': [3] * n
})
else:
df = pd.DataFrame({'id': [x for x in range(n)],
"x1": [x for x in range(n)],
'x2': [1] * n,
'x3': [2] * n,
'x4': [3] * n
})
return df
class TestFeatureSet(TestCase):
def test_construction(self):
# Test a few basic constructions.
df = make_dummy_df(3, standard=False)
# Check that the missing metadata columns throws
with self.assertRaises(ValueError):
FeatureSet(df=df)
# Construct a more standard looking one.
df = make_dummy_df(3)
# Check that we can supply custom metadata_columns values
FeatureSet(df=df, metadata_columns=['id'])
# Test that standard construction works
FeatureSet(df)
FeatureSet(df, name="testing!")
def test_do_pca_reduction(self):
# Test with a _very_ simple case
# Create a dummy DataFrame with only one column having variation - should have only on non-zero PC
df = make_dummy_df(3)
fs = FeatureSet(df=df, metadata_columns=['id'])
meta_df = fs.get_example_df()[['zone', 'dtime', 'cavity_label', 'fault_label', 'cavity_conf', 'fault_conf',
'example', 'label_source', 'id']]
# Defaults to three components. Test the no standardization option
fs.do_pca_reduction(standardize=False, report=False)
exp = pd.DataFrame({"id": [0, 1, 2], "pc1": [1., 0., -1.], "pc2": [0., 0., 0.], "pc3": [0., 0., 0.]})
exp = meta_df.merge(exp, on='id')
self.assertTrue((exp.equals(fs.get_pca_df())), f"exp = \n{exp}\npca_df = \n{fs.get_pca_df()}")
# Check that this works with standardization
fs.do_pca_reduction(standardize=True, report=False)
exp = pd.DataFrame({"id": [0, 1, 2], "pc1": [1.224744871391589, 0., -1.224744871391589], "pc2": [0., 0., 0.],
"pc3": [0., 0., 0.]})
exp = meta_df.merge(exp, on='id')
self.assertTrue((exp.equals(fs.get_pca_df())), f"exp = \n{exp}\npca_df = \n{fs.get_pca_df()}")
# Check that the explained variance is what we expect (all on one PC)
self.assertTrue((np.array([1., 0., 0.]) == fs.pca.explained_variance_ratio_).all())
def test_eq(self):
# Test our equality operator
# Make some Feature Sets
df = make_dummy_df(4, standard=True)
# Identical
fs1 = FeatureSet(df=df, metadata_columns=['id'])
fs1_same = FeatureSet(df=df, metadata_columns=['id'])
# Different metadata_columns
fs2 = FeatureSet(df=df, metadata_columns=['id', 'x2'])
# Different value for x2
df["x2"] = 17
fs3 = FeatureSet(df=df, metadata_columns=['id'])
# Check the not equal cases
self.assertNotEqual(fs1, None)
self.assertNotEqual(fs1, fs2)
self.assertNotEqual(fs1, fs3)
# Check the equal cases
self.assertEqual(fs1, fs1)
self.assertEqual(fs1, fs1_same)
def test_load_save_csv(self):
# Test that we can load and save CSV files.
fs = FeatureSet()
csv_file = "test-feature_set.csv"
tsv_file = "test-feature_set.tsv"
# Load the TSV file and save it to a tmp dir. Make sure the files match, and that at least one field matches
fs.load_csv(tsv_file, in_dir=test.test_data_dir, sep='\t')
fs.save_csv(tsv_file, out_dir=test.tmp_data_dir, sep='\t')
self.assertTrue(filecmp.cmp(os.path.join(test.test_data_dir, tsv_file),
os.path.join(test.tmp_data_dir, tsv_file)), "TSV files did not match.")
self.assertEqual(fs.get_example_df().loc[0, 'cavity_label'], "5")
self.assertEqual(fs.get_example_df().loc[0, 'f1'], 6)
# Clean up the tmp TSV file
os.unlink(os.path.join(test.tmp_data_dir, tsv_file))
# Do the same test with CSV file/separator
fs.load_csv(csv_file, in_dir=test.test_data_dir)
fs.save_csv(csv_file, out_dir=test.tmp_data_dir)
self.assertTrue(filecmp.cmp(os.path.join(test.test_data_dir, csv_file),
os.path.join(test.tmp_data_dir, csv_file)), "CSV files did not match.")
self.assertEqual(fs.get_example_df().loc[0, 'fault_label'], "Microphonics")
self.assertEqual(fs.get_example_df().loc[2, 'f3'], 3)
# Clean up the tmp CSV file
os.unlink(os.path.join(test.tmp_data_dir, csv_file))
def test_update_example_set(self):
tsv_file = "test-feature_set.tsv"
fs = FeatureSet()
fs.load_csv(tsv_file, in_dir=test.test_data_dir, sep='\t')
# Add one column and include all of the "mandatory" columns in there. They should still only show up once.
m_cols = fs.metadata_columns + ['junk']
df = fs.get_example_df()
df['junk'] = ['junker'] * len(df)
fs.update_example_set(df, metadata_columns=m_cols)
self.assertListEqual(fs.metadata_columns, m_cols)
if __name__ == '__main__':
unittest.main()
|
Python
|
UTF-8
| 3,713 | 2.84375 | 3 |
[] |
no_license
|
import json
import nltk
from collections import Counter
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import jaccard_similarity_score
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
import string
# Simplified question
def getPOS(corpus):
pos_tag = []
for sentence in corpus:
text = nltk.word_tokenize(sentence)
words = nltk.pos_tag(text)
for word in words:
pos_tag.append(word)
#less_words = [wt for (wt, tag) in words if tag not in ["CC","DT","EX","IN","LS","POS","TO",".","\\",",",":","(",")"]]
#return less_words
return pos_tag
def countWordsInParagraph(context):
wordList = nltk.word_tokenize(context)
counts = Counter(wordList)
return counts
def createCorpus(stopwords, filename):
file = open(filename)
j = json.load(file)
corpus = []
data_length = len(j[u'data']) #442
for data in range(data_length):
paragraph_length = len(j[u'data'][data][u'paragraphs']) #66
for paragraph in range(paragraph_length):
context = nltk.word_tokenize(j[u'data'][data][u'paragraphs'][paragraph][u'context'].lower())
corpus.append(" ".join([w for w in context if not w in stopwords]))
question_length = len(j[u'data'][data][u'paragraphs'][paragraph][u'qas'])
for q in range(question_length):
question = nltk.word_tokenize(j[u'data'][data][u'paragraphs'][paragraph][u'qas'][q]["question"].lower())
corpus.append(" ".join([w for w in question if not w in stopwords]))
file.close()
return corpus
def ourLemmatize(dictonary, corpus):
lemma = WordNetLemmatizer()
corp = []
for sentence in corpus:
s = nltk.word_tokenize(sentence)
sent = []
for word in s:
if dictonary[word] != None:
nw = lemma.lemmatize(word, dictonary[word])
sent.append(nw)
else:
sent.append(word)
corp.append(" ".join(sent))
return corp
def main():
stop_words = set(stopwords.words('english'))
stop_words.union(set(string.punctuation))
question = ["who", "what", "when", "where", "why", "how", "which", "whose", "whom", "is", "was", "are", "does", "did", "were", "can", "do", "has", "had", "name"]
for w in question:
stop_words.remove(w)
corpus = createCorpus(stop_words, "training_sample.json")
#print (corpus)
#print ("=---=-------")
file = open("training_sample.json")
j = json.load(file)
predictions = {} #id:value
similarity = {}
pos = getPOS(corpus)
pos_dict = {}
for (word, tag) in pos:
wtag = tag[0].lower()
wtag = wtag if wtag in ["a","r","n","v"] else None
pos_dict[word] = wtag
corpus = ourLemmatize(pos_dict, corpus)
vectorizer = CountVectorizer()
vectors = vectorizer.fit_transform(corpus)
vectorsArrayForm = vectors.toarray()
counter = 0
data_length = len(j[u'data']) #442
for data in range(data_length):
paragraph_length = len(j[u'data'][data][u'paragraphs']) #66
for paragraph in range(paragraph_length):
context_vector = vectorsArrayForm[counter]
counter += 1
question_length = len(j[u'data'][data][u'paragraphs'][paragraph][u'qas'])
for q in range(question_length):
question_id = j[u'data'][data][u'paragraphs'][paragraph][u'qas'][q]["id"]
question_vector = vectorsArrayForm[counter]
similarity[question_id] = jaccard_similarity_score(context_vector, question_vector)
counter += 1
print(similarity)
main()
|
C++
|
UTF-8
| 1,300 | 2.578125 | 3 |
[] |
no_license
|
#pragma comment(linker, "/stack:252457298")
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
const long long Mod = 1000000007LL;
int n, k; vector<int> a;
vector<long long> Powers;
void CalculatePowers() {
if (k == 1) {Powers.push_back(1); return;}
if (k == -1) {Powers.push_back(-1); Powers.push_back(1); return;}
long long Mul = 1;
while (abs(Mul) <= 1e15) {
Powers.push_back(Mul);
Mul *= k;
}
}
void Input() {
cin >> n >> k; a.resize(n);
for (auto &x: a) cin >> x;
}
void Solve() {
CalculatePowers();
map<long long, int> Prefixcnt;
long long sum = 0; Prefixcnt[0]++;
long long ans = 0;
for (auto val: a) {
sum += val;
for (auto demanding: Powers) {
long long neededPrefix = sum - demanding;
if (Prefixcnt.find(neededPrefix) == Prefixcnt.end()) continue;
ans += Prefixcnt[neededPrefix];
}
Prefixcnt[sum]++;
}
cout << ans << endl;
}
int main(int argc, char* argv[]) {
ios_base::sync_with_stdio(0); cin.tie(NULL);
Input(); Solve(); return 0;
}
/**********************************************\
* Ngoc-Mai Ngo, #Team4T's Deputy Leader *
* #Team4T Secondary Flagship - Destruction *
\**********************************************/
|
C++
|
UTF-8
| 555 | 3.0625 | 3 |
[] |
no_license
|
#include<iostream>
#include<malloc.h>
using namespace std;
int main(){
int n;
cout<<"Enter the number of numbers that you want to enter: "<<endl;
cin >>n;
int *a=(int*)malloc(sizeof(int)*n);
for(int i=0;i<n;i++){
cin>> a[i];
}
for(int i=0;i<n-1;i++){
int min=a[i];
int minpos=i;
for(int j=i+1;j<n;j++){
if(a[j]<min){
min=a[j];
minpos=j;
}
}
a[minpos]=a[i];
a[i]=min;
}
for(int i=0;i<n;i++){
cout<< a[i];
}
}
|
Python
|
UTF-8
| 1,249 | 2.796875 | 3 |
[] |
no_license
|
from transformers import Trainer
from transformers import BertTokenizerFast
from transformers import BertForSequenceClassification
import numpy as np
import pandas as pd
class FineTunedBertModule:
category_array = ["buildings", "infrastructure ", "other", "resilience"]
def __init__(self):
self.model = BertForSequenceClassification.from_pretrained("fineTunedBert")
self.tokenizer = BertTokenizerFast.from_pretrained("bert-base-uncased")
def tokenize_sentence(self, sentence):
return self.tokenizer(sentence, padding="max_length", truncation=True, return_tensors="pt")
def get_predictions(self, sentences):
preds = []
for x in range(0, len(sentences)):
tokenized_sentence = self.tokenize_sentence(sentences[x])
logits = self.model(**tokenized_sentence).logits
numerical_prediction = np.argmax(logits.detach().numpy(), axis = -1)
preds.append(numerical_prediction[0])
preds = list(map(lambda x: self.category_array[x], preds))
sentences_with_preds = {"sentence": sentences, "label": preds}
df = pd.DataFrame.from_dict(sentences_with_preds)
return df
|
PHP
|
UTF-8
| 2,026 | 2.75 | 3 |
[] |
no_license
|
<?php
/**
* Template Name: Donation Forms & Goals
*
* This snippet is a page template with an example query that gets
* the 10 latest donation forms and displays their goal
*
* IMPORTANT: This snippet, unlike others you might find in our snippet library
* does not go in functions.php or a must-use plugin. Paste the entire contents
* of this file to a new file named archive-give_forms.php and place it in
* the root of your active theme's folder. To view it on your site, naviate to
* /donations (assuming you haven't changed the slug or disabled the form archives
* in Donations --> Settings --> Display )
*
*/
get_header();
?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
/**
* Display Donation Forms
*/
$args = array(
'post_type' => 'give_forms',
'posts_per_page' => 10
);
$wp_query = new WP_Query( $args );
if ( $wp_query->have_posts() ) : ?>
<h2>Choose a Donation</h2>
<hr/>
<?php
while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<div class="<?php post_class(); ?>">
<h2 class="give-form-title"><?php echo get_the_title(); ?></h2>
<?php //you can output the content or excerpt here ?>
<?php
if ( class_exists( 'Give' ) ) {
//Output the goal (if enabled)
$id = get_the_ID();
$goal_option = give_get_meta( $id, '_give_goal_option', true );
if ( give_is_setting_enabled( $goal_option ) ) {
echo do_shortcode( '[give_goal id="' . $id . '"]' );
}
}
?>
<a href="<?php echo get_permalink(); ?>" class="button readmore give-donation-form-link"><?php _e( 'Donate Now', 'give' ); ?> »</a>
</div>
<?php endwhile;
wp_reset_postdata(); // end of Query 1 ?>
<?php else :
//If you don't have donation forms that fit this query
?>
<h2>Sorry, no donations found.</h2>
<?php endif;
wp_reset_query(); ?>
</main>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
Java
|
UTF-8
| 22,748 | 1.609375 | 2 |
[] |
no_license
|
package com.zxtech.mt.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.zxtech.mt.adapter.MtAdapter;
import com.zxtech.mt.adapter.MtFinishAdapter;
import com.zxtech.mt.adapter.MyPagerAdapter;
import com.zxtech.mt.common.Constants;
import com.zxtech.mt.entity.MtWorkPlan;
import com.zxtech.mt.utils.DateUtil;
import com.zxtech.mt.utils.HttpCallBack;
import com.zxtech.mt.utils.HttpUtil;
import com.zxtech.mt.utils.SPUtils;
import com.zxtech.mt.utils.ToastUtil;
import com.zxtech.mt.utils.Util;
import com.zxtech.mt.widget.SimpleDialog;
import com.zxtech.mtos.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import cn.bingoogolapple.refreshlayout.BGARefreshViewHolder;
/**
* 维保
* Created by Chw on 2016/6/22.
*/
@Route(path = "/mt/mt")
public class MtActivity extends BaseActivity {
private ViewPager main_viewpager;
private List<View> pagerViews = new ArrayList<>();
private ListView unfinish_listview;
private ListView finish_listview;
private ListView today_listview;
private ListView week_listview;
private List<ListView> listViews = new ArrayList<>();
private BGARefreshLayout mRefreshLayout1, mRefreshLayout2, mRefreshLayout3 ,mRefreshLayout4;
private List<BGARefreshLayout> refreshLayouts = new ArrayList<>();
private TextView title1_textview, title2_textview, title3_textview, title4_textview;
private List<MtWorkPlan> unfinish_list;
private List<MtWorkPlan> finish_list;
private List<MtWorkPlan> today_list;
private List<MtWorkPlan> week_list;
private MtAdapter todayAdapter;
private MtAdapter weekAdapter;
private MtFinishAdapter finishAdapter;
private MtAdapter unFinishAdapter;
private int unfinish_page = 1, today_page = 1, week_page = 1, finish_page = 1;
private LinearLayout top_title_layout;
private static final int TODAY_REQUEST_CODE = 1001;
private static final int WEEK_REQUEST_CODE = 1002;
private static final int UNFINISH_REQUEST_CODE = 1003;
@Override
protected void onCreate() {
View view = mInfalter.inflate(R.layout.activity_maintenance, null);
main_layout.addView(view);
//开启定位服务
// setBackHide();
title_textview.setText(getString(R.string.maintenance));
menu2.setTextColor(getResources().getColor(R.color.bg_blue));
menu2_bg.setText("\ue73a");
menu2_bg.setTextColor(mContext.getResources().getColor(R.color.c_theme));
}
@Override
protected void initView() {
initTodayList();
initWeekList();
initUnfinishList();
initFinishList();
mRefreshLayout1.beginRefreshing();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void initData() {
}
@Override
protected void findView() {
main_viewpager = findViewById(R.id.main_viewpager);
top_title_layout = findViewById(R.id.top_title_layout);
title1_textview = findViewById(R.id.title1_textview);
title2_textview = findViewById(R.id.title2_textview);
title3_textview = findViewById(R.id.title3_textview);
title4_textview = findViewById(R.id.title4_textview);
View pager1 = mInfalter.inflate(R.layout.viewpager_1, null);
View pager2 = mInfalter.inflate(R.layout.viewpager_1, null);
View pager3 = mInfalter.inflate(R.layout.viewpager_1, null);
View pager4 = mInfalter.inflate(R.layout.viewpager_1, null);
today_listview = pager1.findViewById(R.id.listView);
week_listview = pager2.findViewById(R.id.listView);
unfinish_listview = pager3.findViewById(R.id.listView);
finish_listview = pager4.findViewById(R.id.listView);
listViews.add(today_listview);
listViews.add(week_listview);
listViews.add(unfinish_listview);
listViews.add(finish_listview);
BGARefreshViewHolder refreshViewHolder = new BGANormalRefreshViewHolder(this, false);
mRefreshLayout1 = pager1.findViewById(R.id.rl_refresh);
mRefreshLayout1.setRefreshViewHolder(refreshViewHolder);
mRefreshLayout1.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate(){
@Override
public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
today_page = 1;
Map<String, String> param = new HashMap<>();
param.put("search_type", "1");
param.put("emp_id", SPUtils.get(mContext, "emp_id", "").toString());
param.put("page", String.valueOf(today_page));
HttpUtil.getInstance(mContext).request("/mtmo/getmtplanlist.mo", param, new HttpCallBack<List<MtWorkPlan>>() {
@Override
public void onSuccess(List<MtWorkPlan> list) {
if (list != null) {
today_list.clear();
today_list.addAll(list);
}
todayAdapter.notifyDataSetChanged();
mRefreshLayout1.endRefreshing();
}
@Override
public void onFail(String msg) {
mRefreshLayout1.endRefreshing();
}
});
}
@Override
public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
today_page++;
Map<String, String> param = new HashMap<>();
param.put("search_type", "1");
param.put("emp_id", SPUtils.get(mContext, "emp_id", "").toString());
param.put("page", String.valueOf(today_page));
HttpUtil.getInstance(mContext).request("/mtmo/getmtplanlist.mo", param, new HttpCallBack<List<MtWorkPlan>>() {
@Override
public void onSuccess(List<MtWorkPlan> list) {
if (list != null) {
today_list.addAll(Util.removeDistinct(today_list, list));
}
todayAdapter.notifyDataSetChanged();
mRefreshLayout1.endLoadingMore();
}
@Override
public void onFail(String msg) {
mRefreshLayout1.endLoadingMore();
}
});
return false;
}
});
BGARefreshViewHolder refreshViewHolder2 = new BGANormalRefreshViewHolder(this, false);
mRefreshLayout2 = pager2.findViewById(R.id.rl_refresh);
mRefreshLayout2.setRefreshViewHolder(refreshViewHolder2);
mRefreshLayout2.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate(){
@Override
public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
week_page = 1;
Map<String, String> param = new HashMap<>();
param.put("search_type", "2");
param.put("emp_id", SPUtils.get(mContext,"emp_id","").toString());
param.put("page",String.valueOf(week_page));
HttpUtil.getInstance(mContext).request("/mtmo/getmtplanlist.mo", param, new HttpCallBack<List<MtWorkPlan>>() {
@Override
public void onSuccess(List<MtWorkPlan> list) {
if (list != null) {
week_list.clear();
week_list.addAll(list);
}
weekAdapter.notifyDataSetChanged();
mRefreshLayout2.endRefreshing();
}
@Override
public void onFail(String msg) {
mRefreshLayout2.endRefreshing();
}
});
}
@Override
public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
week_page++;
Map<String, String> param = new HashMap<>();
param.put("search_type", "2");
param.put("emp_id", SPUtils.get(mContext, "emp_id", "").toString());
param.put("page", String.valueOf(week_page));
HttpUtil.getInstance(mContext).request("/mtmo/getmtplanlist.mo", param, new HttpCallBack<List<MtWorkPlan>>() {
@Override
public void onSuccess(List<MtWorkPlan> list) {
if (list != null) {
week_list.addAll(Util.removeDistinct(week_list, list));
}
weekAdapter.notifyDataSetChanged();
mRefreshLayout2.endLoadingMore();
}
@Override
public void onFail(String msg) {
mRefreshLayout2.endLoadingMore();
}
});
return true;
}
});
BGARefreshViewHolder refreshViewHolder3 = new BGANormalRefreshViewHolder(this, false);
mRefreshLayout3 = pager3.findViewById(R.id.rl_refresh);
mRefreshLayout3.setRefreshViewHolder(refreshViewHolder3);
mRefreshLayout3.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate(){
@Override
public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
finish_page = 1;
Map<String, String> param = new HashMap<>();
param.put("search_type", "4");
param.put("emp_id", SPUtils.get(mContext, "emp_id", "").toString());
param.put("page", String.valueOf(finish_page));
HttpUtil.getInstance(mContext).request("/mtmo/getmtplanlist.mo", param, new HttpCallBack<List<MtWorkPlan>>() {
@Override
public void onSuccess(List<MtWorkPlan> list) {
if (list != null) {
finish_list.clear();
finish_list.addAll(list);
}
finishAdapter.notifyDataSetChanged();
mRefreshLayout3.endRefreshing();
}
@Override
public void onFail(String msg) {
mRefreshLayout3.endRefreshing();
}
});
}
@Override
public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
finish_page++;
Map<String, String> param = new HashMap<>();
param.put("search_type", "4");
param.put("emp_id", SPUtils.get(mContext, "emp_id", "").toString());
param.put("page", String.valueOf(finish_page));
HttpUtil.getInstance(mContext).request("/mtmo/getmtplanlist.mo", param, new HttpCallBack<List<MtWorkPlan>>() {
@Override
public void onSuccess(List<MtWorkPlan> list) {
if (list != null) {
finish_list.addAll(Util.removeDistinct(finish_list, list));
}
finishAdapter.notifyDataSetChanged();
mRefreshLayout3.endLoadingMore();
}
@Override
public void onFail(String msg) {
mRefreshLayout3.endLoadingMore();
}
});
return true;
}
});
BGARefreshViewHolder refreshViewHolder4 = new BGANormalRefreshViewHolder(this, false);
mRefreshLayout4 = pager4.findViewById(R.id.rl_refresh);
mRefreshLayout4.setRefreshViewHolder(refreshViewHolder4);
mRefreshLayout4.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate(){
@Override
public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
unfinish_page = 1;
Map<String, String> param = new HashMap<>();
param.put("search_type", "3");
param.put("emp_id", SPUtils.get(mContext, "emp_id", "").toString());
param.put("page", String.valueOf(unfinish_page));
HttpUtil.getInstance(mContext).request("/mtmo/getmtplanlist.mo", param, new HttpCallBack<List<MtWorkPlan>>() {
@Override
public void onSuccess(List<MtWorkPlan> list) {
if (list != null) {
unfinish_list.clear();
unfinish_list.addAll(list);
}
unFinishAdapter.notifyDataSetChanged();
mRefreshLayout4.endRefreshing();
}
@Override
public void onFail(String msg) {
mRefreshLayout4.endRefreshing();
}
});
}
@Override
public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
unfinish_page++;
Map<String, String> param = new HashMap<>();
param.put("search_type", "3");
param.put("emp_id", SPUtils.get(mContext, "emp_id", "328CD4E29E52423C8F58F51885709678").toString());
param.put("page", String.valueOf(unfinish_page));
HttpUtil.getInstance(mContext).request("/mtmo/getmtplanlist.mo", param, new HttpCallBack<List<MtWorkPlan>>() {
@Override
public void onSuccess(List<MtWorkPlan> list) {
if (list != null) {
unfinish_list.addAll(Util.removeDistinct(unfinish_list, list));
}
unFinishAdapter.notifyDataSetChanged();
mRefreshLayout4.endLoadingMore();
}
@Override
public void onFail(String msg) {
mRefreshLayout4.endLoadingMore();
}
});
return true;
}
});
refreshLayouts.add(mRefreshLayout1);
refreshLayouts.add(mRefreshLayout2);
refreshLayouts.add(mRefreshLayout3);
refreshLayouts.add(mRefreshLayout4);
pagerViews.add(pager1);
pagerViews.add(pager2);
pagerViews.add(pager3);
pagerViews.add(pager4);
main_viewpager.setAdapter(new MyPagerAdapter(pagerViews));
main_viewpager.setCurrentItem(0);
main_viewpager.addOnPageChangeListener(new MyOnPageChangeListener());
unfinish_list = new ArrayList<>();
finish_list = new ArrayList<>();
today_list = new ArrayList<>();
week_list = new ArrayList<>();
}
@Override
protected void setListener() {
title1_textview.setOnClickListener(this);
title2_textview.setOnClickListener(this);
title3_textview.setOnClickListener(this);
title4_textview.setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
// PushManager.listTags(getApplicationContext());
}
public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
@Override
public void onPageSelected(int position) {
int count = top_title_layout.getChildCount();
for (int i = 0; i < count; i++) {
TextView textView = (TextView) top_title_layout.getChildAt(i);
if (position == 0 && i == 0) { //第一个被选中
textView.setBackgroundResource(R.drawable.solid_bule_border_left);
textView.setTextColor(getResources().getColor(R.color.white));
} else if (position == (count - 1) && (count - 1) == i) { //最后一个被选中
textView.setBackgroundResource(R.drawable.solid_bule_border_right);
textView.setTextColor(getResources().getColor(R.color.white));
} else if (i == 0) {//第一个未被选中
textView.setBackgroundResource(R.drawable.solid_white_border_left);
textView.setTextColor(getResources().getColor(R.color.grey));
} else if (i == count - 1) {
textView.setBackgroundResource(R.drawable.solid_white_border_right);
textView.setTextColor(getResources().getColor(R.color.grey));
} else if (i == position) {
textView.setBackgroundResource(R.drawable.solid_bule_border_center);
textView.setTextColor(getResources().getColor(R.color.white));
} else {
textView.setBackgroundResource(R.drawable.solid_white_border_center);
textView.setTextColor(getResources().getColor(R.color.grey));
}
}
refreshLayouts.get(position).beginRefreshing();
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
}
@Override
public void onClick(View v) {
super.onClick(v);
int i = v.getId();
if (i == R.id.title1_textview) {
main_viewpager.setCurrentItem(0);
} else if (i == R.id.title2_textview) {
main_viewpager.setCurrentItem(1);
} else if (i == R.id.title3_textview) {
main_viewpager.setCurrentItem(2);
} else if (i == R.id.title4_textview) {
main_viewpager.setCurrentItem(3);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TODAY_REQUEST_CODE:
today_list.clear();
mRefreshLayout1.beginRefreshing();
break;
case WEEK_REQUEST_CODE:
week_list.clear();
mRefreshLayout2.beginRefreshing();
break;
case UNFINISH_REQUEST_CODE:
unfinish_list.clear();
mRefreshLayout4.beginRefreshing();
break;
}
}
private void clickMtItem(MtWorkPlan mtWorkPlan, int requestCode) {
Intent it = new Intent(mContext, MtTaskActivity.class);
it.putExtra("bean", mtWorkPlan);
startActivityForResult(it, requestCode);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
}
private void initTodayList() {
todayAdapter = new MtAdapter(mContext, today_list, R.layout.item_name);
today_listview.setAdapter(todayAdapter);
today_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final MtWorkPlan mtWorkPlan = today_list.get(position);
clickMtItem(mtWorkPlan, TODAY_REQUEST_CODE);
}
});
}
private void initWeekList() {
weekAdapter = new MtAdapter(mContext, week_list, R.layout.item_name);
week_listview.setAdapter(weekAdapter);
week_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final MtWorkPlan mtWorkPlan = week_list.get(position);
//提示 是否确认提前进行保养?
String now = DateUtil.getCurrentDate();
if (mtWorkPlan.getPlan_date() != null && mtWorkPlan.getPlan_date().compareTo(now) > 0 && mtWorkPlan.getStatus().equals(Constants.MT_WORK_STATUS_WAIT)) {
dialog = SimpleDialog.createDialog(mContext, getString(R.string.hint), getString(R.string.msg_56), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
clickMtItem(mtWorkPlan, WEEK_REQUEST_CODE);
dialog.dismiss();
}
}, false);
dialog.show();
} else {
clickMtItem(mtWorkPlan, WEEK_REQUEST_CODE);
}
}
});
}
private void initUnfinishList() {
unFinishAdapter = new MtAdapter(mContext, unfinish_list, R.layout.item_name);
unfinish_listview.setAdapter(unFinishAdapter);
unfinish_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final MtWorkPlan mtWorkPlan = unfinish_list.get(position);
clickMtItem(mtWorkPlan, UNFINISH_REQUEST_CODE);
}
});
}
private void initFinishList() {
finishAdapter = new MtFinishAdapter(mContext, finish_list, R.layout.item_mt_finish);
finish_listview.setAdapter(finishAdapter);
finish_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MtWorkPlan mtWorkPlan = finish_list.get(position);
if (Constants.MT_WORK_STATUS_SUBMIT.equals(mtWorkPlan.getStatus())) {
ToastUtil.showLong(mContext, getString(R.string.wait_appraise_sign));
} else {
Intent it = new Intent(mContext, MtFeedbackActivity.class);
it.putExtra("data", mtWorkPlan);
startActivity(it);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
}
}
});
}
}
|
C#
|
UTF-8
| 893 | 2.625 | 3 |
[] |
no_license
|
using System;
namespace eStore.Shared.ViewModels.Printers
{
public class ReceiptDetails
{
public const string Employee = "Cashier: M0001 Name: Manager"; //TODO: implement to help
public string BillNo { get; private set; }// = "Bill NO: 67676767";
public string BillDate { get; private set; }// = " Date: ";
public string BillTime { get; private set; } //= " Time: ";
public string CustomerName { get; private set; }// = "Customer Name: ";
public ReceiptDetails(string invNo, DateTime onDate, string time, string custName)
{
BillNo = "Bill No: " + invNo;
BillDate = " Date: " + onDate.Date.ToShortDateString();
BillTime = " Time: " + time;
CustomerName = "Customer Name: " + custName;
}
}
}
|
Markdown
|
UTF-8
| 1,015 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
---
linktitle: Step 2. RStudio
menu:
setup:
parent: Setup
weight: 3
title: Download and install RStudio
type: book
weight: 3
---
Attendees will interact with the R programming language via the RStudio
development environment. The RStudio Desktop application is available
[here](https://rstudio.com/products/rstudio/download/#download). Follow the
instructions for your operating system.
## For Windows
1. Download the file "RStudio-_X_.exe" (where _X_ is the current version of
RStudio Desktop---at the time of writing, 2022.02.3-492).
2. Run the installer by double clicking on the downloaded file.
3. Install RStudio Desktop by accepting the default options in the installer.
## For macOS
1. Download the file "RStudio-_X_.dmg" (where _X_ is the current version of
RStudio Desktop---at the time of writing, 2022.02.3-492).
2. Mount the disk image by double clicking on the downloaded file.
3. Install RStudio Desktop by dragging the RStudio applications icon to the
"Applications" folder.
|
JavaScript
|
UTF-8
| 3,183 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
var widerScreenWidth = window.matchMedia("(max-width: 1024px)");
//For converting mousewheel scroll into horizontal scroll
var scrollicon = document.getElementById("scroll-arrow")
if (!widerScreenWidth.matches) {
main.addEventListener('wheel', (e) => {
main.scrollLeft += e.deltaY;
if(main.scrollLeft > 0){
scrollicon.style.visibility = "hidden";
}
if (main.scrollLeft >= window.innerWidth/1.125) { // Just an example
backbutton.style.visibility = 'visible';
navitems.style.visibility = 'visible';
aboutnav.children[1].style.visibility = 'visible'
} else {
navitems.style.visibility = 'hidden';
backbutton.style.visibility = 'hidden';
aboutnav.children[1].style.visibility = 'hidden'
processnav.children[1].style.visibility = 'hidden'
scholarnav.children[1].style.visibility = 'hidden'
furthernav.children[1].style.visibility = 'hidden'
}
if ((window.scrollX >= about.getBoundingClientRect().left-80) && (window.scrollX <= scholar.getBoundingClientRect().left-300)) {
resetNavbar()
aboutnav.children[0].style.color = 'black'
aboutnav.children[1].style.visibility = 'visible'
}else if ((window.scrollX >= scholar.getBoundingClientRect().left-80) && (window.scrollX <= scholar.getBoundingClientRect().right-500) ) {
resetNavbar()
scholarnav.children[0].style.color = 'white'
scholarnav.children[1].style.visibility = 'visible'
}
else if ((window.scrollX >= further.getBoundingClientRect().left-300) && (window.scrollX <= further.getBoundingClientRect().right-80 )) {
resetNavbar()
furthernav.children[0].style.color = 'black'
furthernav.children[1].style.visibility = 'visible'
}
else if((window.scrollX>=scholar.getBoundingClientRect().right) && process!= null ){
if((window.scrollX >= process.getBoundingClientRect().left-80) && (window.scrollX <= further.getBoundingClientRect().left))
{
resetNavbar()
processnav.children[0].style.color = 'red'
processnav.children[1].style.visibility = 'visible'
}
}
else{
resetNavbar()
}
});
}
document.addEventListener('DOMContentLoaded', function() {
const ele = document.getElementById('main');
let pos = { top: 0, left: 0, x: 0, y: 0 };
const mouseDownHandler = function(e) {
ele.style.cursor = 'grabbing';
ele.style.userSelect = 'none';
pos = {
left: ele.scrollLeft,
top: ele.scrollTop,
// Get the current mouse position
x: e.clientX,
y: e.clientY,
};
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
};
const mouseMoveHandler = function(e) {
// How far the mouse has been moved
const dx = e.clientX - pos.x;
const dy = e.clientY - pos.y;
// Scroll the element
ele.scrollTop = pos.top - dy;
ele.scrollLeft = pos.left - dx;
};
const mouseUpHandler = function() {
ele.style.cursor = 'default';
ele.style.removeProperty('user-select');
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
// Attach the handler
ele.addEventListener('mousedown', mouseDownHandler);
});
|
PHP
|
UTF-8
| 453 | 2.546875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
<?php
namespace app\myclasses;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
class MakeObject{
static function becomeArrayToObject($array){
//array_map((object), $array);
foreach($array as $key => $value){
$array[$key] = (object)$value;
}
return $array;
}
}
|
C#
|
UTF-8
| 2,349 | 2.8125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CSRToolWebApp.Models
{
public class BreadCrumbs
{
public List<BreadCrumb> Items { get; set; }
public BreadCrumbs()
{
this.Items = new List<BreadCrumb>();
}
public void Add(BreadCrumb breadCrumb)
{
this.Items.Add(breadCrumb);
}
public BreadCrumb Add(string text)
{
return Add(text, "", false);
}
public BreadCrumb Add(string text, string url)
{
return Add(text, url, false);
}
public BreadCrumb Add(string text, bool selected)
{
return Add(text, "", selected);
}
public BreadCrumb Add(string text, string url, bool selected)
{
BreadCrumb breadCrumb = new BreadCrumb(text, url, selected);
this.Items.Add(breadCrumb);
return breadCrumb;
}
}
public class BreadCrumb
{
public string Text { get; set; }
public string Url { get; set; }
public bool Selected { get; set; }
public string ShowMessageOnClick { get; set; }
public BreadCrumb(string text)
{
this.Text = text;
this.Selected = false;
}
public BreadCrumb(string text, string url)
{
this.Text = text;
this.Url = url;
this.Selected = false;
}
public BreadCrumb(string text, bool selected)
{
this.Text = text;
this.Selected = selected;
}
public BreadCrumb(string text, string url, bool selected)
{
this.Text = text;
this.Url = url;
this.Selected = selected;
}
public BreadCrumb(string text, string url, string showMessageOnClick)
{
this.Text = text;
this.Url = url;
this.Selected = false;
this.ShowMessageOnClick = showMessageOnClick;
}
public BreadCrumb(string text, string url, string showMessageOnClick, bool selected)
{
this.Text = text;
this.Url = url;
this.Selected = selected;
this.ShowMessageOnClick = showMessageOnClick;
}
}
}
|
Markdown
|
UTF-8
| 4,039 | 3.078125 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: 'Como: Criar um LineSegment em uma PathGeometry'
ms.date: 03/30/2017
dev_langs:
- csharp
- vb
helpviewer_keywords:
- line segments [WPF], creating
- graphics [WPF], line segments
ms.assetid: 0155ed47-a20d-49a7-a306-186d8e07fbc4
ms.openlocfilehash: a50c98ccc3f6d517e0917cb774af4d49d2bfa7a3
ms.sourcegitcommit: 9b552addadfb57fab0b9e7852ed4f1f1b8a42f8e
ms.translationtype: MT
ms.contentlocale: pt-BR
ms.lasthandoff: 04/23/2019
ms.locfileid: "62054543"
---
# <a name="how-to-create-a-linesegment-in-a-pathgeometry"></a>Como: Criar um LineSegment em uma PathGeometry
Este exemplo mostra como criar um segmento de linha. Para criar um segmento de linha, use o <xref:System.Windows.Media.PathGeometry>, <xref:System.Windows.Media.PathFigure>, e <xref:System.Windows.Media.LineSegment> classes.
## <a name="example"></a>Exemplo
Os exemplos a seguir desenham um <xref:System.Windows.Media.LineSegment> de (10, 50) para (200, 70). A ilustração a seguir mostra a resultante <xref:System.Windows.Media.LineSegment>; um plano de fundo de grade foi adicionado para mostrar o sistema de coordenadas.
 LineSegment um desenhada de (10,50) a (200,70)
[xaml]
No [!INCLUDE[TLA#tla_xaml](../../../../includes/tlasharptla-xaml-md.md)], você pode usar a sintaxe de atributo para descrever um caminho.
```xaml
<Path Stroke="Black" StrokeThickness="1"
Data="M 10,50 L 200,70" />
```
[xaml]
(Observe que essa sintaxe de atributo na verdade cria um <xref:System.Windows.Media.StreamGeometry>, uma versão leve de um <xref:System.Windows.Media.PathGeometry>. Para obter mais informações, consulte o [sintaxe de marcação de caminho](path-markup-syntax.md) página.)
No [!INCLUDE[TLA2#tla_xaml](../../../../includes/tla2sharptla-xaml-md.md)], você também pode desenhar um segmento de linha usando sintaxe de elemento de objeto. A seguir é equivalente ao anterior [!INCLUDE[TLA2#tla_xaml](../../../../includes/tla2sharptla-xaml-md.md)] exemplo.
```xaml
<Path Stroke="Black" StrokeThickness="1">
<Path.Data>
<PathGeometry>
<PathFigure StartPoint="10,50">
<LineSegment Point="200,70" />
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
```
```csharp
PathFigure myPathFigure = new PathFigure();
myPathFigure.StartPoint = new Point(10, 50);
LineSegment myLineSegment = new LineSegment();
myLineSegment.Point = new Point(200, 70);
PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
myPathSegmentCollection.Add(myLineSegment);
myPathFigure.Segments = myPathSegmentCollection;
PathFigureCollection myPathFigureCollection = new PathFigureCollection();
myPathFigureCollection.Add(myPathFigure);
PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures = myPathFigureCollection;
Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myPathGeometry;
```
```vb
Dim myPathFigure As New PathFigure()
myPathFigure.StartPoint = New Point(10, 50)
Dim myLineSegment As New LineSegment()
myLineSegment.Point = New Point(200, 70)
Dim myPathSegmentCollection As New PathSegmentCollection()
myPathSegmentCollection.Add(myLineSegment)
myPathFigure.Segments = myPathSegmentCollection
Dim myPathFigureCollection As New PathFigureCollection()
myPathFigureCollection.Add(myPathFigure)
Dim myPathGeometry As New PathGeometry()
myPathGeometry.Figures = myPathFigureCollection
Dim myPath As New Path()
myPath.Stroke = Brushes.Black
myPath.StrokeThickness = 1
myPath.Data = myPathGeometry
```
Este exemplo faz parte de um exemplo maior; para ver o exemplo completo, confira o [Exemplo de geometrias](https://go.microsoft.com/fwlink/?LinkID=159989).
## <a name="see-also"></a>Consulte também
- <xref:System.Windows.Media.PathFigure>
- <xref:System.Windows.Media.PathGeometry>
- <xref:System.Windows.Media.GeometryDrawing>
- <xref:System.Windows.Shapes.Path>
- [Visão geral de geometria](geometry-overview.md)
|
C++
|
UTF-8
| 7,492 | 3.125 | 3 |
[] |
no_license
|
// We need to include the declaration of our new rectangle class in order to use it.
#include "camera.h"
#include <iostream>
#include <iomanip>
#include <vector>
#include <random>
#include <chrono>
#include <thread>
int main()
{
int set_rows;
int set_columns;
int set_sampling_time;
int index = 0;
// welcome use
std::cout << "Welcome" << std::endl;
std::cout << "Please enter user parameters" << std::endl;
std::cout << "The program will determine the best configuration based on your inputs" << std::endl;
std::cout << "Press Enter to Continue" << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
system("clear"); // clear console
std::cout << "Please enter the number of rows required for the image size: " << std::endl;
while (!(std::cin >> set_rows) || set_rows < 0)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input, Try again: ";
}
std::cout << "Please enter the number of columns required for the image size: " << std::endl;
while (!(std::cin >> set_columns) || set_columns < 0)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input, Try again: ";
}
std::cout << "Please enter the sampling required: " << std::endl;
while (!(std::cin >> set_sampling_time) || set_sampling_time < 0)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input, Try again: ";
}
Camera *test = new Camera(set_rows, set_columns, set_sampling_time); // creation of testing object for user inputs
while (test->queryParameters() == false)
{
system("clear"); // clear console
std::cout << "Invalid Parameters. Please try again" << std::endl;
std::cin.clear();
std::cout << "Please enter the number of rows required for the image size: " << std::endl;
while (!(std::cin >> set_rows) || set_rows < 0)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input, Try again: ";
}
std::cout << "Please enter the number of columns required for the image size: " << std::endl;
while (!(std::cin >> set_columns) || set_columns < 0)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input, Try again: ";
}
std::cout << "Please enter the sampling required: " << std::endl;
while (!(std::cin >> set_sampling_time) || set_sampling_time < 0)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input, Try again: ";
}
// adjust new adjusted user parameters
test->setImageSize(set_rows, set_columns);
test->setSamplingTime(set_sampling_time);
}
if (test->queryParameters() == true)
{
system("clear"); // clear console
std::cout << "Based on Inputs the configuration is: " << std::endl;
test->getData();
std::cout << "Image Size (Rows x Columns):" << test->getImageSize() << "\n"
<< "Sampling time :" << test->getSamplingTime() << " miliseconds \n"
<< std::endl;
set_sampling_time = test->getSamplingTime();
set_columns = test->getColumnNumer();
set_rows = test->getRowNumber();
delete test;
}
auto start = std::chrono::system_clock::now();
Camera data(set_rows, set_columns, set_sampling_time); // creation valid object of object
while ((std::chrono::system_clock::now() - start) < std::chrono::seconds{5}) // while loop for time
{
Camera data(set_rows, set_columns, set_sampling_time); // creation valid object of object
index++;
data.setSampleNumber(index);
data.getData();
std::vector<std::vector<int>> output = data.printData();
std::cout << "Sample #" << data.getSampleNumber() << std::endl;
// print sensing range
for (int i = 0; i < output.size(); i++)
{
for (int j = 0; j < output.at(i).size(); j++)
{
std::cout << "[" << output.at(i).at(j) << "] ";
}
std::cout << std::endl;
}
std::cout << "The Sampling time is: " << data.getSamplingTime() << " miliseconds \n"
<< std::endl;
}
auto end = std::chrono::system_clock::now();
std::cout << "Elapsed time is " << std::chrono::duration_cast<std::chrono::seconds>(end - start).count() << " seconds" << std::endl;
return 0;
}
// test.getData();
// std::vector<std::vector<int>> output = test.printData();
// std::cout << "Sample #" << test.getSampleNumber() << std::endl;
// // print sensing range
// for (int i = 0; i < output.size(); i++)
// {
// for (int j = 0; j < output.at(i).size(); j++)
// {
// std::cout << "[" << output.at(i).at(j) << "] ";
// }
// std::cout << std::endl;
// }
// std::cout << "The Sampling time is: " << test.getSamplingTime() << " miliseconds \n"
// << std::endl;
/*
for (int i=5; i>0; --i) {
std::this_thread::sleep_for (std::chrono::seconds(1));
}
*/
// while (test.queryParameters() == false)
// {
// system("clear"); // clear console
// std::cout << "Invalid Parameters. Please try again" << std::endl;
// std::cin.clear();
// std::cout << "Please enter the number of rows required for the image size: " << std::endl;
// while (!(std::cin >> set_rows) || set_rows < 0)
// {
// std::cin.clear();
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// std::cout << "Invalid input, Try again: ";
// }
// std::cout << "Please enter the number of columns required for the image size: " << std::endl;
// while (!(std::cin >> set_columns) || set_columns < 0)
// {
// std::cin.clear();
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// std::cout << "Invalid input, Try again: ";
// }
// std::cout << "Please enter the sampling required: " << std::endl;
// while (!(std::cin >> set_sampling_time) || set_sampling_time < 0)
// {
// std::cin.clear();
// std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// std::cout << "Invalid input, Try again: ";
// }
// // adjust new adjusted user parameters
// test.setImageSize(set_rows, set_columns);
// test.setSamplingTime(set_sampling_time);
// test .clear()
// }
// if (test.queryParameters() == true)
// {
// system("clear"); // clear console
// std::cout << "Based on Inputs the configuration is: " << std::endl;
// test.getData();
// std::cout << "Image Size (Rows x Columns):" << test.getImageSize() << "\n"
// << "Sampling time :" << test.getSamplingTime() << " miliseconds" << std::endl;
// }
|
C
|
UTF-8
| 4,231 | 3.640625 | 4 |
[] |
no_license
|
/****************************************
Assignment - 5
Name : Dinesh Sandadi
Zid : Z1797942
Section : 2
DateDue : 10/28/2017
TA : David Wiilams
Purpose : This program implement producer consumer problem solution using semaphores and mutex.
Execution : make
./Assign5
****************************************/
// including libraries.
#include "Synchronization_Process.h"
/*
* Function : Produce
* Purpose : This function is called by the producer thread.
* Returns : void* .
*/
void* Produce(void* threadID) {
int i ;
// a loop to insert the items.
for (i = 0; i < P_STEPS; i++) {
// waiting if buffer is full.
sem_wait(&NotFull);
Insert(threadID);// inserting item in to the buffer.
sem_post(&NotEmpty);// signalling.
sleep(1);//sleep for 1 milli second.
}
pthread_exit(NULL);// exit the thread.
}
/*
* Function : Insert
* Purpose : This function is called by the produce method to insert an item.
* Returns : Nothing.
*/
void Insert(void* threadID){
long id = (long)threadID;
// grabbing the mutex lock.
pthread_mutex_lock(&mutex);
counter ++ ;// incrementing the counter.
fprintf(stderr,"Producer %ld inserted one item. Total is now %d\n",id,counter);
pthread_mutex_unlock(&mutex);// unlocking the mutex.
}
/*
* Function : Remove
* Purpose : This function is called by the consumer thread to remove an item from the bufer.
* Returns : Nothing.
*/
void Remove(void* threadID){
long id = (long)threadID;
// grabbing the mutex lock.
pthread_mutex_lock(&mutex);
counter-- ;// decrementing the counter.
fprintf(stderr,"Consumer %ld removed one item. Total is now %d\n",id,counter);
pthread_mutex_unlock(&mutex);// unlocking the mutex.
}
/*
* Function : Consume
* Purpose : This function is called by the consumer thread.
* Returns : void*.
*/
void* Consume(void* threadID) {
int i;
for (i = 0; i < C_STEPS; i++) {
sem_wait(&NotEmpty);//wait if the buffer is empty.
Remove(threadID);// remove item from the buffer.
sem_post(&NotFull);// signal not full.
sleep(1);
}
pthread_exit(NULL);// exit the thread.
}
/*
* Function : main
* Purpose : This is the entry point of the program.
* Returns : integer value representing the exit status.
*/
int main(int argc, char** argv) {
fprintf(stdout,"Simulation of Producer and Consumers \n");
//creating semaphores.
if (sem_init(&NotFull, 0, BUFFER_SIZE) < 0) {
fprintf(stderr, "Can't initialize the NotFull semaphore.\n");
exit(NON_SUCCESS);
}
if (sem_init(&NotEmpty, 0, 0)) {
fprintf(stderr, "Can't initialize the NotEmpty semaphore.\n");
exit(NON_SUCCESS);
}
//create mutex.
if (pthread_mutex_init(&mutex, NULL)) {
fprintf(stderr, "Can't initialize the mutex lock.\n");
exit(NON_SUCCESS);
}
//mutex and semaphores have been setup.
fprintf(stdout,"The semaphores and mutex have been initialized.\n");
// Creating an array of producer threads, and an array of consumer threads.
//initializing producer threads and consumer threads.
pthread_t producerThreads[P_NUMBER];
pthread_t consumerThreads[C_NUMBER];
// creating P_NUMBER of producer threads.
long i;
for(i =0;i<P_NUMBER;i++){
long rc = pthread_create(&producerThreads[i],NULL,Produce,(void*) i);
if(rc){
fprintf(stderr,"Error creating producer thread %ld \n",i);
}
}
// creating C_NUMBER of consumer threads.
for(i = 0;i<C_NUMBER;i++){
long rc = pthread_create(&consumerThreads[i],NULL,Consume,(void*) i);
if(rc){
fprintf(stderr,"Error creating producer thread %ld \n",i);
}
}
// Waiting for producer threads to join the main thread.
for (i =0;i<P_NUMBER;i++){
pthread_join(producerThreads[i],NULL);
}
// Waiting for consumer threads to join the main thread.
for (i =0;i<C_NUMBER;i++){
pthread_join(consumerThreads[i],NULL);
}
fprintf(stdout,"All the producer and consumer threads have been closed.\n");
// destroy the notFull semaphore.
sem_destroy(&NotFull);
sem_destroy(&NotEmpty);// destroy the notEmpty semaphore.
pthread_mutex_destroy(&mutex);// destroying the mutex lock.
fprintf(stdout,"The semaphores and mutex have been deleted.\n");
return (EXIT_SUCCESS);
}
|
Python
|
UTF-8
| 3,355 | 2.96875 | 3 |
[] |
no_license
|
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
import astropy.units as unit
import astropy.constants as cons
import matplotlib as mpl
mpl.rcParams['font.size']=14
def f(r, x2, y2):
x,y,xdot,ydot=r[2],r[3],x2(r[2],r[3]),y2(r[2], r[3])
return np.array([x,y,xdot,ydot])
def trajectory(v0, theta, planet, mass=1.):
if (planet=='Earth' or planet=='earth'):
g=9.8
rho=1.22
elif (planet=='Mars' or planet=='mars'):
g=3.71
rho=0.20
else:
print('Planets currently supported are Earth and Mars. Please enter one of those two for "planet".')
return
R=.08
theta=np.deg2rad(theta)
x0,x1,y0,y1=0.,v0*np.cos(theta), 0, v0*np.sin(theta)
xs=[]
ys=[]
C=0.47
H=.01
t0=0
delta=1e-4
y2=lambda x1,y1: -g-(np.pi*R**2*rho*C*y1*np.sqrt(x1**2+y1**2))/(2*mass)
x2=lambda x1,y1: -(np.pi*R**2*rho*C*x1*np.sqrt(x1**2+y1**2))/(2*mass)
vec=np.array([x0,y0,x1,y1])
y=y0
while y>-1e-6:
xs.append(vec[0])
ys.append(vec[1])
n=1
r1=vec+0.5*H*f(vec, x2, y2)
r2=vec+H*f(r1, x2, y2)
R1=np.empty([1,4], float)
R1[0]=0.5*(r1+r2+0.5*H*f(r2, x2, y2))
error=2*H*delta
while error>H*delta:
n+=1
h=H/n
r1=vec+0.5*h*f(vec, x2, y2)
r2=vec+h*f(r1,x2, y2)
for i in range(n-1):
r1+=h*f(r2, x2, y2)
r2+=h*f(r1, x2, y2)
R2=R1
R1=np.empty([n,4],float)
R1[0]=0.5*(r1+r2+0.5*h*f(r2, x2, y2))
for m in range(1,n):
epsilon=(R1[m-1]-R2[m-1])/((n/(n-1))**(2*m)-1.)
R1[m]=R1[m-1]+epsilon
error=np.abs(epsilon[0])
vec=R1[n-1]
y=ys[-1]
return xs, ys
def max_distance(v0, theta, planet, mass=1., plot=False):
xs, ys = trajectory(v0=v0, theta=theta, planet=planet, mass=mass)
if plot:
f, ax = plt.subplots(1, figsize=(7,5))
ax.plot(xs, ys)
ax.set_xlabel('x[m]')
ax.set_ylabel('y[m]')
ax.set_title('$v_0={}$, $\\theta={}$, {}, $xmax=${:.0f}'.format(v0,theta, planet, xs[-1]))
plt.show()
return xs[-1]
def multimass_distance(v0, theta, planet, minmass, maxmass):
masses=np.linspace(minmass, maxmass, 50)
xlist=[]
for m in masses:
x=max_distance(v0=v0, theta=theta, planet=planet, mass=m)
xlist.append(x)
return masses, xlist
def multimass_distance_plot(v0, theta, planet, minmass, maxmass):
if planet=='both' or planet=='Both':
emasses, exlist=multimass_distance(v0=v0, theta=theta, planet='earth', minmass=minmass, maxmass=maxmass)
mmasses, mxlist=multimass_distance(v0=v0, theta=theta, planet='mars', minmass=minmass, maxmass=maxmass)
f, ax = plt.subplots(1, figsize=(7,5))
exlist, mxlist=np.array(exlist), np.array(mxlist)
exlist=exlist/np.max(exlist)
mxlist=mxlist/np.max(mxlist)
ax.plot(emasses, exlist, label='Earth')
ax.plot(mmasses, mxlist,label='Mars')
ax.set_xlabel('Mass [kg]')
ax.set_ylabel('Normalized Maximum Distance')
plt.legend()
plt.show()
return f, ax
masses, xlist=multimass_distance(v0=v0, theta=theta, planet=planet, minmass=minmass, maxmass=maxmass)
f, ax = plt.subplots(1, figsize=(7,5))
ax.plot(masses, xlist)
ax.set_xlabel('Mass [kg]')
ax.set_ylabel('Maximum Distance [m]')
plt.show()
return f, ax
|
Markdown
|
UTF-8
| 616 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
# SoundManager
Sound handle.
## Functions
| Name | Description |
|:---|:---|
| switchBGMByName | Play the background music by resource name. |
| switchBGMBySound | Play the background music by sound itself. |
| playOneShotByNames | Play one shot the sound by using the resource name. |
| playOneShotBySound | Play one shot the sound by using the sound itself. |
| setBGMFadeInTime | Set the background music fade in time. |
| setBGMFadeOutTime | Set the backgroun music fade out time. |
| setBGMVolume | Set the background music volume. |
| getBGMVolume | Returns the background music's sound channel's volume. |
|
C++
|
UTF-8
| 2,032 | 2.8125 | 3 |
[] |
no_license
|
#include "Sprite.h"
//------------------------------------Constructors-----------------------------------------------
Sprite::Sprite(): drawBox{0,0,0,0}, drawCirc{}, assetTex{nullptr} {};
Sprite::Sprite(SDL_Rect dBox, SDL_Texture* aTex): drawBox{dBox}, drawCirc{}, assetTex{aTex}, animFrame{-1} {};
Sprite::Sprite(SDL_Rect dBox, SDL_Texture* aTex, int anim): drawBox{dBox}, drawCirc{}, assetTex{aTex}, animFrame{anim} {};
Sprite::Sprite(NSDL_Circ dCirc, SDL_Texture* aTex):drawBox{0,0,0,0}, drawCirc{dCirc}, assetTex{aTex} {};
//------------------------------------Destructor--------------------------------------------------
Sprite::~Sprite(){
SDL_DestroyTexture(assetTex);
assetTex = nullptr;
}
//------------------------------Getters and Setters------------------------------------------------
void Sprite::setX(int x){
drawBox.x = x;
}
int Sprite::getX(){
return drawBox.x;
}
void Sprite::setY(int y){
drawBox.y = y;
}
int Sprite::getY(){
return drawBox.y;
}
void Sprite::setR(int new_r){
drawCirc.setR(new_r) ;
}
int Sprite::getR(){
return drawCirc.getR();
}
void Sprite::setTexture(SDL_Texture* tex){
assetTex = tex;
}
SDL_Texture* Sprite::getTexture(){
return assetTex;
}
void Sprite::setAngle(double new_angle){
angle = new_angle;
}
double Sprite::getAngle(){
return angle;
}
int Sprite::getH(){
return drawBox.h;
}
int Sprite::getW(){
return drawBox.w;
}
void Sprite::setF(int anim){
animFrame = anim;
}
int Sprite::getF(){
return animFrame;
}
//--------------------------Functions Related to Drawing a Rectangle-----------------------------------------
SDL_Rect* Sprite::getDrawBox(){
return &drawBox;
}
bool Sprite::isRectEnt(){
return drawBox.w != 0 && drawBox.h != 0;
}
//---------------------------Functions Related to Drawing a Circle-----------------------------------------
NSDL_Circ* Sprite::getDrawCirc(){
return &drawCirc;
}
bool Sprite::isCircEnt(){
return drawCirc.getR() != 0;
}
|
Java
|
UTF-8
| 1,181 | 3.515625 | 4 |
[] |
no_license
|
// FirstEvents.java
// События - нажатия клавиш на клавиатуре
import javax.swing.*;
import java.awt.event.*;
public class FirstEvents extends JFrame {
public FirstEvents() {
super("FirstEvents");
// при закрытии окна - выход
setDefaultCloseOperation(EXIT_ON_CLOSE);
// регистрируем нашего слушателя
addKeyListener(new KeyL());
// выводим окно на экран
setSize(200, 200);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
new FirstEvents();
}
});
}
}
// этот класс будет получать извещения о событиях
class KeyL implements KeyListener {
// печать символа
public void keyTyped(KeyEvent k) {
System.out.println(k);
}
// нажатие клавиши
public void keyPressed(KeyEvent k) {
System.out.println(k);
}
// отпускание нажатой клавиши
public void keyReleased(KeyEvent k) {
System.out.println(k);
}
}
|
Java
|
UTF-8
| 275 | 2.015625 | 2 |
[] |
no_license
|
package com.example.demo.services;
import com.example.demo.entity.Books;
import java.util.List;
public interface BooksService {
boolean save(Books books);
List<Books> findAllBooks();
Books findBook(int id);
void addBookGenre(int bookId, int genreId);
}
|
JavaScript
|
UTF-8
| 631 | 4 | 4 |
[] |
no_license
|
function getString() {
s1 = "hello";
s2 = "pillow";
return s1 && s2;
}
function getStrings(s1, s2) {
s1List = [];
s2List = [];
i = 0;
sameLetter = "";
for (s in s1) {
s1List.push(s);
}
for (s in s2) {
s2List.push(s);
}
while (i < s1List.length && i < s2List.length) {
if (s1List[i] != s2List[i]) {
sameLetter += ".";
} else {
sameLetter += s1List[i];
}
i += 1;
return sameLetter;
}
}
function work() {
s1 = getString();
s2 = getString();
console.log(getStrings(s1, s2));
}
work();
|
Python
|
UTF-8
| 288 | 3.65625 | 4 |
[] |
no_license
|
#!/usr/bin/python3
""" A Function that computes
the square value of all integers of a matrix.
"""
def square_matrix_simple(matrix=[]):
if matrix:
new_matrix = []
for rows in matrix:
new_matrix.append([n ** 2 for n in rows])
return new_matrix
|
Python
|
UTF-8
| 171 | 3.859375 | 4 |
[] |
no_license
|
#Multiplication of the given number:
entrada=input("Digite los numeros: ")
lista=entrada.split(',')
mult = 1
for i in lista:
mult = mult * int(i)
print(mult)
|
Python
|
UTF-8
| 1,281 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
a = 50
print('\033[32m_\033[m'*a)
print('\033[1;32m{:=^{}}\033[m'.format('SISTEMA DE BOLETIM', a))
print('\033[32m-\033[m'*a)
boletim = list()
individuo = list()
notas = list()
media = 0
continuar = 's'
conti2 = 0
while True:
if 's' in continuar:
individuo.append(input('Nome: '))
notas.append(float(input('Nota 1: ')))
notas.append(float(input('Nota 2: ')))
individuo.append(notas[:])
boletim.append(individuo[:])
notas.clear()
individuo.clear()
elif 'n' in continuar:
break
else:
print('Tente novamente!', end='')
continuar = str(input('Deseja continuar? [S/N]')).lower().strip()[0]
print('\033[35m-=\033[m'*20)
print('\033[1;34mNº NOME MEDIA')
print('-'*26)
for c, n in enumerate(boletim):
media = (n[1][0]+n[1][1])/2
#print(f'n={n}, c={c}')
print(f'{c:<2} {n[0]:<15} {media:>5}')
print('\033[35m-=\033[m'*20)
while True:
conti2 = int(input('\033[1;36mMostrar notas de qual aluno? (999 para interromper) \033[m'))
if conti2 == 999:
break
elif conti2 > len(boletim):
print('\033[31mAluno nao encontrado, tente novamente! \033[m')
else:
print(f'\033[1;34mNotas de {boletim[conti2][0]} são: {boletim[conti2][1]}\033[m')
|
Java
|
UTF-8
| 2,889 | 3.75 | 4 |
[] |
no_license
|
package Lists;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class InsertionSort {
public static JFrame frame = new JFrame();
public static JPanel panel = new JPanel();
public static JPanel display = new JPanel();
public static JButton button = new JButton();
public static JTextField text = new JTextField(20);
public InsertionSort() {
UI(); //call basic UI setup
Button(); //add button and functionality
}
/**
* This is used for the initial UI setup
*/
public void UI() {
frame.setTitle("Insertion Sort");
frame.setSize(1200,1200);
frame.setVisible(true);
frame.getContentPane();
Label menu = new Label("Enter a list using CSV format");
text.setSize(100, 100);
panel.add(menu);
panel.add(text);
panel.setSize(50, 50);
frame.add(panel);
}
/**
* Set up for the button and response when pressed
*/
public void Button() {
button = new JButton();
button.setText("Sort List!");
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String input = text.getText();
int[] arrayInput = stringToArray(input);
insertionSort(arrayInput);
}
};
button.addActionListener(listener);
panel.add(button);
}
public static void main(String[] args) {
new InsertionSort();
}
/**
* This method takes a string and parse it as an array containing int numbers
* @param input
* @return
*/
public static int[] stringToArray(String input) {
String[] strArray = input.split(",");
int[] intArray = new int[strArray.length];
for(int i = 0; i<strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
return intArray;
}
/**
* Insertion Sort for array of int
* @param array
*/
public static void insertionSort(int [] array) {
int length = array.length;
int iteration = 0;
for(int i = 1; i < length; i ++) {
int key = array[i];
int hole = i;
while(hole > 0 && array[hole-1] > key) {
array[hole] = array[hole-1];
hole--;
}
array[hole] = key;
iteration++;
toLabel(array,iteration);
}
}
/**
* Method to format array to properly display on the frame
* @param array
* @return
*/
public static String toLabel(int [] array, int iteration) {
String s = "";
for(int i = 0; i< array.length; i++) {
s = s + array[i] + "|";
}
s = "Iteration" + iteration + ": " + s;
Label label = new Label(s);
Dimension size = label.getPreferredSize();
label.setBounds(150, 100, size.width, size.height);
label.setFont(new Font("Serif", Font.PLAIN, 34));
panel.add(label);
s = ""; //trim the string for next iteration
return s;
}
}
|
C++
|
UTF-8
| 7,061 | 2.59375 | 3 |
[] |
no_license
|
#include <sys/shm.h>
#include <libexplain/shmctl.h>
#include <string>
#include "Node.h"
#include "Gk.h"
#include "pp.h"
#include "util_shm.h"
#include "util_clt.h"
void *GetShmMem_(key_t key, size_t size)
{
void *shm = NULL; //分配的共享内存的原始首地址
int shmid; //共享内存标识符
//创建共享内存
shmid = shmget((key_t)key, size, 0666 | IPC_CREAT);
if (shmid == -1)
{
printf("shmget failed. key:%x size:%lu\n", key, size);
exit(EXIT_FAILURE);
}
//将共享内存连接到当前进程的地址空间
shm = shmat(shmid, 0, 0);
if (shm == (void *)-1)
{
printf("shmat failed\n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %p\n", shm);
return shm;
}
template <typename T>
T *GetShmMem(key_t key)
{
return (T *)GetShmMem_(key, sizeof(T));
}
void FreeShmMem(key_t key, void *ptr)
{
shmid_ds shmbuffer;
//把共享内存从当前进程中分离
if (shmdt(ptr) == -1)
{
printf("shmdt failed\n");
exit(EXIT_FAILURE);
}
//删除共享内存
shmctl(key, IPC_RMID, 0);
}
bool *GetNeedGenPtr()
{
static bool *needGen = GetShmMem<bool>(KEY_NEEDGEN);
return needGen;
}
void FreeNeedGen()
{
bool *needGen = GetNeedGenPtr();
FreeShmMem(KEY_NEEDGEN, (void *)needGen);
}
SystemParam *GetSystemParamPtr()
{
static SystemParam *systemParam = GetShmMem<SystemParam>(KEY_SYSTEMPARAM);
return systemParam;
}
void SendSystemParam(const SystemParam *systemParam)
{
SystemParam *shm_systemParam = GetSystemParamPtr();
shm_systemParam->serParam = systemParam->serParam;
shm_systemParam->attrNumber = systemParam->attrNumber;
for (int i = 0; i < systemParam->attrNumber; ++i)
{
shm_systemParam->attr[i] = systemParam->attr[i];
}
}
void FreeSystemParam()
{
SystemParam *systemParam = GetSystemParamPtr();
FreeShmMem(KEY_SYSTEMPARAM, (void *)systemParam);
}
Gk *GetGkPtr(int nodeNumb)
{
//static Gk *shm_gk = (Gk *)GetShmMem_(KEY_GK, sizeof(Gk) + sizeof(Node) * nodeNumb);
static Gk *shm_gk = GetShmMem<Gk>(KEY_GK);
return shm_gk;
}
void SendGk(const Gk *gk)
{
Gk *shm_gk = GetGkPtr(gk->nodeNumb);
//*shm_gk = *gk;
shm_gk->nodeNumb = gk->nodeNumb;
//shm_gk->nodes = gk->nodes;
//printf("gk nodes size:%d\n", gk->nodes.size());
}
void FreeGk()
{
Gk *shm_gk = GetGkPtr(0);
FreeShmMem(KEY_GK, (void *)shm_gk);
}
FILE *GetPublicKeyFile(std::string command)
{
FILE *file;
file = fopen("publicKey.dat", command.c_str());
if (file == NULL)
{
perror("Error opening file");
}
return file;
}
PublicKey *GetPublicKeyPtr()
{
static PublicKey *shm_publicKey = GetShmMem<PublicKey>(KEY_PUBLICKEY);
return shm_publicKey;
}
PublicKey *GetPublicKey()
{
PublicKey *shm_publicKey = GetPublicKeyPtr();
FILE *file = GetPublicKeyFile("rb+");
printf("GetPublicKey shm_publicKey->top_level:%d\n", shm_publicKey->top_level);
printf("GetPublicKey shm_publicKey->attrNumber:%d\n", shm_publicKey->attrNumber);
shm_publicKey->pp = util_clt_pp_restore(file);
printf("GetPublicKey util_clt_pp_restore over\n");
shm_publicKey->sk = util_clt_state_restore(file);
printf("GetPublicKey util_clt_state_restore over\n");
shm_publicKey->MSK = clt_elem_new();
util_clt_elem_restore(file, shm_publicKey->MSK);
printf("GetPublicKey shm_publicKey->MSK over\n");
for (int i = 0; i < shm_publicKey->attrNumber; ++i)
{
mpz_init(shm_publicKey->attributes[i].t);
if (mpz_inp_raw(shm_publicKey->attributes[i].t, file) == 0)
{
fprintf(stderr, "attributes mpz_inp_raw failed!\n");
exit(1);
}
}
printf("GetPublicKey shm_publicKey->attributes over\n");
shm_publicKey->encodingOfa = clt_elem_new();
util_clt_elem_restore(file, shm_publicKey->encodingOfa);
printf("GetPublicKey shm_publicKey->encodingOfa over\n");
rewind(file);
fclose(file);
return shm_publicKey;
}
void SendPublicKey(const PublicKey *publicKey)
{
//printf("SendPublicKey enter\n");
PublicKey *shm_publicKey = GetPublicKeyPtr();
FILE *file = GetPublicKeyFile("wb+");
//*shm_publicKey = *publicKey;
shm_publicKey->top_level = publicKey->top_level;
shm_publicKey->attrNumber = publicKey->attrNumber;
util_clt_pp_store(file, publicKey->pp);
util_clt_state_store(file, publicKey->sk);
util_clt_elem_store(file, publicKey->MSK);
/*if (mpz_out_raw(file, publicKey->MSK) == 0)
{
fprintf(stderr, "mpz_out_raw failed!\n");
exit(1);
}*/
//printf("SendPublicKey attributes begin\n");
for (int i = 0; i < publicKey->attrNumber; ++i)
{
if (mpz_out_raw(file, ((PublicKey *)publicKey)->attributes[i].t) == 0)
{
fprintf(stderr, "attributes mpz_out_raw failed!\n");
exit(1);
}
}
//printf("SendPublicKey attributes end\n");
util_clt_elem_store(file, publicKey->encodingOfa);
rewind(file);
fclose(file);
//printf("SendPublicKey end\n");
}
void FreePublicKey()
{
PublicKey *shm_publicKey = GetPublicKeyPtr();
FreeShmMem(KEY_PUBLICKEY, (void *)shm_publicKey);
}
FILE *GetSskFile(std::string command)
{
FILE *file;
file = fopen("ssk.dat", command.c_str());
if (file == NULL)
{
perror("Error opening file");
}
return file;
}
ssk *GetSskPtr()
{
static ssk *shm_sk = GetShmMem<ssk>(KEY_SSK);
return shm_sk;
}
ssk *GetSsk()
{
ssk *shm_sk = GetSskPtr();
FILE *file = GetSskFile("rb+");
printf("GetSsk shm_sk->nodeNumber:%d\n", shm_sk->nodeNumber);
mpz_init(shm_sk->kh);
if (mpz_inp_raw(shm_sk->kh, file) == 0)
{
fprintf(stderr, "kh mpz_inp_raw failed!\n");
exit(1);
}
printf("GetSsk shm_sk->kh over\n");
for (int i = 0; i < shm_sk->nodeNumber * 4; ++i)
{
mpz_init(shm_sk->skUnion[i]);
if (mpz_inp_raw(shm_sk->skUnion[i], file) == 0)
{
fprintf(stderr, "skUnion[%d] mpz_inp_raw failed!\n", i);
exit(1);
}
}
printf("GetSsk shm_sk->skUnion over\n");
printf("GetSsk shm_sk->skStartIndex over\n");
rewind(file);
fclose(file);
return shm_sk;
}
void SendSsk(const ssk *sk)
{
ssk *shm_sk = GetSskPtr();
FILE *file = GetSskFile("wb+");
shm_sk->nodeNumber = sk->nodeNumber;
if (mpz_out_raw(file, sk->kh) == 0)
{
fprintf(stderr, "kh mpz_out_raw failed!\n");
exit(1);
}
for (int i = 0; i < sk->nodeNumber * 4; ++i)
{
if (mpz_out_raw(file, sk->skUnion[i]) == 0)
{
fprintf(stderr, "skUnion[%d] mpz_out_raw failed!\n", i);
exit(1);
}
}
for (int i = 0; i < sk->nodeNumber; ++i)
{
shm_sk->skStartIndex[i] = sk->skStartIndex[i];
}
rewind(file);
fclose(file);
}
void FreeSsk()
{
ssk *shm_sk = GetSskPtr();
FreeShmMem(KEY_SSK, (void *)shm_sk);
}
|
PHP
|
UTF-8
| 579 | 2.640625 | 3 |
[] |
no_license
|
<?php
/**
* Delete a user
*/
require "../config.php";
if (isset($_GET["id"])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$id = $_GET["id"];
$sql = "DELETE FROM baibao WHERE MaBB = :id";
$statement = $connection->prepare($sql);
$statement->bindValue(':id', $id);
$statement->execute();
$success = "Bai bao successfully deleted";
header('Location: PhamManhHieu_1530059_03.php');
} catch (PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
|
JavaScript
|
UTF-8
| 2,503 | 2.578125 | 3 |
[] |
no_license
|
import React, { useState, useEffect } from "react";
import '../styles/MyKdrama.css'
import "./Icons.js";
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import DramaCard from "./DramaCard";
const axios = require('axios').default;
function MyKdrama(props) {
const [watchedDramas, setWatchedDramas] = useState([]);
const [laterDramas, setLaterDramas] = useState([]);
// get dramas from database
const getWatched = () => {
axios.post('https://mykdrama.herokuapp.com/getWatched', {
userID: localStorage.getItem('userID')
}).then((res) => {
setWatchedDramas(res.data);
});
}
const getWatchlater = () => {
axios.post('https://mykdrama.herokuapp.com/getWatchlater', {
userID: localStorage.getItem('userID')
}).then((res) => {
setLaterDramas(res.data);
});
}
useEffect(() => {
window.scrollTo(0, 0);
if (localStorage.getItem('userID') && localStorage.getItem('userID') !== "0") {
getWatched();
getWatchlater();
}
}, [props.location]);
return (
<div className="myKdramaPage">
<div className="arrowTitle">
<FontAwesomeIcon icon="angle-double-right" size="2x" className="purpleAngleRight"/>
<p className="watchTitle">Watched</p>
</div>
<div className="horzScroll">
<div className="myDramas">
{watchedDramas.length !== 0 && watchedDramas.map(x=>{return <DramaCard key={x.showID} data={x} dramaID={x.watchedID} fromWatched={true} />})}
</div>
</div>
<div className="arrowTitle">
<FontAwesomeIcon icon="angle-double-right" size="2x" className="blueAngleRight"/>
<p className="watchTitle">Watch Later</p>
</div>
<div className="horzScroll">
<div className="myDramas">
{laterDramas.length !== 0 && laterDramas.map(x=>{return <DramaCard key={x.showID} data={x} dramaID={x.watchlaterID} fromWatched={false} />})}
</div>
</div>
{watchedDramas.length === 0 && laterDramas.length === 0 && (
<div className="emptyMessage">
<p>So far empty :(</p>
<p>Go look for some K-dramas!</p>
</div>
)}
</div>
);
}
export default MyKdrama;
|
C
|
UTF-8
| 935 | 2.625 | 3 |
[] |
no_license
|
#define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_2__ TYPE_1__ ;
/* Type definitions */
struct pointer_status {int pointer_id; struct pointer_status* next; } ;
struct TYPE_2__ {struct pointer_status* next; } ;
struct dinput_input {TYPE_1__ pointer_head; } ;
/* Variables and functions */
__attribute__((used)) static struct pointer_status *dinput_find_pointer(
struct dinput_input *di, int pointer_id)
{
struct pointer_status *check_pos = di->pointer_head.next;
while (check_pos)
{
if (check_pos->pointer_id == pointer_id)
break;
check_pos = check_pos->next;
}
return check_pos;
}
|
C#
|
UTF-8
| 1,692 | 2.75 | 3 |
[] |
no_license
|
using System;
namespace OpenDentBusiness {
///<summary>Stores the session token for when a user has logged into something.</summary>
[Serializable]
public class SessionToken:TableBase {
///<summary>Primary key.</summary>
[CrudColumn(IsPriKey=true)]
public long SessionTokenNum;
///<summary>The hash of the token. Hashed using SHA3_512 without a salt.</summary>
public string SessionTokenHash;
///<summary>The datetime when this token will expire.</summary>
[CrudColumn(SpecialType=CrudSpecialColType.DateT)]
public DateTime Expiration;
///<summary>Enum:SessionTokenType The type of token this is.</summary>
public SessionTokenType TokenType;
///<summary>The FKey this token is for. For Patient Portal tokens, this is patient.PatNum. For Mobile Web tokens, this is userod.UserNum.</summary>
public long FKey;
///<summary>The plain text (non-hashed) version of the token.</summary>
[CrudColumn(IsNotDbColumn=true)]
public string TokenPlainText;
///<summary></summary>
public SessionToken Copy() {
return (SessionToken)this.MemberwiseClone();
}
}
public enum SessionTokenType {
///<summary>0 - Should not be used in the database.</summary>
Undefined,
///<summary>1 - The patient has logged in with a username and password.</summary>
PatientPortal,
///<summary>2 - The OD user has logged in with a username and password.</summary>
MobileWeb,
///<summary>3 - This token is for an OD HQ service that has authenticated to us.</summary>
ODHQ,
///<summary>4 - The patient verified him or herself with just a name and birthdate.</summary>
PatientPortalVerifyUser,
}
}
|
Markdown
|
UTF-8
| 1,987 | 3.203125 | 3 |
[] |
no_license
|
# 論婚姻的鎖鏈以及保祿特權
**依諾森三世**
**致富拉里主教烏里書--公元一一九九年五月一日-PL214, 588C**
閣下曾函告我們,請示:夫妻之一方,遺棄另一方而改入異端教。那被遺棄的一,方想要再結婚,生育子女。試問:根據律法,這能這
樣做嗎?所以我們就把你所問的問題,同我們的兄們商議結果,我們這樣答覆閣下:雖然我們的前任教宗(如:天士三世 Caelestinus
Ⅲ)似乎並不這樣想法,但我們要加以分析:是否夫妻二人,先是外教人,後來,中一方,歸正,信奉天主教?或是:夫妻二人,先是天主教人,後來中一方,陷入
異端教,或失落信德,又入落入外教人的錯誤中?如2木2夫妻二人,先是外教人,後來其中一方歸正,信奉天主教,而另一方,或完全不願與對方同居,或至少非
凌辱天主聖名,非牽引對方陷入大罪,不願同居,那麼,在這些環境之下,那被遺棄的一,方若願再結婚,儘可准予結婚,因為保祿宗徙說過:「若不信主的一方要
離去,就由他離去;在這種情形之下,兄弟或姐妹,不必受拘束」(格前:七,十五)。而且教會的典章,也這樣規定:「對造物主的凌辱,解除了那被遺棄者的姻
(權利)-束縳」。【 Grat Decr P ⅡCS 28.Q2c2 ( Frdb.1,1090)】
如果夫妻二人,都是(天主教)教友,而其中之一,陷入異端或外教的錯誤,那麼,我們相信:在這種情況之下,那被遺棄的一,方在
對方還沒有死去之前,縱然對造物主的凌辱,顯得更大,也不能再和別人結婚。因為二個外教夫妻的婚姻,固然是真實的,卻不成聖事;至於信友夫妻的婚姻,則不
然;他們一結婚,則若對方還在世間時,總不能離散而再行結婚,因為信友一結婚,便成為婚配聖事。
|
PHP
|
UTF-8
| 3,667 | 3.09375 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
/**
* Class Date_conv
*
* Class for date conversion in Gregorian-Julian-Hijri calendar.
* This class originally adopted from hijri-dates library (https://github.com/GeniusTS/hijri-dates/blob/master/src/Converter.php)
*
* @license MIT
*/
class Date_conv
{
/**
* The Julian Day for a given Gregorian date.
*
* @param int $year
* @param int $month
* @param int $day
*
* @return float
*/
public static function gregorianToJulian($year, $month, $day)
{
if ($month < 3)
{
$year -= 1;
$month += 12;
}
$a = floor($year / 100.0);
$b = ($year === 1582 && ($month > 10 || ($month === 10 && $day > 4)) ? -10 :
($year === 1582 && $month === 10 ? 0 :
($year < 1583 ? 0 : 2 - $a + floor($a / 4.0))));
return floor(365.25 * ($year + 4716)) + floor(30.6001 * ($month + 1)) + $day + $b - 1524;
}
/**
* The Julian Day for a given Hijri date.
*
* @param int $year
* @param int $month
* @param int $day
*
* @return float
*/
public static function hijriToJulian($year, $month, $day)
{
return floor((11 * $year + 3) / 30) + floor(354 * $year) + floor(30 * $month)
- floor(($month - 1) / 2) + $day + 1948440 - 386;
}
/**
* The Gregorian date Day for a given Julian
*
* @param float $julianDay
*
* @return array
*/
public static function julianToGregorian($julianDay)
{
$b = 0;
if ($julianDay > 2299160)
{
$a = floor(($julianDay - 1867216.25) / 36524.25);
$b = 1 + $a - floor($a / 4.0);
}
$bb = $julianDay + $b + 1524;
$cc = floor(($bb - 122.1) / 365.25);
$dd = floor(365.25 * $cc);
$ee = floor(($bb - $dd) / 30.6001);
$day = ($bb - $dd) - floor(30.6001 * $ee);
$month = $ee - 1;
if ($ee > 13)
{
$cc += 1;
$month = $ee - 13;
}
$year = $cc - 4716;
return array('year' => (int) $year, 'month' => (int) $month, 'day' => (int) $day);
}
/**
* The Hijri date Day for a given Julian
*
* @param float $julianDay
*
* @return array
*/
public static function julianToHijri($julianDay)
{
$y = 10631.0 / 30.0;
$epochAstro = 1948084;
$shift1 = 8.01 / 60.0;
$z = $julianDay - $epochAstro;
$cyc = floor($z / 10631.0);
$z = $z - 10631 * $cyc;
$j = floor(($z - $shift1) / $y);
$z = $z - floor($j * $y + $shift1);
$year = 30 * $cyc + $j;
$month = (int)floor(($z + 28.5001) / 29.5);
if ($month === 13)
{
$month = 12;
}
$day = $z - floor(29.5001 * $month - 29);
return array('year' => (int) $year, 'month' => (int) $month, 'day' => (int) $day);
}
public static function gregorianToHijri($year, $month, $day)
{
$jd = self::gregorianToJulian($year, $month, $day);
return self::julianToHijri($jd);
}
}
class Hijri_date_id
{
private static $months = array(1=>'Muharram', 'Safar', "Rabi'ul Awal", "Rabi'ul akhir", 'Jumadil Awal', 'Jumadil Akhir', 'Rajab', "Sya'ban", 'Ramadhan', 'Syawal', 'Dzulqaidah', 'Dzulhijjah');
public static function date($format, $time=null)
{
//greg
list ($Y,$n,$j) = explode('/', date('Y/n/j', $time ?: time()));
// hijri
$hijri = Date_conv::gregorianToHijri($Y, $n, $j);
$n = $hijri['month'];
$Y = $hijri['year'];
$j = $hijri['day'];
$F = self::$months[$n];
return strtr($format, compact('F','Y','j','n')) .' H';
}
}
|
C#
|
UTF-8
| 3,586 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Script to controll enemy turrets behaviour. It lets them move the turret using two degrees of freedom in two different GameObjects (Base and Turret).
/// Inherits form EnemyController.
/// </summary>
public class TurretController : EnemyController
{
[Header("Turret Variables")]
public float shootDelay = 1.0f; // Delay between bullet spawn.
public float targetDistance = 300.0f; // Distance at which the enemy will start shooting
public Transform turret;
new void Start()
{
base.Start();
Invoke("ShootSpawnableAmmo", shootDelay); // Start shooting.
}
void Update()
{
if (transform != null)
LookAtPlayer();
else
Debug.LogWarning(gameObject.name + ": Doesn't contain Transform component.");
}
/// <summary>
/// Overrides the previous function, it changes due to turrets being composed by two rotating GameObjects. One for Y axis and other for X axis.
/// </summary>
protected override void LookAtPlayer()
{
if (player == null) // Avoid executing code if player variable is null.
{
Debug.LogWarning("Player couldn't be found. Searching again...");
player = GameManager.Instance.player; // Set player variable.
if (player != null)
Debug.LogWarning("Player found!");
else
return;
}
// Look at the player: It's done rotating two pieces, for the y axis rotation the cannonParent is used and for the x axis the turret.
// Y axis:
var cannonTargetPoint = new Vector3(player.transform.position.x, cannonParent.position.y, player.transform.position.z) - cannonParent.position;
var targetRotation = Quaternion.LookRotation(cannonTargetPoint, Vector3.up);
cannonParent.localRotation = Quaternion.Slerp(cannonParent.localRotation, targetRotation, Time.deltaTime * cannonRotationSpeed);
// X axis:
//Take player position minus the offset and then make the cannon rotate to that position.
var turretTargetPoint = new Vector3(turret.position.x, player.transform.position.y - heightOffset, player.transform.position.z) - turret.position;
var turretTargetRotation = Quaternion.LookRotation(turretTargetPoint, Vector3.up);
turret.localRotation = Quaternion.Slerp(turret.localRotation, turretTargetRotation, Time.deltaTime * cannonRotationSpeed);
}
/// <summary>
/// Overriden function to shoot bullets, they are only spawned if the player distance is lower than targetDistance.
/// </summary>
protected override void ShootSpawnableAmmo()
{
if (player == null) // Avoid executing code if player variable is null.
{
Debug.LogWarning("Player couldn't be found. Searching again...");
player = GameManager.Instance.player; // Set player variable.
if (player != null)
Debug.LogWarning("Player found!");
else
return;
}
if (Vector3.Project(player.transform.position - transform.position, player.transform.forward).magnitude <= targetDistance)
base.ShootSpawnableAmmo();
if (bulletSpawnPoints.Length > 0) // Avoid to keep shooting if there are no spawn points.
Invoke("ShootSpawnableAmmo", shootDelay);
else
Debug.Log(gameObject.name + ": spawn points could't be found.");
}
}
|
Go
|
UTF-8
| 710 | 3.21875 | 3 |
[] |
no_license
|
package bowlingkata
// Game keeps the score of a bowling game.
type Game struct {
currentFrame Frame
previousFrame Frame
beforePreviousFrame Frame
score int
}
// Score returns the total score of a game.
func (game *Game) Score() int {
return game.score
}
// Roll registers a new roll to the game.
func (game *Game) Roll(pinsDown int) {
game.currentFrame.Roll(pinsDown)
if game.currentFrame.IsComplete() {
game.score += game.beforePreviousFrame.Bonus(
game.previousFrame,
game.currentFrame,
)
game.score += game.currentFrame.Score()
game.beforePreviousFrame = game.previousFrame
game.previousFrame = game.currentFrame
game.currentFrame = *new(Frame)
}
}
|
Java
|
UTF-8
| 518 | 1.953125 | 2 |
[] |
no_license
|
package com.app;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.app.*")
public class SampleappApplication {
private static final Logger logger = LoggerFactory.getLogger(SampleappApplication.class);
public static void main(String[] args) {
logger.info("Hello World ");
SpringApplication.run(SampleappApplication.class, args);
}
}
|
Java
|
UTF-8
| 2,865 | 2.1875 | 2 |
[] |
no_license
|
package com.hdsx.rabbitmq.vo;
import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
/**
* Jpush 推送的消息体
*/
public class PushMsg implements Serializable {
private static final long serialVersionUID = 1L;
//发送平台类型
private String type;
//标题
private String title;
//消息内容
private String alert;
//通知内容
private String msg_content;
//消息类型
private String contentType;
//角标
private Integer badge;
//声音
private String sound;
//registrationId
private Collection<String> registrationIds = null;
//alias
private Collection<String> alias = null;
//tag
private String tag;
//消息体
private Map<String, String> extras = null;
public PushMsg() {
}
public PushMsg(String type, String title, String contentType, String msg_content, Collection<String> alias, Map<String, String> extras) {
this.type = type;
this.title = title;
this.contentType = contentType;
this.msg_content = msg_content;
this.alias = alias;
this.extras = extras;
}
public Map<String, String> getExtras() {
return extras;
}
public void setExtras(Map<String, String> extras) {
this.extras = extras;
}
public Collection<String> getAlias() {
return alias;
}
public void setAlias(Collection<String> alias) {
this.alias = alias;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getSound() {
return sound;
}
public void setSound(String sound) {
this.sound = sound;
}
public Integer getBadge() {
return badge;
}
public void setBadge(Integer badge) {
this.badge = badge;
}
public String getMsg_content() {
return msg_content;
}
public void setMsg_content(String msg_content) {
this.msg_content = msg_content;
}
public String getAlert() {
return alert;
}
public void setAlert(String alert) {
this.alert = alert;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Collection<String> getRegistrationIds() {
return registrationIds;
}
public void setRegistrationIds(Collection<String> registrationIds) {
this.registrationIds = registrationIds;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
Swift
|
UTF-8
| 490 | 2.578125 | 3 |
[] |
no_license
|
import Foundation
import UIKit
enum Colors {
static let base = UIColor(red: 0.12, green: 0.12, blue: 0.13, alpha: 1.0)
static let red = UIColor(red: 0.85, green: 0.09, blue: 0.14, alpha: 1.0)
static let card = UIColor(red: 0.13, green: 0.15, blue: 0.17, alpha: 1.0)
static let secondaryBase = UIColor(red: 0.13, green: 0.15, blue: 0.17, alpha: 1.00)
static let secondary = UIColor(red: 0.71, green: 0.71, blue: 0.71, alpha: 1.00)
static let white = UIColor.white
}
|
Python
|
UTF-8
| 2,997 | 3.390625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
import simple_draw as sd
sd.resolution = (1200, 700)
# 1) Написать функцию draw_branches, которая должна рисовать две ветви дерева из начальной точки
# Функция должна принимать параметры:
# - точка начала рисования,
# - угол рисования,
# - длина ветвей,
# Отклонение ветвей от угла рисования принять 30 градусов,
# 2) Сделать draw_branches рекурсивной
# - добавить проверку на длину ветвей, если длина меньше 10 - не рисовать
# - вызывать саму себя 2 раза из точек-концов нарисованных ветвей,
# с параметром "угол рисования" равным углу только что нарисованной ветви,
# и параметром "длинна ветвей" в 0.75 меньшей чем длина только что нарисованной ветви
# 3) первоначальный вызов:
# Пригодятся функции
# sd.get_point()
# sd.get_vector()
# Возможный результат решения см lesson_004/results/exercise_04_fractal_01.jpg
# можно поиграть -шрифтами- цветами и углами отклонения
# 4) Усложненное задание (делать по желанию)
# - сделать рандомное отклонение угла ветвей в пределах 40% от 30-ти градусов (28, 42)
# - сделать рандомное отклонение длины ветвей в пределах 20% от коэффициента 0.75 (0.55, 0.95)
# Возможный результат решения см lesson_004/results/exercise_04_fractal_02.jpg
# Пригодятся функции
# sd.random_number()
root_point = sd.get_point(600, 0)
def draw_branches(point, angle, length, delta):
if length < 10:
return
v1 = sd.get_vector(start_point=point, angle=angle, length=length)
v1.draw()
next_point = v1.end_point
rand_angle = int(sd.random_number(0, 1))
if rand_angle == 1:
delta += sd.random_number(0, 12)
else:
delta -= sd.random_number(0, 12)
rand_length = int(sd.random_number(0, 1))
coefficient_length = .75
if rand_length == 1:
coefficient_length += sd.random_number(1, 20)/100
else:
coefficient_length -= sd.random_number(1, 20)/100
next_angle_right = angle - delta
next_angle_left = angle + delta
next_length = length * coefficient_length
draw_branches(point=next_point, angle=next_angle_right, length=next_length, delta=delta)
draw_branches(point=next_point, angle=next_angle_left, length=next_length, delta=delta)
draw_branches(point=root_point, angle=90, length=100, delta=30)
sd.pause()
|
Java
|
UTF-8
| 1,424 | 3.375 | 3 |
[] |
no_license
|
package stream_API.exercises;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
public class OfficeStuff {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
Map<String,Map<String, Integer>> stuff = new TreeMap<>();
for (int i = 0; i < n; i++) {
String line = reader.readLine();
String[] input = line.replaceAll("\\|", "").split("\\s+-\\s+");
String company = input[0];
Integer amount = Integer.parseInt(input[1]);
String product = input[2];
if(!stuff.containsKey(company)){
stuff.put(company, new LinkedHashMap<>());
}
if(!stuff.get(company).containsKey(product)){
stuff.get(company).put(product, amount);
}else {
Integer newAmount =stuff.get(company).get(product) + amount;
stuff.get(company).put(product, newAmount);
}
}
stuff.forEach((key, value) -> System.out.printf("%s: %s%n", key, value.toString()
.replaceAll("[{}]", "")
.replaceAll("=", "-")));
}
}
|
Java
|
UTF-8
| 548 | 1.828125 | 2 |
[] |
no_license
|
package com.example.HelloTabsMh;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
public class ListView extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] countries = getResources().getStringArray(R.array.countries_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));
getListView().setTextFilterEnabled(true);
}
}
|
JavaScript
|
UTF-8
| 710 | 3.546875 | 4 |
[] |
no_license
|
///VARIABLES///
var input = document.getElementById("tarea")
var boton = document.getElementById("boton")
var lista = document.getElementById("lista")
var limpiar = document.getElementById("limpiar")
console.log(tarea + boton + lista)
var inputs=document.getElementsByTagName("input")
console.log(inputs)
//FUNCIÓN//
function cargalista() {
var crearli = document.createElement("li")
crearli.innerHTML = input.value
lista.appendChild(crearli)
input.value=""
}
function cleanup() {
console.log(inputs);
var inputsArray = Array.from(inputs);
inputsArray.forEach(function(e)
{console.log(e)
e.value = ""
}
)
}
boton.addEventListener("click",cargalista)
limpiar.addEventListener("click",cleanup)
|
C++
|
UTF-8
| 9,362 | 2.640625 | 3 |
[] |
no_license
|
#include <pseudoc/ast/flow.hpp>
using namespace ast;
IfStatement::IfStatement(std::unique_ptr<Expression> condition, std::unique_ptr<Statement> on_true):
_condition(std::move(condition)),
_on_true(std::move(on_true))
{
}
IfStatement::IfStatement(std::unique_ptr<Expression> condition, std::unique_ptr<Statement> on_true, std::unique_ptr<Statement> on_false):
_condition(std::move(condition)),
_on_true(std::move(on_true)),
_on_false(std::move(on_false))
{
}
std::string IfStatement::print()
{
if (_on_false)
return "if (" + _condition->print() + ")\nthen "
+ _on_true->print() + "else "
+ _on_false->print();
else
return "if (" + _condition->print() + ")\nthen "
+ _on_true->print();
}
std::unique_ptr<irl::IrlSegment> IfStatement::code_gen(irl::Context context)
{
auto segment = std::make_unique<irl::IrlSegment>();
context.ph_true = _var_scope->new_placeholder(irl::LlvmAtomic::v);
context.ph_false = _var_scope->new_placeholder(irl::LlvmAtomic::v);
auto condition = _condition->code_gen(context);
for (auto& i: condition->instructions)
{
segment->instructions.push_back(std::move(i));
}
_var_scope->fix_placehoder(context.ph_true);
auto on_true = _on_true->code_gen(context);
_var_scope->fix_placehoder(context.ph_false);
if (!_on_false)
{
auto label_end = std::make_unique<irl::Label>(context.ph_false);
segment->instructions.push_back(std::make_unique<irl::JumpC>(std::move(condition->out_value), context.ph_false, context.ph_false));
segment->instructions.push_back(std::make_unique<irl::Label>(std::move(context.ph_true)));
for (auto& i: on_true->instructions)
{
segment->instructions.push_back(std::move(i));
}
segment->instructions.push_back(std::make_unique<irl::Jump>(context.ph_false));
segment->instructions.push_back(std::make_unique<irl::Label>(std::move(context.ph_false)));
return segment;
}
auto on_false = _on_false->code_gen(context);
auto ref_end = _var_scope->new_temp(irl::LlvmAtomic::v);
segment->instructions.push_back(std::make_unique<irl::JumpC>(std::move(condition->out_value), context.ph_true, context.ph_false));
segment->instructions.push_back(std::make_unique<irl::Label>(std::move(context.ph_true)));
for (auto& i: on_true->instructions)
{
segment->instructions.push_back(std::move(i));
}
segment->instructions.push_back(std::make_unique<irl::Jump>(ref_end));
segment->instructions.push_back(std::make_unique<irl::Label>(std::move(context.ph_false)));
for (auto& i: on_false->instructions)
{
segment->instructions.push_back(std::move(i));
}
segment->instructions.push_back(std::make_unique<irl::Jump>(ref_end));
segment->instructions.push_back(std::make_unique<irl::Label>(std::move(ref_end)));
return segment;
}
void IfStatement::set_variable_scope(std::shared_ptr<VariableScope> var_scope, std::shared_ptr<FunctionTable> ftable)
{
_condition->set_variable_scope(var_scope, ftable);
_on_true->set_variable_scope(var_scope, ftable);
if (_on_false)
_on_false->set_variable_scope(var_scope, ftable);
_var_scope = std::move(var_scope);
_ftable = std::move(ftable);
}
WhileLoop::WhileLoop(std::unique_ptr<Expression> condition, std::unique_ptr<Statement> body):
_condition(std::move(condition)),
_body(std::move(body))
{
}
std::string WhileLoop::print()
{
return "while (" + _condition->print()
+ ")\ndo " + _body->print();
}
std::unique_ptr<irl::IrlSegment> WhileLoop::code_gen(irl::Context context)
{
auto segment = std::make_unique<irl::IrlSegment>();
context.ph_true = _var_scope->new_placeholder(irl::LlvmAtomic::v);
context.ph_false = _var_scope->new_placeholder(irl::LlvmAtomic::v);
// prepare refs and code generation
auto ref_condition = _var_scope->new_temp(irl::LlvmAtomic::v);
auto condition = _condition->code_gen(context);
// auto ref_end = _var_scope->new_placeholder(irl::LlvmAtomic::v);
irl::Context lcontext;
lcontext.break_label = context.ph_false;
lcontext.continue_label = ref_condition;
_var_scope->fix_placehoder(context.ph_true);
auto body = _body->code_gen(lcontext);
_var_scope->fix_placehoder(context.ph_false);
// build code segment
segment->instructions.push_back(std::make_unique<irl::Jump>(ref_condition));
segment->instructions.push_back(std::make_unique<irl::Label>(ref_condition));
for (auto& i: condition->instructions)
{
segment->instructions.push_back(std::move(i));
}
segment->instructions.push_back(std::make_unique<irl::JumpC>(std::move(condition->out_value), context.ph_true, context.ph_false));
segment->instructions.push_back(std::make_unique<irl::Label>(std::move(context.ph_true)));
for (auto& i: body->instructions)
{
segment->instructions.push_back(std::move(i));
}
segment->instructions.push_back(std::make_unique<irl::Jump>(std::move(ref_condition)));
segment->instructions.push_back(std::make_unique<irl::Label>(std::move(context.ph_false)));
return segment;
}
void WhileLoop::set_variable_scope(std::shared_ptr<VariableScope> var_scope, std::shared_ptr<FunctionTable> ftable)
{
_condition->set_variable_scope(var_scope, ftable);
_body->set_variable_scope(var_scope, ftable);
_var_scope = std::move(var_scope);
_ftable = std::move(ftable);
}
ForLoop::ForLoop(std::unique_ptr<Statement> initializer, std::unique_ptr<Expression> condition, std::unique_ptr<Expression> increment, std::unique_ptr<Statement> body):
_initializer(std::move(initializer)),
_condition(std::move(condition)),
_increment(std::move(increment)),
_body(std::move(body))
{
}
std::string ForLoop::print()
{
return "for (" + _initializer->print() + " ; " + _condition->print() + " ; " + _increment->print()
+ ")\ndo " + _body->print();
}
void ForLoop::set_variable_scope(std::shared_ptr<VariableScope> var_scope, std::shared_ptr<FunctionTable> ftable)
{
_initializer->set_variable_scope(var_scope, ftable);
_condition->set_variable_scope(var_scope, ftable);
_increment->set_variable_scope(var_scope, ftable);
_body->set_variable_scope(var_scope, ftable);
_var_scope = std::move(var_scope);
_ftable = std::move(ftable);
}
std::unique_ptr<irl::IrlSegment> ForLoop::code_gen(irl::Context context)
{
auto segment = std::make_unique<irl::IrlSegment>();
context.ph_true = _var_scope->new_placeholder(irl::LlvmAtomic::v);
context.ph_false = _var_scope->new_placeholder(irl::LlvmAtomic::v);
// prepare refs and code generation
auto initializer = _initializer->code_gen(context);
auto ref_condition = _var_scope->new_temp(irl::LlvmAtomic::v);
auto condition = _condition->code_gen(context);
irl::Context lcontext;
lcontext.break_label = context.ph_false;
lcontext.continue_label = ref_condition;
_var_scope->fix_placehoder(context.ph_true);
auto body = _body->code_gen(lcontext);
auto ref_increment = _var_scope->new_temp(irl::LlvmAtomic::v);
auto increment = _increment->code_gen(context);
_var_scope->fix_placehoder(context.ph_false);
// build code segment
for (auto& i: initializer->instructions)
{
segment->instructions.push_back(std::move(i));
}
segment->instructions.push_back(std::make_unique<irl::Jump>(ref_condition));
segment->instructions.push_back(std::make_unique<irl::Label>(ref_condition));
for (auto& i: condition->instructions)
{
segment->instructions.push_back(std::move(i));
}
segment->instructions.push_back(std::make_unique<irl::JumpC>(std::move(condition->out_value), context.ph_true, context.ph_false));
segment->instructions.push_back(std::make_unique<irl::Label>(std::move(context.ph_true)));
for (auto& i: body->instructions)
{
segment->instructions.push_back(std::move(i));
}
segment->instructions.push_back(std::make_unique<irl::Jump>(ref_increment));
segment->instructions.push_back(std::make_unique<irl::Label>(ref_increment));
for (auto& i: increment->instructions)
{
segment->instructions.push_back(std::move(i));
}
segment->instructions.push_back(std::make_unique<irl::Jump>(std::move(ref_condition)));
segment->instructions.push_back(std::make_unique<irl::Label>(std::move(context.ph_false)));
return segment;
}
std::string Continue::print()
{
return "continue\n";
}
std::unique_ptr<irl::IrlSegment> Continue::code_gen(irl::Context context)
{
if (!context.continue_label)
throw std::logic_error("continue called outside a loop");
auto segment = std::make_unique<irl::IrlSegment>();
segment->instructions.push_back(std::make_unique<irl::Jump>(context.continue_label));
return segment;
}
std::string Break::print()
{
return "break\n";
}
std::unique_ptr<irl::IrlSegment> Break::code_gen(irl::Context context)
{
if (!context.break_label)
throw std::logic_error("break called outside a loop");
auto segment = std::make_unique<irl::IrlSegment>();
segment->instructions.push_back(std::make_unique<irl::Jump>(context.break_label));
return segment;
}
|
PHP
|
UTF-8
| 3,438 | 3.046875 | 3 |
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
namespace AppBundle;
use Dotenv\Dotenv;
use Dotenv\Loader;
use Respect\Validation\Validator as v;
/**
* Handles things that need to be secret by reading things from env.
*/
class Secrets
{
const MISSING_ENV_EXCEPTION_MESSAGE = 'Loading .env file failed while attempting to access environment variable ';
/**
* Returns the path that Dotenv should scan for a .env file.
*
* On Acquia, we need to handle their symlinky file system structure. On local
* dev we can simply dump our .env file into sites/all.
*
* @return string
* Path to the directory containing .env.
*/
public function dotEnvPath()
{
return __DIR__;
}
/**
* Sets an environment variable in a Dotenv compatible way.
*
* @param string $name
* The environment variable name to set.
*
* @param string $value
* The value of the environment variable to set.
*/
public function set($name, $value)
{
v::PhpLabel()->check($name);
v::stringType()->check($value);
// Get a mutable loader.
$loader = new Loader($this->dotEnvPath());
$loader->setEnvironmentVariable($name, $value);
}
/**
* Clears an environment variable in a Dotenv compatible way.
*
* @param string $name
* The environment variable to clear.
*
* @see https://github.com/vlucas/phpdotenv/issues/106
*/
public function clear($name)
{
v::PhpLabel()->check($name);
putenv($name);
unset($_ENV[$name]);
unset($_SERVER[$name]);
}
/**
* Gets environment variables, or dies trying.
*
* @param string $name
* The name of the environment variable to get.
*
* @return string
* The environment variable found.
*/
public function get($name)
{
v::PhpLabel()->check($name);
$loader = new Loader($this->dotEnvPath());
// If the environment variable is already set, don't try to use Dotenv
// as an exception will be thrown if a .env file cannot be found.
$value = $loader->getEnvironmentVariable($name);
if (!isset($value)) {
try {
// Attempt to load environment variables from .env if we didn't
// already have what we were looking for in memory.
$dotenv = new Dotenv($this->dotEnvPath());
$dotenv->load();
// Try once more to find what we're looking for before giving
// up. It is not possible to test this on infrastructure with
// .env missing and it is not possible to test the above
// exception where it is set. We have to ignore this for code
// coverage reports.
// @codeCoverageIgnoreStart
$value = $loader->getEnvironmentVariable($name);
if (!isset($value)) {
throw new \Exception(self::MISSING_ENV_EXCEPTION_MESSAGE . $name);
}
// Code coverage requires this return.
return $value;
// @codeCoverageIgnoreEnd
} catch (\Exception $e) {
// Provide a more useful message than the Dotenv default.
throw new \Exception(self::MISSING_ENV_EXCEPTION_MESSAGE . $name);
}
}
return $value;
}
}
|
Ruby
|
UTF-8
| 625 | 3.0625 | 3 |
[] |
no_license
|
# fm = "%{a} %{b} %{c} %{d}"
# puts fm % {a:"Hung", b:"cute", c:"qua troi", d:0326.to_s(8).to_i}
# tabby = "\tI'm \\tabie \r in."
# tabby2 = "\t*I'm \a \\ \\ \\ \f goodboy."
# puts %q{
# List options for you:
# 1- ABC
# 2- XYZ
# 3- XXX
# }
# puts tabby
# puts tabby2
puts "Chuong trinh thay boi"
print "Ban ten gi ? - "
name = gets.chomp
puts""
print "Ban sinh nam bao nhieu ? - "
age = gets.chomp.to_i
puts""
print "Ban thich mau gi ? - "
color_f = gets.chomp
puts "=========================Ket qua ne========================="
puts "Ban ten la #{name} nam nay da #{2020-age} tuoi va ban thich mau #{color_f}"
|
Java
|
UTF-8
| 5,957 | 2.765625 | 3 |
[] |
no_license
|
package template.geometry.geo2;
import java.util.function.Consumer;
public class IntegerTriangulation {
public IntegerTriangulation() {
this((long) 1e6);
}
/**
* @param LOTS 顶点xy数据范围
*/
public IntegerTriangulation(long LOTS) {
theRoot = newTriangle(new Triangle(new IntegerPoint2(-LOTS, -LOTS), new IntegerPoint2(+LOTS, -LOTS), new IntegerPoint2(0, +LOTS)));
}
static long sqr(long x) {
return x * x;
}
static long distSqr(IntegerPoint2 a, IntegerPoint2 b) {
return sqr(a.x - b.x) + sqr(a.y - b.y);
}
boolean inCircumcircle(IntegerPoint2 p1, IntegerPoint2 p2, IntegerPoint2 p3, IntegerPoint2 p4) {
//return IntegerPoint2.inCicle(p1, p2, p3, p4);
long u11 = p1.x - p4.x, u21 = p2.x - p4.x, u31 = p3.x - p4.x;
long u12 = p1.y - p4.y, u22 = p2.y - p4.y, u32 = p3.y - p4.y;
long u13 = sqr(p1.x) - sqr(p4.x) + sqr(p1.y) - sqr(p4.y);
long u23 = sqr(p2.x) - sqr(p4.x) + sqr(p2.y) - sqr(p4.y);
long u33 = sqr(p3.x) - sqr(p4.x) + sqr(p3.y) - sqr(p4.y);
long det = -u13 * u22 * u31 + u12 * u23 * u31 + u13 * u21 * u32 - u11 * u23 * u32 - u12 * u21 * u33 + u11 * u22 * u33;
return det > 0;
}
static long side(IntegerPoint2 a, IntegerPoint2 b, IntegerPoint2 p) {
return (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
}
public void forEach(Consumer<Triangle> consumer) {
version++;
dfs(consumer, theRoot);
}
int version;
private void dfs(Consumer<Triangle> consumer, Triangle root) {
if (root.version == version) {
return;
}
root.version = version;
if (!root.hasChildren()) {
consumer.accept(root);
return;
} else for (int i = 0; i < 3 && root.children[i] != null; ++i)
dfs(consumer, root.children[i]);
}
public static class Edge {
public Triangle tri;
public int side;
Edge() {
this(null, 0);
}
Edge(Triangle tri, int side) {
this.tri = tri;
this.side = side;
}
}
public static class Triangle {
public IntegerPoint2[] p = new IntegerPoint2[3];
public Edge[] edge = new Edge[3];
public Triangle[] children = new Triangle[3];
private int version;
Triangle() {
this(new IntegerPoint2(), new IntegerPoint2(), new IntegerPoint2());
}
Triangle(IntegerPoint2 p0, IntegerPoint2 p1, IntegerPoint2 p2) {
p[0] = p0;
p[1] = p1;
p[2] = p2;
for (int i = 0; i < 3; i++) {
edge[i] = new Edge();
}
children[0] = children[1] = children[2] = null;
}
public boolean hasChildren() {
return children[0] != null;
}
public int numChildren() {
return children[0] == null ? 0
: children[1] == null ? 1
: children[2] == null ? 2 : 3;
}
public boolean contains(IntegerPoint2 q) {
long a = side(p[0], p[1], q), b = side(p[1], p[2], q), c = side(p[2], p[0], q);
return a >= 0 && b >= 0 && c >= 0;
}
}
public Triangle newTriangle(Triangle t) {
return t;
}
void setEdge(Edge a, Edge b) {
if (a.tri != null) a.tri.edge[a.side] = b;
if (b.tri != null) b.tri.edge[b.side] = a;
}
public Triangle find(IntegerPoint2 p) {
version++;
return find(theRoot, p);
}
public void addPoint(IntegerPoint2 p) {
addPoint(find(p), p);
}
public Triangle theRoot = new Triangle();
Triangle find(Triangle root, IntegerPoint2 p) {
for (; ; ) {
if (root.version == version) {
throw new RuntimeException();
}
root.version = version;
if (!root.hasChildren()) return root;
else for (int i = 0; i < 3 && root.children[i] != null; ++i)
if (root.children[i].contains(p)) {
root = root.children[i];
break;
}
}
}
void addPoint(Triangle root, IntegerPoint2 p) {
Triangle tab, tbc, tca;
tab = newTriangle(new Triangle(root.p[0], root.p[1], p));
tbc = newTriangle(new Triangle(root.p[1], root.p[2], p));
tca = newTriangle(new Triangle(root.p[2], root.p[0], p));
setEdge(new Edge(tab, 0), new Edge(tbc, 1));
setEdge(new Edge(tbc, 0), new Edge(tca, 1));
setEdge(new Edge(tca, 0), new Edge(tab, 1));
setEdge(new Edge(tab, 2), root.edge[2]);
setEdge(new Edge(tbc, 2), root.edge[0]);
setEdge(new Edge(tca, 2), root.edge[1]);
root.children[0] = tab;
root.children[1] = tbc;
root.children[2] = tca;
flip(tab, 2);
flip(tbc, 2);
flip(tca, 2);
}
void flip(Triangle tri, int pi) {
Triangle trj = tri.edge[pi].tri;
int pj = tri.edge[pi].side;
if (trj == null || !inCircumcircle(tri.p[0], tri.p[1], tri.p[2], trj.p[pj])) return;
Triangle trk = newTriangle(new Triangle(tri.p[(pi + 1) % 3], trj.p[pj], tri.p[pi]));
Triangle trl = newTriangle(new Triangle(trj.p[(pj + 1) % 3], tri.p[pi], trj.p[pj]));
setEdge(new Edge(trk, 0), new Edge(trl, 0));
setEdge(new Edge(trk, 1), tri.edge[(pi + 2) % 3]);
setEdge(new Edge(trk, 2), trj.edge[(pj + 1) % 3]);
setEdge(new Edge(trl, 1), trj.edge[(pj + 2) % 3]);
setEdge(new Edge(trl, 2), tri.edge[(pi + 1) % 3]);
tri.children[0] = trk;
tri.children[1] = trl;
tri.children[2] = null;
trj.children[0] = trk;
trj.children[1] = trl;
trj.children[2] = null;
flip(trk, 1);
flip(trk, 2);
flip(trl, 1);
flip(trl, 2);
}
}
|
Java
|
UTF-8
| 1,636 | 2.25 | 2 |
[] |
no_license
|
package com.github.dagger2demo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.github.dagger2demo.component.DaggerLoginComponent;
import com.github.dagger2demo.module.LoginModule;
import com.github.dagger2demo.presenter.LoginPresenter;
import com.github.dagger2demo.view.ILoginView;
import javax.inject.Inject;
/**
* Created by boby on 2017/2/8.
*/
public class LoginActivity extends AppCompatActivity implements ILoginView {
//注入
@Inject
LoginPresenter mLoginPresenter;
EditText mEtUsername, mEtPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEtUsername = (EditText) findViewById(R.id.et_username);
mEtPassword = (EditText) findViewById(R.id.et_password);
DaggerLoginComponent.builder().loginModule(new LoginModule(this)).build().inject(this);
}
@Override
public void emptyData() {
Toast.makeText(this, getString(R.string.empty_data), Toast.LENGTH_SHORT).show();
}
@Override
public void loginFailed() {
Toast.makeText(this, getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
}
@Override
public void loginSuccess() {
Toast.makeText(this, getString(R.string.login_success), Toast.LENGTH_SHORT).show();
}
public void login(View view) {
mLoginPresenter.login(mEtUsername.getText().toString(), mEtPassword.getText().toString());
}
}
|
PHP
|
UTF-8
| 1,202 | 2.703125 | 3 |
[] |
no_license
|
<?php
class ApiGenerator
{
private $ipBDD;
private $usuarioBDD;
private $claveBDD;
public function __construct($ipBDD, $usuarioBDD, $claveBDD) {
$this->ipBDD = $ipBDD;
$this->usuarioBDD = $usuarioBDD;
$this->claveBDD = $claveBDD;
}
public function bases() {
$bdd = new BDD($this->ipBDD,$this->usuarioBDD, $this->claveBDD);
return $bdd->ejecutarConsulta('SHOW databases;',array());
}
public function tablas($args) {
$dataBase = $args['dataBase'];
$bdd2 = new BDD2($this->ipBDD,$this->usuarioBDD,$this->claveBDD,$dataBase);
$respuestaTablas = $bdd2->ejecutarConsulta('SHOW tables;',array());
$tablas = [];
foreach($respuestaTablas as $SelectTabla) {
$nombreTabla = $SelectTabla["Tables_in_".$dataBase];
array_push($tablas,["nombreTabla"=>$nombreTabla]);
}
return $tablas;
}
public function usuarios($args) {
$dataBase = $args['dataBase'];
$bdd2 = new BDD2($this->ipBDD,$this->usuarioBDD,$this->claveBDD,$dataBase);
$usuarios = $bdd2->ejecutarConsulta('SELECT * FROM Usuarios;',array());
return $usuarios;
}
}
|
C#
|
UTF-8
| 2,638 | 2.71875 | 3 |
[] |
no_license
|
using DAL.Conexion;
using FlamERPennyAPI_Entidades.Persistencia;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace FlamERPennyAPI_DAL.Manejadoras
{
public class ManejadoraVendedores
{
public static int insertarVendedor(Vendedor vendedor)
{
Connection conexion = new Connection();
int insertado;
SqlConnection sqlConnection = new SqlConnection();
SqlCommand command = null;
try
{
command = new SqlCommand();
sqlConnection = conexion.getConnection();
command.CommandText = "INSERT INTO Vendedores (Username) VALUES (@name)";
//Definicion de los parametros del comando
command.Parameters.AddWithValue("@name", vendedor.username);
command.Connection = sqlConnection;
//Ejecutar la consulta
insertado = command.ExecuteNonQuery();
}
catch(SqlException ex)
{
if (ex.Number == 2627)
insertado = -1;
else
throw ex;
}
finally
{
conexion.closeConnection(ref sqlConnection);
}
return insertado;
}
public static Vendedor vendedorPorNombre(string username)
{
//Variables de conexión
SqlConnection conexion = null;
SqlDataReader lector = null;
SqlCommand command = new SqlCommand();
Connection gestConexion = new Connection();
Vendedor vendedor = null;
//Datos de los clientes
int idCliente;
string nombreCliente;
try
{
//Conexión para obtener el cliente
conexion = gestConexion.getConnection();
command.CommandText = "SELECT Username FROM Vendedores WHERE Username = @username";
command.Parameters.AddWithValue("@username", username);
command.Connection = conexion;
lector = command.ExecuteReader();
if (lector.HasRows)
{
vendedor = new Vendedor(username);
}
}
catch (SqlException e) { throw e; }
finally
{
gestConexion.closeConnection(ref conexion);
if (lector != null)
lector.Close();
}
return vendedor;
}
}
}
|
Swift
|
UTF-8
| 21,803 | 2.65625 | 3 |
[] |
no_license
|
/*
* FieldPosition+BottomCameraContainer.swift
* GURobots
*
* Created by Callum McColl on 26/7/20.
* Copyright © 2020 Callum McColl. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgement:
*
* This product includes software developed by Callum McColl.
*
* 4. Neither the name of the author nor the names of contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* -----------------------------------------------------------------------
* This program is free software; you can redistribute it and/or
* modify it under the above terms or under the terms of the GNU
* General Public License as published by the Free Software Foundation;
* either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see http://www.gnu.org/licenses/
* or write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
import GUUnits
import GUCoordinates
extension FieldPositionContainer where Self: BottomCameraContainer {
// MARK: - Bottom Camera Visibility Of Objects On The Field
/// Can the camera see the object?
///
/// - Parameter coord: The location of the object on the field.
///
/// - Returns: True if the bottom camera can see the object, False
/// otherwise. Returns nil if `fieldPosition` is nil.
public func bottomCameraCanSee(object coord: CartesianCoordinate) -> Bool? {
guard let relativeCoordinate = self.relativeCoordinate(to: coord) else {
return nil
}
return self.bottomCameraCanSee(object: relativeCoordinate)
}
/// Can the camera see the object?
///
/// - Parameter coord: The location of the object on the field.
///
/// - Parameter camera: The camera index for the camera in the camera
/// pivots `cameraPivot.cameras` array.
///
/// - Returns: True if the bottom camera can see the object, False
/// otherwise. Returns nil if `fieldPosition` is nil.
public func bottomCameraCanSee(object coord: FieldCoordinate) -> Bool? {
guard let relativeCoordinate = self.relativeCoordinate(to: coord) else {
return nil
}
return self.bottomCameraCanSee(object: relativeCoordinate)
}
// MARK: Field Coordinates From Bottom Camera Image Coordinates
/// Calculate the position of an object in an image from the bottom camera
/// in relation to `fieldPosition`.
///
/// - Parameter coord: The pixel in the image representing the object.
///
/// - Returns: A new `CartesianCoordinate` calculated in relation to this
/// coordinate. Returns nil if `fieldPosition` is nil.
///
/// - Warning: Only use this function if you are positive that the pixel in
/// the image represented by `coord` is representing an object on the ground.
/// If this is not the case, then the maximum value for the distance will
/// be used.
public func bottomCameraCartesianCoordinate(at coord: CameraCoordinate) -> CartesianCoordinate? {
return self.fieldPosition.map { self.bottomCamera.cartesianCoordinate(at: coord, from: $0) }
}
/// Calculate the position of an object in an image from the bottom camera
/// in relation to `fieldPosition`.
///
/// - Parameter coord: The pixel in the image representing the object.
///
/// - Returns: A new `CartesianCoordinate` calculated in relation to this
/// coordinate. Returns nil if `fieldPosition` is nil.
///
/// - Warning: Only use this function if you are positive that the pixel in
/// the image represented by `coord` is representing an object on the ground.
/// If this is not the case, then the maximum value for the distance will
/// be used.
public func bottomCameraCartesianCoordinate(at coord: PixelCoordinate) -> CartesianCoordinate? {
return self.fieldPosition.map { self.bottomCamera.cartesianCoordinate(at: coord, from: $0) }
}
/// Calculate the position of an object in an image from the bottom camera
/// in relation to `fieldPosition`.
///
/// - Parameter coord: The point in the image representing the object.
///
/// - Returns: A new `CartesianCoordinate` calculated in relation to this
/// coordinate. Returns nil if `fieldPosition` is nil.
///
/// - Warning: Only use this function if you are positive that the point in
/// the image represented by `coord` is representing an object on the ground.
/// If this is not the case, then the maximum value for the distance will
/// be used.
public func bottomCameraCartesianCoordinate(at coord: PercentCoordinate) -> CartesianCoordinate? {
return self.fieldPosition.map { self.bottomCamera.cartesianCoordinate(at: coord, from: $0) }
}
/// Calculate the position of an object in an image from the bottom camera
/// in relation to `fieldPosition`.
///
/// - Parameter coord: The pixel in the image representing the object.
///
/// - Parameter heading: The direction in which the new coordinate
/// is facing.
///
/// - Returns: A new `FieldCoordinate` calculated in relation to this
/// coordinate. Returns nil if `fieldPosition` is nil.
///
/// - Warning: Only use this function if you are positive that the pixel in
/// the image represented by `coord` is representing an object on the ground.
/// If this is not the case, then the maximum value for the distance will
/// be used.
public func bottomCameraFieldCoordinate(at coord: CameraCoordinate, heading: Degrees_t) -> FieldCoordinate? {
return self.fieldPosition.map { self.bottomCamera.fieldCoordinate(at: coord, from: $0, heading: heading) }
}
/// Calculate the position of an object in an image from the bottom camera
/// in relation to `fieldPosition`.
///
/// - Parameter coord: The pixel in the image representing the object.
///
/// - Parameter heading: The direction in which the new coordinate
/// is facing.
///
/// - Returns: A new `FieldCoordinate` calculated in relation to this
/// coordinate. Returns nil if `fieldPosition` is nil.
///
/// - Warning: Only use this function if you are positive that the pixel in
/// the image represented by `coord` is representing an object on the ground.
/// If this is not the case, then the maximum value for the distance will
/// be used.
public func bottomCameraFieldCoordinate(at coord: PixelCoordinate, heading: Degrees_t) -> FieldCoordinate? {
return self.fieldPosition.map { self.bottomCamera.fieldCoordinate(at: coord, from: $0, heading: heading) }
}
/// Calculate the position of an object in an image from the bottom camera
/// in relation to `fieldPosition`.
///
/// - Parameter coord: The point in the image representing the object.
///
/// - Parameter heading: The direction in which the new coordinate
/// is facing.
///
/// - Returns: A new `FieldCoordinate` calculated in relation to this
/// coordinate. Returns nil if `fieldPosition` is nil.
///
/// - Warning: Only use this function if you are positive that the point in
/// the image represented by `coord` is representing an object on the ground.
/// If this is not the case, then the maximum value for the distance will
/// be used.
public func bottomCameraFieldCoordinate(at coord: PercentCoordinate, heading: Degrees_t) -> FieldCoordinate? {
return self.fieldPosition.map { self.bottomCamera.fieldCoordinate(at: coord, from: $0, heading: heading) }
}
// MARK: - Bottom Camera Image Coordinates From Field Coordinates
/// Calculate a pixel within a specific image from the bottom camera
/// representing an object at a given position.
///
/// - Parameter coord: The position of the object.
///
/// - Parameter resWidth: The width of the resolution of the image that
/// we are placing the object in.
///
/// - Parameter resHeight: The height of the resolution of the image that
/// we are placing the object in.
///
/// - Returns: A new `CameraCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
///
/// - Warning: This function does not check whether the calculated coordinate
/// is within the bounds of the `resWidth` and `resHeight`. As such you
/// should only use this function if you are positive that the camera can
/// actually see the object at `coord`.
public func bottomCameraCameraCoordinate(to coord: CartesianCoordinate, resWidth: Pixels_u, resHeight: Pixels_u) -> CameraCoordinate? {
return self.fieldPosition.map { self.bottomCamera.cameraCoordinate(to: coord, from: $0, resWidth: resWidth, resHeight: resHeight) }
}
/// Calculate a pixel within a specific image from the bottom camera
/// representing an object at a given position.
///
/// - Parameter coord: The position of the object.
///
/// - Parameter resWidth: The width of the resolution of the image that
/// we are placing the object in.
///
/// - Parameter resHeight: The height of the resolution of the image that
/// we are placing the object in.
///
/// - Returns: A new `CameraCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
///
/// - Warning: This function does not check whether the calculated coordinate
/// is within the bounds of the `resWidth` and `resHeight`. As such you
/// should only use this function if you are positive that the camera can
/// actually see the object at `coord`.
public func bottomCameraCameraCoordinate(to coord: FieldCoordinate, resWidth: Pixels_u, resHeight: Pixels_u) -> CameraCoordinate? {
return self.fieldPosition.map { self.bottomCamera.cameraCoordinate(to: coord, from: $0, resWidth: resWidth, resHeight: resHeight) }
}
/// Calculate a pixel within a specific image from the bottom camera
/// representing an object at a given position.
///
/// - Parameter coord: The position of the object.
///
/// - Parameter resWidth: The width of the resolution of the image that
/// we are placing the object in.
///
/// - Parameter resHeight: The height of the resolution of the image that
/// we are placing the object in.
///
/// - Returns: A new `PixelCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
///
/// - Warning: This function does not check whether the calculated coordinate
/// is within the bounds of the `resWidth` and `resHeight`. As such you
/// should only use this function if you are positive that the camera can
/// actually see the object at `coord`.
public func bottomCameraPixelCoordinate(to coord: CartesianCoordinate, resWidth: Pixels_u, resHeight: Pixels_u) -> PixelCoordinate? {
return self.fieldPosition.map { self.bottomCamera.pixelCoordinate(to: coord, from: $0, resWidth: resWidth, resHeight: resHeight) }
}
/// Calculate a pixel within a specific image from the bottom camera
/// representing an object at a given position.
///
/// - Parameter coord: The position of the object.
///
/// - Parameter resWidth: The width of the resolution of the image that
/// we are placing the object in.
///
/// - Parameter resHeight: The height of the resolution of the image that
/// we are placing the object in.
///
/// - Returns: A new `PixelCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
///
/// - Warning: This function does not check whether the calculated coordinate
/// is within the bounds of the `resWidth` and `resHeight`. As such you
/// should only use this function if you are positive that the camera can
/// actually see the object at `coord`.
public func bottomCameraPixelCoordinate(to coord: FieldCoordinate, resWidth: Pixels_u, resHeight: Pixels_u) -> PixelCoordinate? {
return self.fieldPosition.map { self.bottomCamera.pixelCoordinate(to: coord, from: $0, resWidth: resWidth, resHeight: resHeight) }
}
/// Calculate a point within a specific image from the bottom camera
/// representing an object at a given position.
///
/// - Parameter coord: The position of the object.
///
/// - Returns: A new `PercentCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
///
/// - Warning: This function does not check whether the calculated coordinate
/// is within the bounds of the `resWidth` and `resHeight`. As such you
/// should only use this function if you are positive that the camera can
/// actually see the object at `coord`.
public func bottomCameraPercentCoordinate(to coord: CartesianCoordinate) -> PercentCoordinate? {
return self.fieldPosition.map { self.bottomCamera.percentCoordinate(to: coord, from: $0) }
}
/// Calculate a point within a specific image from the bottom camera
/// representing an object at a given position.
///
/// - Parameter coord: The position of the object.
///
/// - Returns: A new `PercentCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
///
/// - Warning: This function does not check whether the calculated coordinate
/// is within the bounds of the `resWidth` and `resHeight`. As such you
/// should only use this function if you are positive that the camera can
/// actually see the object at `coord`. If you would like to use a version
/// of this function that performs this bounds check then use
/// `bottomCameraPercentCoordinate(to:)`.
public func bottomCameraPercentCoordinate(to coord: FieldCoordinate, camera: Int) -> PercentCoordinate? {
return self.fieldPosition.map { self.bottomCamera.percentCoordinate(to: coord, from: $0) }
}
/// Calculate a pixel within a specific image from the bottom camera
/// representing an object at a given position.
///
/// All calculated pixels that fall outside
/// the bounds of the image are moved to the edge of the image to ensure
/// that the function always calculates a coordinate within the image
/// bounds.
///
/// - Parameter coord: The position of the object.
///
/// - Parameter resWidth: The width of the resolution of the image that
/// we are placing the object in.
///
/// - Parameter resHeight: The height of the resolution of the image that
/// we are placing the object in.
///
/// - Returns: A new `CameraCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
public func bottomCameraClampedCameraCoordinate(to coord: CartesianCoordinate, resWidth: Pixels_u, resHeight: Pixels_u) -> CameraCoordinate? {
return self.fieldPosition.map { self.bottomCamera.clampedCameraCoordinate(to: coord, from: $0, resWidth: resWidth, resHeight: resHeight) }
}
/// Calculate a pixel within a specific image from the bottom camera
/// representing an object at a given position.
///
/// All calculated pixels that fall outside
/// the bounds of the image are moved to the edge of the image to ensure
/// that the function always calculates a coordinate within the image
/// bounds.
///
/// - Parameter coord: The position of the object.
///
/// - Parameter resWidth: The width of the resolution of the image that
/// we are placing the object in.
///
/// - Parameter resHeight: The height of the resolution of the image that
/// we are placing the object in.
///
/// - Returns: A new `CameraCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
public func bottomCameraClampedCameraCoordinate(to coord: FieldCoordinate, resWidth: Pixels_u, resHeight: Pixels_u) -> CameraCoordinate? {
return self.fieldPosition.map { self.bottomCamera.clampedCameraCoordinate(to: coord, from: $0, resWidth: resWidth, resHeight: resHeight) }
}
/// Calculate a pixel within a specific image from the bottom camera
/// representing an object at a given position.
///
/// All calculated pixels that fall outside
/// the bounds of the image are moved to the edge of the image to ensure
/// that the function always calculates a coordinate within the image
/// bounds.
///
/// - Parameter coord: The position of the object.
///
/// - Parameter resWidth: The width of the resolution of the image that
/// we are placing the object in.
///
/// - Parameter resHeight: The height of the resolution of the image that
/// we are placing the object in.
///
/// - Returns: A new `PixelCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
public func bottomCameraClampedPixelCoordinate(to coord: CartesianCoordinate, resWidth: Pixels_u, resHeight: Pixels_u) -> PixelCoordinate? {
return self.fieldPosition.map { self.bottomCamera.clampedPixelCoordinate(to: coord, from: $0, resWidth: resWidth, resHeight: resHeight) }
}
/// Calculate a pixel within a specific image from the bottom camera
/// representing an object at a given position.
///
/// All calculated pixels that fall outside
/// the bounds of the image are moved to the edge of the image to ensure
/// that the function always calculates a coordinate within the image
/// bounds.
///
/// - Parameter coord: The position of the object.
///
/// - Parameter resWidth: The width of the resolution of the image that
/// we are placing the object in.
///
/// - Parameter resHeight: The height of the resolution of the image that
/// we are placing the object in.
///
/// - Returns: A new `PixelCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
public func bottomCameraClampedPixelCoordinate(to coord: FieldCoordinate, resWidth: Pixels_u, resHeight: Pixels_u) -> PixelCoordinate? {
return self.fieldPosition.map { self.bottomCamera.clampedPixelCoordinate(to: coord, from: $0, resWidth: resWidth, resHeight: resHeight) }
}
/// Calculate a point within a specific image from the bottom camera
/// representing an object at a given position.
///
/// All calculated pixels that fall outside
/// the bounds of the image are moved to the edge of the image to ensure
/// that the function always calculates a coordinate within the image
/// bounds.
///
/// - Parameter coord: The position of the object.
///
/// - Returns: A new `PercentCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
public func bottomCameraClampedPercentCoordinate(to coord: CartesianCoordinate) -> PercentCoordinate? {
return self.fieldPosition.map { self.bottomCamera.clampedPercentCoordinate(to: coord, from: $0) }
}
/// Calculate a point within a specific image from the bottom camera
/// representing an object at a given position.
///
/// All calculated pixels that fall outside
/// the bounds of the image are moved to the edge of the image to ensure
/// that the function always calculates a coordinate within the image
/// bounds.
///
/// - Parameter coord: The position of the object.
///
/// - Returns: A new `PercentCoordinate` representing the object in the
/// camera. Returns nil if `fieldPosition` is nil.
public func bottomClampedPercentCoordinate(to coord: FieldCoordinate) -> PercentCoordinate? {
return self.fieldPosition.map { self.bottomCamera.clampedPercentCoordinate(to: coord, from: $0) }
}
}
|
PHP
|
UTF-8
| 242 | 2.578125 | 3 |
[] |
no_license
|
<?php
class LdapObjectNotWritableException extends Exception {
public function __construct(\Model $model, $dn, $parentDn) {
parent::__construct("Model: \"{$model->name}\" / DN: \"{$dn}\" / Parent DN: \"{$parentDn}\"");
}
}
|
Python
|
UTF-8
| 657 | 3.75 | 4 |
[] |
no_license
|
# encoding: utf-8
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
x = "{0:b}".format(x)
y = "{0:b}".format(y)
print x, y
if len(x) > len(y):
y = ''.join(['0' for _ in range(len(x)- len(y))]) + y
else:
x = ''.join(['0' for _ in range(len(y)- len(x))]) + x
count = 0
for e1, e2 in zip(x, y):
if e1 != e2:
count += 1
return count
if __name__ == '__main__':
ss = Solution()
print ss.hammingDistance(4, 1)
|
C
|
UTF-8
| 882 | 4.03125 | 4 |
[] |
no_license
|
#include <cs50.h>
#include <math.h>
#include <stdio.h>
void printSum(void); // declare the function
void printSums(int, int); // place holder
int squared(int);
bool isLeapYear(void)
int main(void)
{
const year = get_int("Enter a year: ");
if (isLeapYear(year))
}
int year = get_int("Enter a year: ");
if (isLeapYear(year))
{
printf("%i is a leap year.\n", year");
} else {
printf("%i is not a leap year\n", year)
}
}
bool is LeapYear(year)
{
return % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
int squared(num)
{
return num * num;
}
// isLeapYear - declare the variable = 1996, 2004, 2000, 1600
// return bool
// accepts int
// not divisible 100 = notLeapYear = 1997, 1998, 1999, 1800, 1900
// every 4 years - isLeapYear = 1996, 2004, 2000, 1600
// however is if divisible by 400 = yes
// 18%7 = R4
// 21%7 = R0
|
Markdown
|
UTF-8
| 992 | 2.75 | 3 |
[] |
no_license
|
# live php 简洁高效的PHP框架
## 框架核心只做了一件事: url地址到控制器方法的映射 支持多级控制器目录
- 默认地址:/index/index 对应 app/controller/index.php控制器 index方法
- /admin/user/list 对应 app/controller/admin/user.php控制器 list方法
- /home/user/index/userinfo 对应 app/controller/home/user/index.php控制器 userinfo方法
## 集成mysql操作
[ninvfeng/mysql](https://github.com/ninvfeng/mysql)
## 集成mongodb操作
[ninvfeng/mongodb](https://github.com/ninvfeng/mongodb)
## 集成数据验证
['think-validate'](https://github.com/top-think/think-validate)
## 封装get和post方法快速获取并验证请求参数
- $id=get('id','require','请输入ID');
- $username=post('username','require|min:6','请填写用户名且长度不少于6位');
## 适用场景
- 回归php简单的本质, 快速开始一个简单的项目
- 框架核心只有短短几十行, 特别适合学习如何快速搭建一个自己的框架
|
Java
|
UTF-8
| 1,486 | 2.296875 | 2 |
[] |
no_license
|
/**
*
*/
package thesis.nlp.core.process.export.tuple;
import java.util.LinkedHashSet;
import java.util.Set;
import thesis.nlp.models.AdverbPhrase;
import thesis.nlp.models.PrepositionalPhrase;
import thesis.nlp.util.StringProcessUtil;
/**
* @author lohuynh
*
*/
public class PrepPhraseStringConvert {
private static PrepPhraseStringConvert instance = null;
public static PrepPhraseStringConvert getInstance() {
if (instance == null) {
instance = new PrepPhraseStringConvert ();
}
return instance;
}
// public Set<String> prepPhraseStr (PrepositionalPhrase prepphrase)
// {
// if (prepphrase == null)
// return new LinkedHashSet<String>();
// Set<String> listOfPrepPhrase = new LinkedHashSet<String>();
// StringBuilder strBuilder = new StringBuilder();
// strBuilder.append(advphrase.getAdv());
// strBuilder.append(" ");
// strBuilder.append(StringProcessUtil.valueOf(advphrase.getNounPhrase()));
// listOfPrepPhrase.add(strBuilder.toString());
// if (advphrase.getListPrepPhrase().size() != 0)
// {
// String prepbuilder = strBuilder.toString();
// for (PrepositionalPhrase pp : advphrase.getListPrepPhrase())
// {
// strBuilder.append(" ");
// String prep = prepbuilder + " " + StringProcessUtil.valueOf(pp).trim();
// strBuilder.append(StringProcessUtil.valueOf(pp).trim());
// listOfPrepPhrase.add(prep.trim());
// }
//
// }
//
// return listOfPrepPhrase;
// }
}
|
PHP
|
UTF-8
| 2,963 | 2.765625 | 3 |
[] |
no_license
|
<?php
namespace App\Entity;
use App\Repository\SubjectRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=SubjectRepository::class)
*/
class Subject
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\Column(type="integer")
*/
private $code;
/**
* @ORM\Column(type="float")
*/
private $price;
/**
* @ORM\ManyToMany(targetEntity=Course::class, mappedBy="subject")
*/
private $courses;
/**
* @ORM\ManyToMany(targetEntity=Subject::class, inversedBy="subjects")
*/
private $subject;
/**
* @ORM\ManyToMany(targetEntity=Subject::class, mappedBy="subject")
*/
private $subjects;
public function __construct()
{
$this->courses = new ArrayCollection();
$this->subject = new ArrayCollection();
$this->subjects = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getCode(): ?int
{
return $this->code;
}
public function setCode(int $code): self
{
$this->code = $code;
return $this;
}
public function getPrice(): ?float
{
return $this->price;
}
public function setPrice(float $price): self
{
$this->price = $price;
return $this;
}
/**
* @return Collection|Course[]
*/
public function getCourses(): Collection
{
return $this->courses;
}
public function addCourse(Course $course): self
{
if (!$this->courses->contains($course)) {
$this->courses[] = $course;
$course->addSubject($this);
}
return $this;
}
public function removeCourse(Course $course): self
{
if ($this->courses->removeElement($course)) {
$course->removeSubject($this);
}
return $this;
}
/**
* @return Collection|self[]
*/
public function getSubject(): Collection
{
return $this->subject;
}
public function addSubject(self $subject): self
{
if (!$this->subject->contains($subject)) {
$this->subject[] = $subject;
}
return $this;
}
public function removeSubject(self $subject): self
{
$this->subject->removeElement($subject);
return $this;
}
/**
* @return Collection|self[]
*/
public function getSubjects(): Collection
{
return $this->subjects;
}
}
|
JavaScript
|
UTF-8
| 5,959 | 2.671875 | 3 |
[] |
no_license
|
const express = require('express');
const { rejectUnauthenticated } = require('../modules/authentication-middleware');
const encryptLib = require('../modules/encryption');
const pool = require('../modules/pool');
const userStrategy = require('../strategies/user.strategy');
const axios = require('axios');
const router = express.Router();
//function to create a uniqiue code for each user
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
const rejectNonAdmin = (req, res, next) => {
// check if logged in
if (req.user.role_id === 2) {
// They were authenticated! User may do the next thing
// Note! They may not be Authorized to do all things
next();
} else {
// failure best handled on the server. do redirect here.
res.sendStatus(403);
}
};
// Handles Ajax request for user information if user is authenticated
router.get('/', rejectUnauthenticated, (req, res) => {
// Send back user object from the session (previously queried from the database)
res.send(req.user);
});
// Handles POST request with new user data
// The only thing different from this and every other post we've seen
// is that the password gets encrypted before being inserted
router.post('/register', (req, res, next) => {
const username = req.body.username;
const password = encryptLib.encryptPassword(req.body.password);
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const phoneNumber = req.body.phoneNumber;
const streetAddress = req.body.streetAddress;
const city = req.body.city;
const state = req.body.state;
const queryText = 'INSERT INTO users (username, password, first_name, last_name, email, phone_number, street_address, city, state, authenticated, code, role_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING id';
pool.query(queryText, [username, password, firstName, lastName, email, phoneNumber, streetAddress, city, state, true, uuidv4(), 1])
.then(response => {
res.sendStatus(201);
})
.catch((err) => { next(err); });
});
router.get('/num/:id', (req, res) => {
let id = req.params.id;
axios.get(`http://apilayer.net/api/validate?access_key=${process.env.NUMVERIFY_API_KEY}&number=${id}&country_code=US&format=1`)
.then(response => {
res.send(response.data);
console.log(response.data);
})
.catch(error => {
console.log('Error with phone verification:', error);
res.sendStatus(500);
})
})
// Handles login form authenticate/login POST
// userStrategy.authenticate('local') is middleware that we run on this route
// this middleware will run our POST if successful
// this middleware will send a 404 if not successful
router.post('/login', userStrategy.authenticate('local'), (req, res) => {
res.sendStatus(200);
});
// clear all server session information about this user
router.post('/logout', (req, res) => {
// Use passport's built-in method to log out the user
req.logout();
res.sendStatus(200);
});
//Gets user info for the UserSettings page.
router.get('/info', rejectUnauthenticated, (req, res) => {
let id = req.user.id
pool.query('SELECT * FROM users WHERE id = $1;', [id])
.then(response => {
res.send(response.rows);
})
.catch(err => {
res.sendStatus(500);
console.log(err);
})
})
//not RESTful, but it gets the job done. GET instead of PUT, you cannot make put requests directly from the browser.
router.get('/attend/:id/:event', rejectNonAdmin, (req, res) => {
let code = req.params.id;
let eventId = req.params.event;
pool.query('UPDATE user_events SET attended = $1 FROM users WHERE users.id = user_events.users_id AND code = $2 AND user_events.events_id = $3;', [true, code, eventId])
.then(response => {
res.sendStatus(201);
})
.catch(err => {
res.sendStatus(500);
})
})
router.put('/update', rejectUnauthenticated, (req, res) => {
let username = req.body.username;
let firstName = req.body.firstName;
let lastName = req.body.lastName;
let email = req.body.email;
let streetAddress = req.body.streetAddress;
let city = req.body.city;
let state = req.body.state;
let id = req.user.id;
let queryText = 'UPDATE users SET (username, first_name, last_name, email, street_address, city, state) = ($1, $2, $3, $4, $5, $6, $7) WHERE id = $8;';
pool.query(queryText, [username, firstName, lastName, email, streetAddress, city, state, id])
.then(response => {
res.sendStatus(201);
})
.catch(err => {
res.sendStatus(500);
console.log(err);
})
})
router.get('/userList', rejectUnauthenticated, (req, res) => {
let queryText = `SELECT users.id,
users.first_name,
users.last_name,
users.email,
users.phone_number,
users.street_address,
users.username,
users.role_id FROM users;`;
pool.query(queryText)
.then(response => {
res.send(response.rows);
})
.catch(err => {
res.sendStatus(500);
console.log(err);
})
})
router.put('/changeRole', rejectNonAdmin, (req, res) => {
let user = req.body;
if(user.role_id === 2){
pool.query('UPDATE users SET role_id = $1 WHERE id = $2;', [1, user.id])
.then(response => {
res.sendStatus(201);
})
.catch(err => {
console.log(err);
res.sendStatus(500);
})
} else {
pool.query('UPDATE users SET role_id = $1 WHERE id = $2;', [2, user.id])
.then(response => {
res.sendStatus(201);
})
.catch(err => {
console.log(err);
res.sendStatus(500);
})
}
})
router.delete('/delete/:id', rejectNonAdmin, (req, res) => {
let id = req.params.id;
pool.query('DELETE FROM users WHERE id = $1;', [id])
.then(response => {
res.sendStatus(200);
})
.catch(err => {
res.sendStatus(500);
console.log(err);
})
})
module.exports = router;
|
Java
|
UTF-8
| 2,211 | 2.171875 | 2 |
[] |
no_license
|
package jp.co.willwave.aca.dto.api;
import jp.co.willwave.aca.model.entity.RouteDetailEntity;
import jp.co.willwave.aca.model.enums.CustomerType;
import jp.co.willwave.aca.utilities.WebUtil;
import lombok.Data;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Data
public class RouteDetailDTO {
private Long id;
private Long routesId;
private Long visitOrder;
private String iconMarker;
private Date arrivalTime;
private String arrivalNote;
private Date reDepartTime;
private Long customersId;
private String name;
private String address;
private String buildingName;
private String longtitude;
private String latitude;
private String description;
private Boolean finished = Boolean.FALSE;
private CustomerType customerType;
public void setIconMarker(String serverBaseUrl, String iconMarker) {
if (!StringUtils.isEmpty(iconMarker)) {
this.iconMarker = WebUtil.combineUrl(serverBaseUrl, iconMarker);
}
}
public static RouteDetailDTO fromEntity(RouteDetailEntity entity) {
RouteDetailDTO dto = new RouteDetailDTO();
dto.setRoutesId(entity.getRoutesId());
dto.setVisitOrder(entity.getVisitOrder());
dto.setArrivalTime(entity.getArrivalTime());
dto.setArrivalNote(entity.getArrivalNote());
dto.setReDepartTime(entity.getReDepartTime());
dto.setCustomersId(entity.getCustomers().getId());
dto.setName(entity.getCustomers().getName());
dto.setAddress(entity.getCustomers().getAddress());
dto.setBuildingName(entity.getCustomers().getBuildingName());
dto.setLongtitude(entity.getCustomers().getLongitude());
dto.setLatitude(entity.getCustomers().getLatitude());
dto.setDescription(entity.getCustomers().getDescription());
dto.setCustomerType(entity.getCustomers().getCustomerType());
return dto;
}
public static List<RouteDetailDTO> fromEntity(List<RouteDetailEntity> entities) {
return entities.stream().map(entity -> RouteDetailDTO.fromEntity(entity)).collect(Collectors.toList());
}
}
|
Java
|
UTF-8
| 590 | 2.328125 | 2 |
[] |
no_license
|
package com.nayan.SpringStuff;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.nayan.beans.HelloWord;
import com.nayan.components.Employee;
public class App {
public static void main(String a[]){
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module.xml");
HelloWord obj = (HelloWord) context.getBean("helloBean");
obj.printHello();
Employee e1 = (Employee) context.getBean("employee");
System.out.println(e1);
}
}
|
Java
|
UTF-8
| 30,424 | 1.734375 | 2 |
[] |
no_license
|
/**
* @author Jason Gossit
* @version 1.0, 04/30/13
*/
package jgossit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class GarminActivityCompare {
PrintWriter printWriter;
String title;
String activityDir = null;
String[] activityFilenames = { "", "" };
String[] activityNames = { "", "" };
String[] activityTimes = { "", "" };
SimpleDateFormat gpxTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
SimpleDateFormat filenameTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
{
gpxTimeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
filenameTimeFormat.setTimeZone(TimeZone.getDefault());
}
// originals from http://www.benjaminkeen.com/google-maps-coloured-markers/
// converted with http://websemantics.co.uk/online_tools/image_to_data_uri_convertor/
String markerAImageData = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAiCAYAAABfqvm9AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAATcSURBVHjaYmTADeSB2AWI9YGYDyr2BYgvAfFeIL6LTRNAADFiEeMC4nIgzmRl5xYVktJm4BGQZWBgZGT4+uEJw9unVxh+//zyDig/C4jbgPgzsmaAAEI3UBGI13DzSxrpOxcxqJpG/ucTkmZgZmQAq/v7n+H/5/fPGe6eX814fncPw5d3j68ChUOA+AbMAIAAQjZQBYj3y2q5ybglLfvPzy/M+Oc/0JB/qDYyATErM9DvXz8y7F4Qz3D/wsZXQCFnIL4CkgcIIJiBnEB8VFbT3dA/bxMDEyMbw18G/ABoJsP//38Zts4KZbh3fj3IheZA/AkggJig8mXcAtKGHimL/2Mz7MiqAob1fQ4Mn98+gIuB1DAyMzO4Jcz/zyeipAHk1oLEAQIIZJEkEE8z927kV9J2Zvz9H9UwkCG75kYC6Ydgvpy2B1zuP1AtJzsHIxMbF8P9S5tVQeEPEEAgFzqwsHLJqpqGMfz+h+m1exc2gGl9p3yG68cXYMiD9CgbBv1n5xIUBYUlQACBDDQWktJk4AXG5r//mAZe3DuBQVHfn0HDMoHh1/ePDDfQDAXp4eIWZhSW1gVxdQACCGSgMDc/OGlggDePLzB8fvcQbJiIrAHQUnmwBeiACWgKj6AMiMkPEEDgSGFkYsQakxf3QTSzcwkwPL11gEFa3YHhzZOLYIswcggjxAyAAGIB4vdf3j0FJVoU8PPbB3j4behzxLDIOR7hdZDWL++fgJifAAIIZOCZ9y+vAwWeMXDxSzHAzL1/cQM4zMKrz4O9CwPbpgeALbIJ/QB2OchdXz+9+//mySUQ8wpAAIG8fPD3z6/P7p5fx8DCjHAFKEZBYYZsGAjAIgdkIdiLQBPuX97E+PPb+7egnAYQQCADnwLx7DM7Oxm+f/v4H+ZdcFJxLsAIKyWDAHCsg8MRqPrnz8//T29rBUmBwuAOQADBYoMHiE8q6gdo+WSu/f+PAUcsoWc/Job/O+ZEM946tewekGsKxO8AAgjmyV+gMu7DyxtB71/e5lMzCQbnAnwA5NU9i9IYbxxf+AbI9QJicL4ECCCkUGMAhcGBd8+uRALTEbuipj1GSYNs2Pm9kxnObG/9AeT6APFpmBxAADGjqX0OiuCnNw+GSKraMwiJKmDkHpBhb55e+b9jdgTjv7+/84FCa5HlAQKICYsDVgJDe8nBFbkMv379+I8tMI+sLWf88+vbflChgi4HEEBMOIKoFljUf7x8cAYjK5IfQOx7l7YxPLyyDcStwaYRIIBwGQgK4FkX901i+PHjO9yVwOgH5pKJIOYWID6GTSNAADHhicjJn97e//Lg8lZGULgxg8Lu+TWGx9f3gOVwaQIIIHwGPgbiTTdPLYHEHtCZd86uASanf6BqdBcuTQABxEQg7a55ducww9ev7xn+Ab0LdC1IbBM+DQABRMjAwz++vPv4+tEFhq9f3gCTy0Vw+YBPA0AAsRAwEJQLLr95ct6GEWj1398/X0BbDjgBQACxEJFlzwKTkM3f36DcyXAZVFrhUwwQQMQYePXjqzvAIusTAyHXgQBAABFj4MPP7x4xfPv0ElxMElIMEEDEGPjm68fnsHrnESHFAAFEjIGf//399R/YVACZ+ImQYoAAYiLCwI9A/A2piMMLAAKIhUgDn0EbVK8JKQYIMABhubHIul5+4wAAAABJRU5ErkJggg==";
String markerBImageData = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAiCAYAAABfqvm9AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAATkSURBVHjaYmTADeSB2AWI9YGYDyr2BYgvAfFeIL6LTRNAADFiEeMC4nIgzmTnYhOV0hBlEJDmY2AEqvzw7DPD0+uvGH5+/fUOKD8LiNuA+DOyZoAAQjdQEYjX8IvzGjlnmTOYBGn/F5YUABrGDFb3///f/+9ffmI4v/Ea466pxxneP/10FSgcAsQ3YAYABBCygSpAvF/LUUkmaVbQf34hfsb/DH8Z/v7/i+YlJgZmRhaGrx+/MMzP3sBwcfvNV0BhZyC+ApIHCCCYgZxAfFTTUckwd1k0AzMbM8M/NIPQARMjUM3f/wyzElcynN96A+RCcyD+BBBAMAPrBSR5G2oOZPznFeFmBBl2fPlFMEYGwnICDGGtbgyc/BxgPjPQ0O+ffv5vcpjO+Pbhhx6gUClAADEBCUkgTnbOsmTgF+FjhLns7eMPDLePPWRQs5EHY1ldcYaL224wVBtOglsACg4uPi5GrwJbEDceFAcAAcQCJBzYOFllTQO0gd78g+E1nzJ7OFvNWoFhRtwqhidXXjDI6EiAxUB6DH00/69t2C367eMPZ4AAArnQWEJNhEFIip/hHxDiAxe23YR4XVYALgbSwy3EzSilJQbi6gAEEMiFwsDwA8YeM8gTGIZkijSj8ENbEGEIjyAgFJQCp31+gABiAUc1IyNOV3mX2cHZF7feZFhds4tBRlcC6H151OQENQMggEAGvv/w/DPDfwbsyQQ5DEHsIqUucOyjGvif4f2zTyDGJ4AAAoXhmRe33jC8f/4J6G1GvGH4/eMPUDJh4OJnR0rojAyf3n/5//TqSxD3CkAAgVx48Oe3X8/Ob7ku5ZxqyfDn/28UQ/r8FsHZoKQEApaR+kgJnIXh0vabjMAYfgvKaQABBHLhUyCevWPSEYZvn779hydiYEyqWqGGk4GXOkPhxjh4kgGBn19+/N/WdwjEXADEdwACCOZHHiA+qe+lrpW5MOL/f8Z/+P0OBcCc8n922hrG02uv3ANyTYH4HUAAMUPlfoHKuJe33wa9uPuGz9RPBxjM/wkYxsKwsGAj44kVl94AuV5A/AAkDhBAzEhqQGFw4Nn115HAFMCuaaMKTLJ/cRq2d9Zxhu19R36AIh+IT8PkAAKIGU3tcyC+f/PYgxBVKzkGMXkRoDv/YRj29PrL/7NT1jD+/fMvHyi0FlkeIICYsDhgJdCUJSsrtjP8/PHzP7aktLZhF+Ov77/3A5nT0OUAAogJRxDVAov6j4fmnwGW1axwQRYg+9LumwxX9twBcWuwaQQIIFwGggJ41r5ZJxm+f/8Od+U/oNP3zTwJYm4B4mPYNAIEEBOeiJz89tGHL1d23WYEJV5QYfrsxkuG6wfvgeVwaQIIIHwGPgbiTSdXX4JmMWaGc5uuMfz/9x8ksAuXJoAAYiKQdtfcOf6I4euHL+By7/Lu2yCxTfg0AAQQIQMPf/3w/eOjyy8Yvrz9Ai6pgWAbPg0AAcRCwEBQLrj85PILG1C0/Pn19wW05YATAAQQCxFZ9iwwCdn8/gXONZeB+Cs+xQABRIyBV1/de8fw/fNPBkKuAwGAACLGwIfvnnxk+Pwa7LDrhBQDBBAxBr758PIzsCAFJ+5HhBQDBBAxBn7+9/vf/38M4OzyiZBigABiIsLAj0D8DamIwwsAAoiFSAOfQRtUrwkpBggwAK1GpdpHAecTAAAAAElFTkSuQmCC";
public static void main(String[] args) throws IOException, ParseException
{
new GarminActivityCompare().go();
}
@SuppressWarnings("unchecked")
private void go() throws IOException, ParseException
{
promptForActivities();
System.out.println("Creating comparison file...");
ArrayList<Double>[] lats = new ArrayList[activityFilenames.length];
ArrayList<Double>[] lons = new ArrayList[activityFilenames.length];
ArrayList<Double>[] distancesTravelled = new ArrayList[activityFilenames.length];
ArrayList<String> htmlContent = new ArrayList<String>();
for (int i=0; i<activityFilenames.length; i++)
{
lats[i] = new ArrayList<Double>();
lons[i] = new ArrayList<Double>();
distancesTravelled[i] = new ArrayList<Double>();
BufferedReader bufferedReader = new BufferedReader(new FileReader(activityDir + activityFilenames[i]));
String line = null;
boolean reachedStart = false;
Date prevTime = null;
Double lat = null, prevLat = null;
Double lon = null, prevLon = null;
while ((line = bufferedReader.readLine()) != null)
{
if (line.contains("<trk>"))
reachedStart = true;
if (!reachedStart)
continue;
if (line.contains("<time>"))
{
String time = line.substring(line.indexOf("<time>")+6,line.indexOf("</time>"));
Date thisTime = gpxTimeFormat.parse(time);
if (prevTime != null)
{
long diff = thisTime.getTime()-prevTime.getTime();
if (diff > 1000)
{
double latDiff = lat - prevLat;
double latDiffIncr = latDiff / (diff / 1000);
double lonDiff = lon - prevLon;
double lonDiffIncr = lonDiff / (diff / 1000);
for (int j=1;j<diff/1000;j++)
{
lats[i].add(prevLat + j*latDiffIncr);
lons[i].add(prevLon + j*lonDiffIncr);
}
}
lats[i].add(lat);
lons[i].add(lon);
}
prevTime = thisTime;
}
else if (line.contains("<trkpt"))
{
if (lon != null)
{
prevLon = lon;
prevLat = lat;
}
lon = Double.parseDouble(line.substring(line.indexOf("lon")+5, line.indexOf("lat")-2));
lat = Double.parseDouble(line.substring(line.indexOf("lat")+5, line.indexOf(">")-1));
if (prevTime == null)
{
lats[i].add(lat);
lons[i].add(lon);
}
}
}
bufferedReader.close();
}
int[] activityOrder = (lats[0].size() >= lats[1].size() ? new int[]{0,1} : new int[]{1,0}); // longest activity first
File outputFile = new File(activityDir + activityNames[activityOrder[0]] + " - " + activityTimes[activityOrder[0]] + ".html");
if (outputFile.exists())
outputFile.delete();
printWriter = new PrintWriter(outputFile);
for(int i=0;i<activityOrder.length;i++)
{
/*htmlContent.add(" var coords" + (i+1) + " = [\n");
for (int j=0;j<lats[activityOrder[i]].size();j++)
{
htmlContent.add(String.format("\t\tnew google.maps.LatLng(%s, %s)%s\n",
lats[activityOrder[i]].get(j),
lons[activityOrder[i]].get(j),
j+1 < lats[activityOrder[i]].size() ? "," : "];\n"));
}*/
htmlContent.add(" var lats" + (i+1) + " = [ ");
for (int j=0;j<lats[activityOrder[i]].size();j++)
{
htmlContent.add(String.format("%s%s%s",
lats[activityOrder[i]].get(j),
j+1 < lats[activityOrder[i]].size() ? "," : "];\n",
j > 0 && j % 10 == 0 ? "\n\t\t" : ""));
}
htmlContent.add(" var lons" + (i+1) + " = [ ");
for (int j=0;j<lons[activityOrder[i]].size();j++)
{
htmlContent.add(String.format("%s%s%s",
lons[activityOrder[i]].get(j),
j+1 < lons[activityOrder[i]].size() ? "," : "];\n",
j > 0 && j % 10 == 0 ? "\n\t\t" : ""));
}
htmlContent.add(" var distance" + (i+1) + " = [ ");
double distance = 0;
for (int j=1;j<lats[activityOrder[i]].size();j++)
{
distance += GarminActivityCompare.distanceBetween(lats[activityOrder[i]].get(j), lons[activityOrder[i]].get(j),
lats[activityOrder[i]].get(j-1), lons[activityOrder[i]].get(j-1));
distancesTravelled[activityOrder[i]].add(distance);
htmlContent.add(String.format("%.3f%s%s",
distance,
j+1 < lats[activityOrder[i]].size() ? "," : "];\n",
j % 10 == 0 ? "\n\t\t" : ""));
}
htmlContent.add(" var pace" + (i+1) + " = [ 0, ");
for (int j=0;j<distancesTravelled[activityOrder[i]].size();j++)
{
Double distanceNow = distancesTravelled[activityOrder[i]].get(j);
int timeFrame = j < 10 ? j+1 : 10;
Double distanceBefore = j < 10 ? 0 : distancesTravelled[activityOrder[i]].get(j - timeFrame);
Double pace = 3600 * ((distanceNow-distanceBefore)/timeFrame);
htmlContent.add(String.format("%.1f%s%s",
pace,
j+1 < distancesTravelled[activityOrder[i]].size() ? "," : "];\n",
j > 0 && j % 10 == 0 ? "\n\t\t" : ""));
}
}
// instead of comparing difference in A and B distance travelled at the same point in time, as the devices may vary,
// find the closest point in B and work out how far it has travelled from there to it's current point
htmlContent.add(" var gap = [ ");
int lastTrkPoint = 0; // remember where the last point was to avoid starting all over again or matching the wrong lap if there are several laps
int lookAhead = 0; // so it doesn't get tripped up on turnarounds/loops
for (int trkPointA=0; trkPointA<lats[activityOrder[0]].size(); trkPointA++)
{
double lat = lats[activityOrder[0]].get(trkPointA);
double lon = lons[activityOrder[0]].get(trkPointA);
double smallestDistance = 999999;
int lookedAhead = 0;
for (int trkPointB=lastTrkPoint; trkPointB<lons[activityOrder[1]].size(); trkPointB++)
{
double distance = GarminActivityCompare.distanceBetween(lat, lon, lats[activityOrder[1]].get(trkPointB), lons[activityOrder[1]].get(trkPointB));
if (smallestDistance == 999999)
{
smallestDistance = distance;
continue;
}
if (distance < smallestDistance)
{
smallestDistance = distance;
}
else if (lookedAhead < lookAhead)
{
lookedAhead++;
}
else
{
if (trkPointB-1 == lastTrkPoint) // matched same point as last time, look ahead further next time in case it's getting stuck
lookAhead++;
else
lookAhead = 0;
lastTrkPoint = trkPointB-1;
break;
}
}
// more trkPoint's in A than B = A took longer, B is probably at the finish line, use B's last trkPoint
// (although sampling frequency could differ...)
int currentTrkPointB = trkPointA >= distancesTravelled[activityOrder[1]].size() ? distancesTravelled[activityOrder[1]].size()-1 : trkPointA;
int closestTrkPointB = lastTrkPoint == distancesTravelled[activityOrder[1]].size() ? lastTrkPoint-1 : lastTrkPoint;
double distance = -1 * (distancesTravelled[activityOrder[1]].get(currentTrkPointB) - distancesTravelled[activityOrder[1]].get(closestTrkPointB));
htmlContent.add(String.format("%.3f%s%s",
distance,
trkPointA+1 < lats[activityOrder[0]].size() ? "," : "];\n",
trkPointA > 0 && trkPointA % 10 == 0 ? "\n\t\t" : ""));
}
title = outputFile.getName().substring(0,outputFile.getName().length()-5);
printHeader(lats[activityOrder[0]].size());
for (String htmlLine : htmlContent)
printWriter.print(htmlLine);
printFooter();
printWriter.close();
System.out.format("Comparison file created at '%s'", outputFile.getAbsolutePath());
}
private void promptForActivities() throws IOException, ParseException
{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
while (activityDir == null)
{
System.out.println("Enter the directory containing the Garmin Activity (.gpx) files:");
String activityDirInput = inputReader.readLine();
File testActivityDir = new File(activityDirInput);
if (!testActivityDir.exists())
{
System.err.println("'" + activityDirInput + "' does not exist");
continue;
}
else if (!testActivityDir.isDirectory())
{
System.err.println("'" + activityDirInput + "' is not a directory");
continue;
}
else
{
File[] activityFiles = testActivityDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".gpx");
}
});
if (activityFiles.length < 2)
{
System.err.println("'" + activityDirInput + "' does not contain at least 2 activity files");
continue;
}
String[] names = new String[activityFiles.length];
String[] times = new String[activityFiles.length];
activityDir = activityDirInput + File.separator;
for (int i=0; i<activityFiles.length; i++)
{
String line = null;
BufferedReader bufferedReader = new BufferedReader(new FileReader(activityFiles[i]));
while ((line = bufferedReader.readLine()) != null)
{
if (line.contains("<time>"))
{
String time = line.substring(line.indexOf("<time>")+6,line.indexOf("</time>"));
Date date = gpxTimeFormat.parse(time);
times[i] = filenameTimeFormat.format(date);
}
if (line.contains("<name>"))
{
names[i] = line.substring(line.indexOf("<name>")+6, line.indexOf("</name>"));
System.out.format("[%s]: %s - %s (%s)\n", i,
activityFiles[i].getName(),
times[i],
names[i]);
break;
}
else
continue;
}
bufferedReader.close();
}
int[] activityNumbers = {0,1};
while (true)
{
System.out.println("Enter the numbers of the activity files to compare: (default 0,1)");
String activityNumbersInput = inputReader.readLine();
if (activityNumbersInput.trim().equals(""))
break;
String[] activityNumbersArray = activityNumbersInput.split(",");
try
{
if (activityNumbersArray.length != 2)
throw new Exception();
if (Integer.parseInt(activityNumbersArray[0]) >= activityFiles.length ||
Integer.parseInt(activityNumbersArray[1]) >= activityFiles.length)
throw new Exception();
activityNumbers[0] = Integer.parseInt(activityNumbersArray[0]);
activityNumbers[1] = Integer.parseInt(activityNumbersArray[1]);
break;
}
catch(Exception e)
{
System.err.println("Invalid entry");
continue;
}
}
for (int i=0;i<activityNumbers.length;i++)
{
activityFilenames[i] = activityFiles[activityNumbers[i]].getName();
activityNames[i] = names[activityNumbers[i]];
activityTimes[i] = times[activityNumbers[i]];
}
}
}
}
private void printHeader(int numPoints)
{
printWriter.println("<!DOCTYPE html>");
printWriter.println("<html>");
printWriter.println("<title>" + title + "</title>");
printWriter.println(" <head>");
printWriter.println(" <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>");
printWriter.println(" <meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\" />");
printWriter.println(" <style type=\"text/css\">");
printWriter.println(" html { height: 100% }");
printWriter.println(" body { height: 100%; margin: 0; padding: 0 }");
printWriter.println(" #map-canvas { height: 100% }");
printWriter.println(" #toolbar {");
printWriter.println(" padding: 4px;");
printWriter.println(" display: inline-block;");
printWriter.println(" }");
printWriter.println(" .small-font {");
printWriter.println(" font-family: 'Trebuchet MS','Helvetica','Arial','Verdana','sans-serif';");
printWriter.println(" font-size: 62.5%;");
printWriter.println(" }");
printWriter.println(" </style>");
printWriter.println(" <link type=\"text/css\" href=\"http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css\" rel=\"Stylesheet\"/>");
printWriter.println(" <script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.9.1.js\"></script>");
printWriter.println(" <script type=\"text/javascript\" src=\"http://code.jquery.com/ui/1.10.2/jquery-ui.js\"></script>");
printWriter.println(" <script>");
printWriter.println(" $(function() {");
printWriter.println(" $( \"#play\" ).button({");
printWriter.println(" text: false,");
printWriter.println(" icons: {");
printWriter.println(" primary: \"ui-icon-play\"");
printWriter.println(" }");
printWriter.println(" })");
printWriter.println(" .click(function() {");
printWriter.println(" var options;");
printWriter.println(" if ( $( this ).text() === \"play\" ) {");
printWriter.println(" options = {");
printWriter.println(" label: \"pause\",");
printWriter.println(" icons: {");
printWriter.println(" primary: \"ui-icon-pause\"");
printWriter.println(" }");
printWriter.println(" };");
printWriter.println(" play();");
printWriter.println(" } else {");
printWriter.println(" options = {");
printWriter.println(" label: \"play\",");
printWriter.println(" icons: {");
printWriter.println(" primary: \"ui-icon-play\"");
printWriter.println(" }");
printWriter.println(" };");
printWriter.println(" pause();");
printWriter.println(" }");
printWriter.println(" $( this ).button( \"option\", options );");
printWriter.println(" });");
printWriter.println(" ");
printWriter.println(" $( \"#stop\" ).button({");
printWriter.println(" text: false,");
printWriter.println(" icons: {");
printWriter.println(" primary: \"ui-icon-stop\"");
printWriter.println(" }");
printWriter.println(" })");
printWriter.println(" .click(function() {");
printWriter.println(" $( \"#play\" ).button( \"option\", {");
printWriter.println(" label: \"play\",");
printWriter.println(" icons: {");
printWriter.println(" primary: \"ui-icon-play\"");
printWriter.println(" }");
printWriter.println(" });");
printWriter.println(" stop();");
printWriter.println(" });");
printWriter.println(" ");
printWriter.println(" $( \"#slider\" ).slider({ orientation: \"horizontal\", range: \"min\", animate: true, min: 0, max: " + (numPoints-1) + " });");
printWriter.println(" $( \"#slider\" ).on( \"slidestart\", function( event, ui ) {");
printWriter.println(" pauseFromSlide();");
printWriter.println(" } );");
printWriter.println(" $( \"#slider\" ).on( \"slidestop\", function( event, ui ) {");
printWriter.println(" playFromSlide();");
printWriter.println(" } );");
printWriter.println(" $( \"#slider\" ).on( \"slide\", function( event, ui ) {");
printWriter.println(" slide(ui.value);");
printWriter.println(" } );");
printWriter.println(" ");
printWriter.println(" $( \"#speedSlider\" ).slider({ orientation: \"horizontal\", range: \"min\", animate: true, value: 50, min: 10, max: 90 });");
printWriter.println(" $( \"#speedSlider\" ).on( \"slide\", function( event, ui ) {");
printWriter.println(" changeSpeed(ui.value);");
printWriter.println(" } );");
printWriter.println(" });");
printWriter.println(" </script>");
printWriter.println(" <script type=\"text/javascript\"");
printWriter.println(" src=\"https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry\">");
printWriter.println(" </script>");
printWriter.println(" <script type=\"text/javascript\"");
printWriter.println(" src=\"http://google-maps-utility-library-v3.googlecode.com/svn/tags/infobox/1.1.12/src/infobox.js\">");
printWriter.println(" </script>");
printWriter.println(" <script type=\"text/javascript\">");
printWriter.println(" var map;");
printWriter.println(" var updateDistance = 0;");
printWriter.println(" var marker1;");
printWriter.println(" var coords1;");
printWriter.println(" var coords2;");
printWriter.println(" var marker1;");
printWriter.println(" var marker2;");
printWriter.println(" var paused = true;");
printWriter.println(" var resume = false;");
printWriter.println(" var speed = 50;");
printWriter.println(" var position1 = 0;");
printWriter.println(" var position2 = 0;");
printWriter.println(" var infoBox;");
printWriter.println(" var infoBoxClearance = 175;");
printWriter.println(" var upArrow = '<font color=\"green\">▲</font>';");
printWriter.println(" var neutral = '▬';");
printWriter.println(" var downArrow = '<font color=\"red\">▼</font>';");
printWriter.println(" var lastGap = 0;");
}
private void printFooter()
{
printWriter.println(" function initialize()");
printWriter.println(" {");
printWriter.println(" coords1 = new google.maps.MVCArray();");
printWriter.println(" for (i=0; i<lats1.length; i++)");
printWriter.println(" {");
printWriter.println(" coords1.push(new google.maps.LatLng(lats1[i], lons1[i]));");
printWriter.println(" }");
printWriter.println(" coords2 = new google.maps.MVCArray();");
printWriter.println(" for (i=0; i<lats2.length; i++)");
printWriter.println(" {");
printWriter.println(" coords2.push(new google.maps.LatLng(lats2[i], lons2[i]));");
printWriter.println(" }");
printWriter.println(" var mapOptions = {");
printWriter.println(" center: coords1.getAt(position1),");
printWriter.println(" zoom: 15,");
printWriter.println(" mapTypeId: google.maps.MapTypeId.ROADMAP");
printWriter.println(" };");
printWriter.println(" map = new google.maps.Map(document.getElementById(\"map-canvas\"),");
printWriter.println(" mapOptions);");
printWriter.println(" var polyline = new google.maps.Polyline({path:coords1});");
printWriter.println(" polyline.setMap(map);");
printWriter.println("");
printWriter.println(" reset();");
printWriter.println(" }");
printWriter.println(" ");
printWriter.println(" function play()");
printWriter.println(" {");
printWriter.println(" if (position1+1 == coords1.getLength()) //finished");
printWriter.println(" {");
printWriter.println(" position1 = 0;");
printWriter.println(" position2 = 0;");
printWriter.println(" }");
printWriter.println(" paused = false;");
printWriter.println(" resume = true;");
printWriter.println(" setTimeout(function() {");
printWriter.println(" move(position1, marker1, coords1, distance1);");
printWriter.println(" }, 0);");
printWriter.println(" setTimeout(function() {");
printWriter.println(" move(position2, marker2, coords2, distance2);");
printWriter.println(" }, 0);");
printWriter.println(" }");
printWriter.println(" function playFromSlide()");
printWriter.println(" {");
printWriter.println(" if (resume)");
printWriter.println(" play();");
printWriter.println(" }");
printWriter.println(" ");
printWriter.println(" function pause()");
printWriter.println(" {");
printWriter.println(" paused = true;");
printWriter.println(" }");
printWriter.println(" function pauseFromSlide()");
printWriter.println(" {");
printWriter.println(" if (paused)");
printWriter.println(" resume = false;");
printWriter.println(" pause();");
printWriter.println(" }");
printWriter.println(" ");
printWriter.println(" function stop()");
printWriter.println(" {");
printWriter.println(" paused = false;");
printWriter.println(" resume = false;");
printWriter.println(" infoBox.close();");
printWriter.println(" marker1.setMap(null);");
printWriter.println(" marker2.setMap(null);");
printWriter.println(" position1 = 0;");
printWriter.println(" position2 = 0;");
printWriter.println(" lastGap = 0;");
printWriter.println(" $( \"#slider\" ).slider( \"option\", \"value\", position1 );");
printWriter.println(" reset();");
printWriter.println(" }");
printWriter.println(" ");
printWriter.println(" function reset()");
printWriter.println(" {");
printWriter.println(" marker1 = new google.maps.Marker({anchorPoint:new google.maps.Point(0,0),map:map,position:coords1.getAt(position1),clickable:false,zIndex:0,icon:'" + markerAImageData + "'});");
printWriter.println(" marker2 = new google.maps.Marker({anchorPoint:new google.maps.Point(0,0),map:map,position:coords2.getAt(position2),clickable:false,zIndex:1,icon:'" + markerBImageData + "'});");
printWriter.println(" infoBox = new InfoBox({closeBoxURL:\"\",enableEventPropagation:false,alignBottom:true,maxWidth:0,pixelOffset: new google.maps.Size(10, -40),boxStyle:{border: '1px solid black',opacity: 0.8,background:'white',whiteSpace:'nowrap',padding:'5px'}});");
printWriter.println(" infoBox.open(map, marker1);");
printWriter.println(" infoBox.setContent('A distance 0.000km<br> pace 0.0kmh<br>B distance 0.000km<br> pace 0.0kmh<br>Gap 0.000km');");
printWriter.println(" }");
printWriter.println(" ");
printWriter.println(" function slide(position)");
printWriter.println(" {");
printWriter.println(" var gapChangeText = neutral;");
printWriter.println(" if (gap[position-1] > gap[position1-1])");
printWriter.println(" gapChangeText = upArrow;");
printWriter.println(" else if (gap[position-1] < gap[position1-1])");
printWriter.println(" gapChangeText = downArrow;");
printWriter.println(" position1 = position;");
printWriter.println(" marker1.setPosition(coords1.getAt(position1));");
printWriter.println(" position2 = position < coords2.getLength() ? position : coords2.getLength()-1;");
printWriter.println(" marker2.setPosition(coords2.getAt(position2));");
printWriter.println(" panMap(coords1.getAt(position1));");
printWriter.println(" updateDistance = 0;");
printWriter.println(" lastGap = gap[position-1];");
printWriter.println(" infoBox.setContent('A distance ' + distance1[position1-1] + 'km<br> pace ' + pace1[position1] + 'kmh<br>B distance ' + distance2[position2-1] + 'km<br> pace ' + pace2[position2] + 'kmh<br>Gap ' + (position1 == 0 ? '0.000' : gap[position1-1]) + 'km ' + gapChangeText);");
printWriter.println(" }");
printWriter.println(" ");
printWriter.println(" function panMap(coord)");
printWriter.println(" {");
printWriter.println(" var mapBounds = map.getBounds();");
printWriter.println(" if (mapBounds != null && coord != null)");
printWriter.println(" {");
printWriter.println(" var ne = mapBounds.getNorthEast();");
printWriter.println(" var sw = mapBounds.getSouthWest();");
printWriter.println(" var mapCanvasProjection = infoBox.getProjection();");
printWriter.println(" var coordPixelPoint = mapCanvasProjection.fromLatLngToContainerPixel(coord);");
printWriter.println(" var nePixelPoint = mapCanvasProjection.fromLatLngToContainerPixel(ne);");
printWriter.println(" if (coordPixelPoint.x+infoBoxClearance > nePixelPoint.x || coordPixelPoint.y-infoBoxClearance < nePixelPoint.y)");
printWriter.println(" {");
printWriter.println(" map.panTo(coord);");
printWriter.println(" }");
printWriter.println(" else if ( (coord.lat() < ne.lat() && coord.lat() < sw.lat()) ||");
printWriter.println(" (coord.lat() > ne.lat() && coord.lat() > sw.lat()) ||");
printWriter.println(" (coord.lng() < ne.lng() && coord.lng() < sw.lng()) ||");
printWriter.println(" (coord.lng() > ne.lng() && coord.lng() > sw.lng()) )");
printWriter.println(" {");
printWriter.println(" map.panTo(coord);");
printWriter.println(" }");
printWriter.println(" }");
printWriter.println(" }");
printWriter.println(" ");
printWriter.println(" function changeSpeed(value)");
printWriter.println(" {");
printWriter.println(" speed = value;");
printWriter.println(" }");
printWriter.println("");
printWriter.println(" function move(pos, mark, coords, distance)");
printWriter.println(" {");
printWriter.println(" if (paused)");
printWriter.println(" return;");
printWriter.println(" panMap(coords.getAt(pos+1));");
printWriter.println(" mark.setPosition(coords.getAt(pos));");
printWriter.println(" if (mark == marker1)");
printWriter.println(" {");
printWriter.println(" updateDistance++;");
printWriter.println(" if (updateDistance == 20)");
printWriter.println(" {");
printWriter.println(" updateDistance = 0;");
printWriter.println(" var gapChangeText = neutral;");
printWriter.println(" if (gap[pos-1] > lastGap)");
printWriter.println(" gapChangeText = upArrow;");
printWriter.println(" else if (gap[pos-1] < lastGap)");
printWriter.println(" gapChangeText = downArrow;");
printWriter.println(" lastGap = gap[pos-1];");
printWriter.println(" infoBox.setContent('A distance ' + distance1[pos-1] + 'km<br> pace ' + pace1[pos] + 'kmh<br>B distance ' + distance2[pos-1 < distance2.length ? pos-1 : distance2.length-1] + 'km<br> pace ' + pace2[pos < pace2.length ? pos : pace2.length-1] + 'kmh<br>Gap ' + gap[pos-1] + 'km ' + gapChangeText);");
printWriter.println(" }");
printWriter.println(" position1 = pos+1;");
printWriter.println(" $( \"#slider\" ).slider( \"option\", \"value\", position1 );");
printWriter.println(" }");
printWriter.println(" else");
printWriter.println(" position2 = pos+1;");
printWriter.println(" pos++;");
printWriter.println(" if (pos+1 < coords.getLength())");
printWriter.println(" setTimeout(function() {");
printWriter.println(" move(pos, mark, coords, distance);");
printWriter.println(" }, 1000/speed);");
printWriter.println(" }");
printWriter.println("");
printWriter.println(" google.maps.event.addDomListener(window, 'load', initialize);");
printWriter.println(" </script>");
printWriter.println(" </head>");
printWriter.println(" <body>");
printWriter.println(" <div align=\"center\" class=\"small-font\" style=\"padding-top:5px; padding-bottom:5px\">");
printWriter.println(" <div id=\"toolbar\" class=\"ui-widget-header ui-corner-all\" style=\"margin-bottom:5px\">");
printWriter.println(" <button id=\"play\">play</button>");
printWriter.println(" <button id=\"stop\">stop</button>");
printWriter.println(" </div>");
printWriter.println(" <br><label>Time:</label>");
printWriter.println(" <div id=\"slider\" class=\"ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all small-font\" style=\"width: 50%;margin-bottom:5px;margin-top:2px\"></div>");
printWriter.println(" <label>Speed:</label>");
printWriter.println(" <div id=\"speedSlider\" class=\"ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all small-font\" style=\"width: 25%;margin-top:2px\">");
printWriter.println(" </div>");
printWriter.println(" </div>");
printWriter.println(" <div id=\"map-canvas\" style=\"font-family: 'Trebuchet MS','Helvetica','Arial','Verdana','sans-serif';\"/>");
printWriter.println(" </body>");
printWriter.println("</html>");
}
public static double distanceBetween(double lat1, double lng1, double lat2, double lng2)
{
int earthRadius = 6371;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double sindLat = Math.sin(dLat / 2);
double sindLng = Math.sin(dLng / 2);
double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
* Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double distance = earthRadius * c;
return distance;
}
}
|
Markdown
|
UTF-8
| 7,468 | 3.15625 | 3 |
[] |
no_license
|
# OOP ORIENTED IMPLEMETATION wp_nonce #
This class as be made as a test, it's not to use in production environment.
The class have the basic function for creating and verifying a nonce
it's already declarated as $jmcNonce:
## $jmcNonce->Create() ##
### Description ###
Generates and returns a nonce. The nonce is generated based on the current time, the $action argument, and the current user ID.
### Usage ###
```
<?php $jmcNonce->Create ( $action ); ?>
```
### Parameters ###
$action
(string/int) (optional) Action name. Should give the context to what is taking place. Optional but recommended.
Default: -1
Return Values
(string)
The one use form token.
### Example ###
In this simple example, we create an nonce and use it as one of the GET query parameters in a URL for a link.
When the user clicks the link they are directed to a page where a certain action will be performed (for example, a post might be deleted). On the target page the nonce is verified to insure that the request was valid (this user really clicked the link and really wants to perform this action).
```
<?php
// Create an nonce for a link.
// We pass it as a GET parameter.
// The target page will perform some action based on the 'do_something' parameter.
$nonce = $jmcNonce->Create( 'my-nonce' );
?>
<a href='myplugin.php?do_something=some_action&_wpnonce=<?php echo $nonce; ?>'>Do some action</a>
<?php
// This code would go in the target page.
// We need to verify the nonce.
$nonce = $_REQUEST['_wpnonce'];
if ( ! $jmcNonce->Verify( $nonce, 'my-nonce' ) ) {
// This nonce is not valid.
die( 'Security check' );
} else {
// The nonce was valid.
// Do stuff here.
}
?>
```
## $jmcNonce->CreateURL() ##
### Description ###
Retrieve URL with nonce added to URL query.
The returned result is escaped for display.
### Usage ###
```
<?php $jmcNonce->CreateURL( $actionurl, $action, $name ); ?>
```
### Parameters ###
$actionurl
(string) (required) URL to add nonce action
Default: None
$action
(string) (optional) nonce action name
Default: -1
$name
(string) (optional, since 3.6) nonce name
Default: _jmcNonce
Return Values
(string)
URL with nonce action added.
### Examples ###
```
function my_plugin_do_something () {
?>
<h2><?php esc_html_e('My Plugin Admin Screen', 'my-plugin-textdomain');?></h2>
<p>
<a href="<?php print $jmcNonce->CreateURL(admin_url('options.php?page=my_plugin_settings'), 'doing_something', 'my_nonce');?>"
class="button button-primary"><?php esc_html_e('Do Something!', 'my-plugin-textdomain');?></a>
<span class="description"><?php esc_html_e('This button does something interesting.', 'my-plugin-textdomain');?></span>
</p>
<?php
}
```
Then check nonce validity
```
if (isset($_GET['my_nonce']) || $jmcNonce->Verify($_GET['my_nonce'], 'doing_something')) {
// do something
} else {
// display an error or the form again
}
```
## $jmcNonce->CreateField() ##
### Description ###
Retrieves or displays the nonce hidden form field.
The nonce field is used to validate that the contents of the form request came from the current site and not somewhere else. A nonce does not offer absolute protection, but should protect against most cases. It is very important to use nonce fields in forms.
The $action and $name arguments are optional, but if you want to have a better security, it is strongly suggested to give those two arguments. It is easier to just call the function without any arguments, because the nonce security method does not require them, but since crackers know what the default is, it will not be difficult for them to find a way around your nonce and cause damage.
The nonce field name will be whatever $name value you gave, and the field value will be the value created using the $jmcNonce->Create() function.
### Usage ###
```
<?php $jmcNonce->CreateField( $action, $name, $referer, $echo ) ?>
```
### Parameters ###
$action
(string) (optional) Action name. Should give the context to what is taking place. Optional but recommended.
Default: -1
$name
(string) (optional) Nonce name. This is the name of the nonce hidden form field to be created. Once the form is submitted, you can access the generated nonce via $_POST[$name].
Default: '_jmcNonce'
$referer
(boolean) (optional) Whether also the referer hidden form field should be created with the wp_referer_field() function.
Default: true
$echo
(boolean) (optional) Whether to display or return the nonce hidden form field, and also the referer hidden form field if the $referer argument is set to true.
Default: true
Return Values
(string)
The nonce hidden form field, optionally followed by the referer hidden form field if the $referer argument is set to true.
### Examples ###
```
<form method="post">
<!-- some inputs here ... -->
<?php $jmcNonce->CreateField( 'name_of_my_action', 'name_of_nonce_field' ); ?>
</form>
```
Then in the page where it is being submitted to, you may verify it using the $jmcNonce->Verify() function.
Notice that you have to manually retrieve the nonce (from the $_POST array in this example), and the name of the action is the 2nd parameter instead of the first:
```
<?php
if (
! isset( $_POST['name_of_nonce_field'] ) || ! $jmcNonce->Verify( $_POST['name_of_nonce_field'], 'name_of_my_action' )
) {
print 'Sorry, your nonce did not verify.';
exit;
} else {
// process form data
}
```
## $jmcNonce->Verify() ##
### Description ###
Verify that a nonce is correct and unexpired with the respect to a specified action. The function is used to verify the nonce sent in the current request usually accessed by the $_REQUEST PHP variable.
Nonces should never be relied on for authentication or authorization, access control. Protect your functions using current_user_can(), always assume Nonces can be compromised.
### Usage ###
<?php $jmcNonce->Verify( $nonce, $action ); ?>
### Parameters ###
$nonce
(string) (required) Nonce to verify.
Default: None
$action
(string/int) (optional) Action name. Should give the context to what is taking place and be the same when the nonce was created.
Default: -1
Return Values
(boolean/integer)
Boolean false if the nonce is invalid. Otherwise, returns an integer with the value of:
1 – if the nonce has been generated in the past 12 hours or less.
2 – if the nonce was generated between 12 and 24 hours ago.
### Example ###
Verify an nonce created with $jmcNonce->Create():
```
<?php
// Create an nonce, and add it as a query var in a link to perform an action.
$nonce = $jmcNonce->Create( 'my-nonce' );
echo "<a href='myplugin.php?_wpnonce={$nonce}'>Save Something</a>";
?>
.....
<?php
// In our file that handles the request, verify the nonce.
$nonce = $_REQUEST['_wpnonce'];
if ( ! $jmcNonce->Verify( $nonce, 'my-nonce' ) ) {
die( 'Security check' );
} else {
// Do stuff here.
}
?>
```
You may also decide to take different actions based on the age of the nonce:
```
<?php
$nonce = $jmcNonce->Verify( $nonce, 'my-nonce' );
switch ( $nonce ) {
case 1:
echo 'Nonce is less than 12 hours old';
break;
case 2:
echo 'Nonce is between 12 and 24 hours old';
break;
default:
exit( 'Nonce is invalid' );
}
?>
```
|
C
|
UTF-8
| 898 | 4.09375 | 4 |
[] |
no_license
|
#include <stdio.h>
int main(void)
{
int incomes[7];
int size = sizeof(incomes) / sizeof(incomes[0]);
int i;
int best = 0, bestIndex = 0;
int total = 0;
double average;
for(i = 0; i < size; i++)
{
printf("Enter the income of day %d: ", i+1);
scanf("%d", &incomes[i]);
}
printf("----------------------------------------------------\n");
for(i = 0; i < size; i++)
if(incomes[i] > best)
{
best = incomes[i];
bestIndex = i+1;
}
printf("The best income: %d in day %d\n", best, bestIndex);
printf("----------------------------------------------------\n");
for(i = 0; i < size; i++)
total += incomes[i];
average = (double) total / size;
printf("The total is %d\n", total);
printf("The average is %.1f\n", average);
printf("The good days and their incomes are\n");
for(i = 0; i < size; i++)
if(incomes[i] > average)
printf("day %d: %d\n", i+1, incomes[i]);
}
|
Shell
|
UTF-8
| 887 | 3.578125 | 4 |
[] |
no_license
|
#!/bin/bash
#echo "printing from auth"
#echo "$name $pass"
#n=$name
#echo $n
#result of mysql query stored in output
output=$(mysql -u host -h MariaDB-lxc.mycloud.com -p123456 -e "SELECT username,password from mycloud.users where username='$name' AND password='$pass';")
#the output variable will have only one line if credentials are correct. As username is the primary key so there is no way multiple lines are #received as output. Also it matches the password. In case of wrong credentials, a empty line is stored in output. In this case also the line #count is 1. So check if the line is not empty.
#echo $output
if [ -n "$output" ] && [ "$(echo $output | wc -l)" -eq 1 ];then
echo "Logged In"
printf "\n $(date): $name Logged In. <br>" | ssh root@10.0.3.34 "cat >> /var/www/html/userLogs.html"
export name pass
./landing.sh
else
echo "Login Failed!"
./login.sh
fi
|
Python
|
UTF-8
| 1,148 | 2.828125 | 3 |
[] |
no_license
|
import re
from expungeservice.models.charge_classifier import ChargeClassifier
class ChargeCreator:
@staticmethod
def create(**kwargs):
case = kwargs['case']
statute = ChargeCreator.__strip_non_alphanumeric_chars(kwargs['statute'])
level = kwargs['level']
chapter = ChargeCreator._set_chapter(kwargs['statute'])
section = ChargeCreator.__set_section(statute)
classification = ChargeClassifier(case.violation_type, statute, level, chapter, section).classify()
kwargs['chapter'] = chapter
kwargs['section'] = section
kwargs['statute'] = statute
return classification(**kwargs)
@staticmethod
def __strip_non_alphanumeric_chars(statute):
return re.sub(r'[^a-zA-Z0-9*]', '', statute).upper()
@staticmethod
def _set_chapter(statute):
if '.' in statute:
return statute.split('.')[0]
else:
return None
@staticmethod
def __set_section(statute):
if len(statute) < 6:
return ''
elif statute[3].isalpha():
return statute[0:7]
return statute[0:6]
|
JavaScript
|
UTF-8
| 3,306 | 2.84375 | 3 |
[] |
no_license
|
#!/usr/bin/env node
"use strict";
/**********************************************************************
* Libraries
*********************************************************************/
const config = require('../config/config.js');
/**********************************************************************
* Logging
*********************************************************************/
const _enabledLogs = [
"command:info"
].join(' ');
process.env.DEBUG = process.env.DEBUG || _enabledLogs;
const log = require("../lib/log.js").init("command");
/**********************************************************************
* Help Text
*********************************************************************/
/**
* Dynamically allow any config in our configuration file be
* overridden on the command line.
*/
let _configOverrides = [];
for (let key in config) {
_configOverrides.push(` --${key} <${key}>`);
}
/**
* See Docopts Syntax here:
* http://bit.ly/1EQXdRe
*/
const help = `
Usage:
command [options] -r <requiredparam>
command [options]
Options:
-c --config Display the Environment
-d --debug Enable Debug Output
-h --help Show this help
-l --log Enable Log Output
-v --verbose Enable Verbose Output
Additional Options:
${_configOverrides.join('\n')}
A generic command documentation you should change
`;
/** Process The Docopts */
const docopt = require('docopt').docopt;
const options = docopt(help);
/** Handle dynamic config overrides */
for (let option in options) {
if (options.hasOwnProperty(option) && options[option] && options[option] !== null) {
const optionWithoutDashes = option.replace(/^--/, "");
config[optionWithoutDashes] = options[option];
}
}
/** Respect log config */
log.enable.debug = config.debug;
log.enable.verbose = config.verbose;
/********************************************************************
* Imports
********************************************************************/
/**********************************************************************
* Setup
*********************************************************************/
// Emit our command line options if debug is set
log.debug("Command Line Settings:", options);
/**
* Output our environment and quit
*/
if (options['--config']) {
// Force logging enabled
log.enable.logging = true;
// Make output look nice
let _message = [];
for (let key in config) {
if (key !== "descriptions") {
_message.push(`${key}=${config[key]}`);
}
}
log.info(`
------------------------------------------------------------------
Configuration:
------------------------------------------------------------------
${_message.join('\n ')}
------------------------------------------------------------------
`);
process.exit(0);
}
/**********************************************************************
* Main
*********************************************************************/
const handleError = error => {
log(error && (error.stack || error.message || error));
process.exit(1);
};
const main = async () => {
try {
// Do things
} catch (e) {
handleError(e);
}
};
main().catch(handleError);
|
C
|
UTF-8
| 2,048 | 2.765625 | 3 |
[] |
no_license
|
/*
** main.c for ElCrypt in /home/barrau_h
**
** Made by Hippolyte Barraud
** Login <barrau_h@epitech.net>
**
** Started on Sun Mar 1 20:50:07 2015 Hippolyte Barraud
** Last update Sun Mar 1 21:53:53 2015 Hippolyte Barraud
*/
#include "../includes/elcrypt.h"
char *strdup(const char *str)
{
int n;
char *dup;
n = strlen(str) + 1;
dup = xmalloc(n);
strcpy(dup, str);
return (dup);
}
FILE *open_files(FILE *file, char *src, int *size)
{
file = fopen(src, "rb");
if (!file)
print_error("Impossible d'ouvrir les fichiers", TRUE);
if (fseek(file, 0L, SEEK_END) != 0)
print_error("Erreur lecture", TRUE);
*size = ftell(file);
if (fseek(file, 0L, SEEK_SET) != 0)
print_error("Erreur lecture", TRUE);
return (file);
}
unsigned char *read_file(t_query *query, FILE **filesrc)
{
static FILE *file = NULL;
static unsigned char buff[9];
int ret;
if (file == NULL)
file = open_files(*filesrc, query->src, &query->MaxByte);
buff[8] = '\0';
*filesrc = file;
ret = fread(buff, sizeof(char), 8, file);
query->CurrentByte += ret;
if (ret < 0)
print_error("Erreur de lecture", TRUE);
else if (ret == 0)
return (get_pad_block(query));
else if (ret != 8)
add_pading(&buff[0], query, ret);
return (&buff[0]);
}
void init(t_query *query)
{
FILE *filedest;
FILE *filesrc;
int writeSize;
unsigned char *cipher_ans;
unsigned char *read;
t_turn turn;
filesrc = NULL;
filedest = fopen(query->dest, "wc");
while (TRUE)
{
if ((read = read_file(query, &filesrc)) == NULL)
break;
cipher_ans = cipher(query, &turn, read);
writeSize = fwrite(cipher_ans, 1, query->towrite, filedest);
if (writeSize != query->towrite)
print_error("Erreur d'écriture", TRUE);
}
fclose(filedest);
fclose(filesrc);
puts("Opération effectué avec succès !");
}
int main(int ac, char **av)
{
t_query query;
query = parse_query(ac, av);
query.CurrentByte = 0;
query.towrite = 8;
query.ditpad = FALSE;
init(&query);
free(query.src);
free(query.dest);
return (0);
}
|
C#
|
UTF-8
| 3,069 | 3.84375 | 4 |
[] |
no_license
|
namespace DataStructureAlgorithm.Leetcode
{
//707. Design Linked List
//https://leetcode.com/problems/design-linked-list/
public class DesignLinkedList
{
}
public class MyLinkedList
{
public int size;
public Node Head;
/** Initialize your data structure here. */
public MyLinkedList()
{
size = 0;
Head = null;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
public int Get(int index)
{
if (index + 1 > size)
{
return -1;
}
var curr = Head;
for (int i = 0; i < index; i++)
{
curr = curr.next;
}
return curr.val;
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
public void AddAtHead(int val)
{
AddAtIndex(0, val);
}
/** Append a node of value val to the last element of the linked list. */
public void AddAtTail(int val)
{
AddAtIndex(size, val);
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
public void AddAtIndex(int index, int val)
{
if (index > size)
{
return;
}
size++;
Node newNode = new Node(val);
if (index <= 0)
{
newNode.next = Head;
Head = newNode;
return;
}
Node prev = null;
var curr = Head;
for (int i = 0; i < index; i++)
{
prev = curr;
curr = curr.next;
}
newNode.next = curr;
prev.next = newNode;
return;
}
/** Delete the index-th node in the linked list, if the index is valid. */
public void DeleteAtIndex(int index)
{
if (index >= size)
{
return;
}
size--;
if (index == 0)
{
Head = Head.next;
return;
}
Node prev = null;
var curr = Head;
for (int i = 0; i < index; i++)
{
prev = curr;
curr = curr.next;
}
prev.next = curr.next;
return;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.Get(index);
* obj.AddAtHead(val);
* obj.AddAtTail(val);
* obj.AddAtIndex(index,val);
* obj.DeleteAtIndex(index);
*/
}
|
Markdown
|
UTF-8
| 754 | 2.921875 | 3 |
[] |
no_license
|
# Ludo
This is the 2nd attempt to get it right.
Players can roll the dice and make moves equal to the number of the dice
## What's new
- When the pieces get clicked, they'll move
- The server ensures no one rolls the dice or clicks on pieces outside their turn
- Implemented dice rolling. Only the player whose turn it is will be allowed to roll the dice.
## Coming next
- App will crash when pieces reach the end of the path array. This will be fixed
- Playes will go to the coloured boxes after completing the white boxes
## Limitations
- Pieces don't go to the colours boxes yet.
- It doesn't require a 6 to start the game.
- Players can't send others to the starting position when crossing over them
- Doesn't handle disconnections well.
|
C
|
UTF-8
| 661 | 3.109375 | 3 |
[] |
no_license
|
/*
** EPITECH PROJECT, 2019
** print_list
** File description:
** piscine synthèse
*/
#include "../include/my.h"
#include "../include/struct.h"
int list_size(list_t *list)
{
list_t *start = list_get_firstelem(list);
unsigned int i = 0;
while (start) {
i = i + 1;
start = start->next;
}
return (i);
}
void list_destroy(list_t *list)
{
list_t *tmp;
while (list) {
tmp = list->next;
free(list->val);
free(list);
list = tmp;
}
}
void list_clear(list_t *list)
{
list_t *tmp;
while (list) {
tmp = list->next;
free(list);
list = tmp;
}
}
|
Swift
|
UTF-8
| 1,233 | 2.703125 | 3 |
[] |
no_license
|
//
// ReviewInputViewController.swift
// Project3Sample
//
// Created by Russell Mirabelli on 11/16/19.
// Copyright © 2019 Russell Mirabelli. All rights reserved.
//
import UIKit
class ReviewInputViewController: UIViewController {
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var titleField: UITextField!
@IBOutlet weak var bodyField: UITextView!
@IBOutlet weak var submitButton: UIButton!
var bookID: Int?
var canSubmit: Bool {
if nameField.hasText && titleField.hasText && bodyField.hasText {
return true
}
return false
}
var review: Review?
let reviewService = ReviewService()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func submitButtonPressed(_ sender: Any) {
if canSubmit {
self.review = Review(id: nil, bookId: self.bookID!, date: Date(), reviewer: self.nameField.text!, title: self.titleField.text!, body: self.bodyField.text)
reviewService.createReview(review: self.review!) { () in
DispatchQueue.main.async {
self.navigationController?.popViewController(animated: true)
}
}
}
}
}
|
Ruby
|
UTF-8
| 143 | 2.59375 | 3 |
[] |
no_license
|
cart_items_prices = [12.43, 19.99, 3.49, 75.00]
expensive_food = []
cart_items_prices.each do |x|
if x >= 15.00
puts x
end
end
|
Swift
|
UTF-8
| 4,966 | 2.890625 | 3 |
[] |
no_license
|
//
// ViewController.swift
// SlideshowApp
//
// Created by Yoshi on 2018/08/31.
// Copyright © 2018年 yoshiyuki.oohara. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var timer: Timer!
// 表示している画像の番号
var dispImageNo = 0
// 表示している画像の番号を元に画像を表示する
func displayImage() {
// 画像の名前の配列
let imageNameArray = [
"African lion 1080x1920.jpg",
"vicuña 1080x1920.jpg",
"Ural owl 1080x1920.jpg",
]
// 画像の番号が正常な範囲を指しているかチェック
// 範囲より下を指している場合、最後の画像を表示
if dispImageNo < 0 {
dispImageNo = 2
}
// 範囲より上を指している場合、最初の画像を表示
if dispImageNo > 2 {
dispImageNo = 0
}
// 表示している画像の番号から名前を取り出し
let name = imageNameArray[dispImageNo]
// 画像を読み込み
let image = UIImage(named: name)
// Image Viewに読み込んだ画像をセット
imageView.image = image
}
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var prevButton: UIButton!
@IBOutlet weak var playButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let image = UIImage(named: "African lion 1080x1920.jpg")
imageView.image = image
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func nextImage(_ sender: Any) {
// 表示している画像の番号を1増やす
dispImageNo += 1
// 表示している画像の番号を元に画像を表示する
displayImage()
}
@IBAction func previousImage(_ sender: Any) {
// 表示している画像の番号を1減らす
dispImageNo -= 1
// 表示している画像の番号を元に画像を表示する
displayImage()
}
@objc func updateTimer(_ timer: Timer) {
// 表示している画像の番号を1増やす
dispImageNo += 1
// 表示している画像の番号を元に画像を表示する
displayImage()
}
@IBAction func startSlideshow(_ sender: Any) {
// スライドショー再生
// 動作中のタイマーを1つに保つために、 timer が存在しない場合だけ、タイマーを生成して動作させる
if self.timer == nil {
self.timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(updateTimer(_:)), userInfo: nil, repeats: true)
// ボタンの表示を停止に
playButton.setTitle("停止", for: .normal)
// 進む/戻るボタンの無効化
nextButton.isEnabled = false
prevButton.isEnabled = false
} else {
// 停止
self.timer.invalidate() // 現在のタイマーを破棄する
self.timer = nil // startTimer() の timer == nil で判断するために、 timer = nil としておく
// ボタンの表示を再生に
playButton.setTitle("再生", for: .normal)
// 進む/戻るボタンの有効化
nextButton.isEnabled = true
prevButton.isEnabled = true
}
}
@IBAction func onTapImage(_ sender: Any) {
// セグエを使用して画面を遷移
performSegue(withIdentifier:"result", sender: nil)
// スライドショー再生中なら停止
if self.timer != nil {
self.timer.invalidate() // 現在のタイマーを破棄する
self.timer = nil // startTimer() の timer == nil で判断するために、 timer = nil としておく
// ボタンの表示を再生に
playButton.setTitle("再生", for: .normal)
// 進む/戻るボタンの有効化
nextButton.isEnabled = true
prevButton.isEnabled = true
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// segueから遷移先のResultViewControllerを取得する
let resultViewController:ResultViewController = segue.destination as! ResultViewController
resultViewController.ExtendImage = imageView.image
}
@IBAction func unwind(_ segue: UIStoryboardSegue) {
}
}
|
Markdown
|
UTF-8
| 673 | 3.234375 | 3 |
[] |
no_license
|
# Uber-Data-Analysis
Data analysis on UBER's data of ride calls from travellers I used simple Python(panda and seaborn) functions to get really useful insights from the data. After analysing the data we got the following output results:
- Generated the map of the place where data belongs to;
- Generated heatmap of the user requesting for rides over the week;
- Generated the hourly, day wise, weekly and monthly plots of user requests;
Although it was not told in the data that to what place the data belongs to, but still I was able to get the location of the place where data belongs, it was Manhattan. Also I did some additional analysis going deeper on the data.
|
Python
|
UTF-8
| 512 | 3.3125 | 3 |
[] |
no_license
|
"""
Python 2 solution for Zipfsong: https://open.kattis.com/problems/zipfsong
author - Oussama Zaki <zaki.oussama@gmail.com>
"""
import operator
def stupid_print(s):
print s
if __name__ == "__main__":
n, m = map(int, raw_input().split())
album = dict()
for i in range(1, n + 1):
fi, song = raw_input().split()
album[song] = int(fi) * i
sorted_album = sorted(album.items(), key=operator.itemgetter(1), reverse=True)[:m]
map(lambda entry: stupid_print(entry[0]), sorted_album)
|
Java
|
UTF-8
| 734 | 3.1875 | 3 |
[] |
no_license
|
package com.yangzl.jvm;
/**
* @author yangzl
* @date 2021/3/14
*
* 测试堆空间初始值与最大值,注意:runtime.maxMemory() = eden + s0 / s1 + 老年代
*
* -Xms1000m
* -Xmx1000m
* -Xmn400m
*/
public class HeapSpaceTest {
/**
* initial = max = 950m
* 年轻代每次只能选择 eden + s0 / s1 = 300m + 50m「难道默认是 6:1:1,或者说 jvm 自动调整了」
*
* @param args args
*/
public static void main(String[] args) {
final Runtime runtime = Runtime.getRuntime();
long inital = runtime.totalMemory() / 1024 / 1024;
long max = runtime.maxMemory() / 1024 / 1024;
System.out.println("初始内存 = " + inital + " m");
System.out.println("最大内存 = " + max + " m");
}
}
|
Markdown
|
UTF-8
| 8,477 | 2.5625 | 3 |
[] |
no_license
|
# Section 2 - 파이썬 기초 스크랩핑
## 크롬(Chrome) 개발자 도구
#### ● 기본개념
1. DOM 구조 분석(요소검사)
2. 선택자(Selector) 추출
- 개발자 도구를 통해 내가 원하는 데이터의 Selector을 가져올 수 있는지
3. Console 도구
4. Source - 로딩 한 리소스 분석 및 디버깅
5. 네트워크 탭 및 기타
## 파이썬 urllib을 활용한 웹에서 필요한 데이터 추출하기(1)
#### ● 오늘 배울 내용 정리
1. Urlretrieve
2. urlopen
3. urlretrieve Vs urlopen 비교
4. open, write, close
5. with
https://wikidocs.net/26
https://docs.python.org/3/library/urllib.request.html
* Atom은 한글 텍스트를 콘솔창에 출력하면 글이 깨짐 그래서 아래 코드를 상단에 추가해야함
* ```python
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
```
### 1. Urlretrieve
* Url을 통해 원하는 정보를 하드 디스크에 다운 받음
* ```python
imgUrl = # 이미지다운 "http://post.phinf.naver.net/MjAxODA4MDFfMjMw/MDAxNTMzMDg4NDAwMTE0.gDPRGifP9tYmNRSxOvNhKQfi1qsyR4luus9bgZdI6uIg.yzhhIvD7AWlpOb4OK1vOA5F4HLVxCEfGb57k9gndK94g.JPEG/Iq_cU6Sac798YMzN22yJSvrEU2GM.jpg"
htmlURL = "https://google.com" # Url을 html파일로 다운
savePath1 = "c:/test1.jpg"
savePath2 = "c:/index.html"
down.urlretrieve(imgUrl, savePath1)
down.urlretrieve(htmlURL, savePath2)
print("다운로드 완료!")
```
*
### 2. Urlopen
* Url을 통해 원하는 정보를 하드 디스크에 다운 받음
```python
import sys
import io
import urllib.request as down
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
imgUrl = "http://post.phinf.naver.net/MjAxODA4MDFfMjMw/MDAxNTMzMDg4NDAwMTE0.gDPRGifP9tYmNRSxOvNhKQfi1qsyR4luus9bgZdI6uIg.yzhhIvD7AWlpOb4OK1vOA5F4HLVxCEfGb57k9gndK94g.JPEG/Iq_cU6Sac798YMzN22yJSvrEU2GM.jpg"
htmlURL = "https://google.com"
savePath1 = "c:/test1.jpg"
savePath2 = "c:/index.html"
f = down.urlopen(imgUrl).read()
f2 = down.urlopen(htmlURL).read()
# 방법 1
saveFile1 = open(savePath1, 'wb') # w: write, r : read, a : add/ wb= binary로 쓰겠다
saveFile1.write(f) # 웹에서 가져온 resource를 읽겠다
saveFile1.close()
# 자바든 python이든 항상 입출력 작업이나 DB 데이터 커넥션 작업을 하면 리소스를 반납해줘야함
# 방법 2 (이 방법을 더 선호) with를 벗어나면 close()가 자동으로 실행, 더 간결!
with open(savePath2, 'wb') as saveFile2:
saveFile2.write(f2)
print("다운로드 완료!")
```
### 3. urlretrieve Vs urlopen
* **`urlretrieve`** : 직접적으로 데이터를 바로 받아옴
* 저장 -> open('r') -> 변수에 할당 -> 파싱 -> 저장 ( **다이렉트 저장** )
* 사진을 단체로 (1000장씩) 한번에 다운 받는데 있어서 적합
* **`urlopen`**: 어떤 html을 받아서 중간에 내가 필요로 하는 데이터를 파싱(분류)할 거면 urlopen이 적합
* **변수 할당** -> 파싱 -> 저장(db) ( **변수에 할당함**)
* 중간 작업에서 다운 받기전에 조건에 맞게 걸러내는데 적합
## 파이썬 urllib을 활용한 웹에서 필요한 데이터 추출하기(2)
#### ● 오늘 배울 내용 정리
1. Urlopen 파라미터(Parameter) 전달 방법
2. Type (자료형 알아보기)
3. decode, geturl, status, getheaders, info, urlparse
● 실습(과제): 네이버 홈페이지 (상단, 우측 배너 광고) 저장해보기
https://wikidocs.net/26
https://docs.python.org/3/library/urllib.request.html
#### ● decode, geturl, status, getheaders, info, urlparse
```python
print("geturl", mem.geturl())
# => geturl http://www.encar.com/index.do
print("status",mem.status) # 이런 페이지오류에 대해서 예외처리를 해줘야하므로 알아야함
# 200(정상), 404(페이지없음), 403(접속안됌), 500(서버문제)
print("headers", mem.getheaders())
# => headers [('Date', 'Wed, 29 May 2019 06:44:21 GMT'), ('Set-Cookie', 'WMONID=ZCzo03q9Eo2; Expires=Thu, 28-May-2020 15:44:21 GMT; Path=/'), ('Content-Type', 'text/html; charset=EUC-KR'), ('Connection', 'close'), ('Content-Language', 'ko-KR'), ('Set-Cookie', 'JSESSIONID=G12dw3QvRzVLtx1qT8g0gJ8FltB9ERzpw1YKOGpa6kO09z2GUtRzJ0YQB2OAfnao.encarwas4_servlet_engine3;Path=/'), ('P3P', "CP='CAO PSA CONi OTR OUR DEM ONL'"), ('X-UA-Compatible', 'IE=Edge'), ('Transfer-Encoding', 'chunked')]
print("info", mem.info())
# => info Date: Wed, 29 May 2019 06:44:21 GMT
# Set-Cookie: WMONID=ZCzo03q9Eo2; Expires=Thu, 28-May-2020 15:44:21 GMT; Path=/
# Content-Type: text/html; charset=EUC-KR
# Connection: close
# Content-Language: ko-KR
# Set-Cookie: JSESSIONID=G12dw3QvRzVLtx1qT8g0gJ8FltB9ERzpw1YKOGpa6kO09z2GUtRzJ0YQB2OAfnao.encarwas4_servlet_engine3;Path=/
# P3P: CP='CAO PSA CONi OTR OUR DEM ONL'
# X-UA-Compatible: IE=Edge
# Transfer-Encoding: chunked
print("code", mem.getcode())
# => code 200
print("read",mem.read(50).decode("utf-8")) # decode는 글자가 깨지는걸 해결
# =>
# from urllib.parse import urlparse를 import 해줘야함
print(urlparse("http://www.encar.com?test=test"))
# => ParseResult(scheme='http', netloc='www.encar.com', path='', params='', query='test=test', fragment='')
```
* 구글 검색창에 `my ip api` 검색후 `ipify` 에 접속
* ```python
https://api.ipify.org #복사하기
```
* ```python
import sys
import io
import urllib.request as req
from urllib.parse import urlencode
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
API = "https://www.mois.go.kr/gpms/view/jsp/rss/rss.jsp"
values = {
'ctxCd' : '1012' # 동적으로 할당이 가능함
}
print('before', values)
# => before {'ctxCd': '1012'}
params = urlencode(values) # urlencode를 import해줌
# 딕셔너리 형태를 format=json으로 변경
print('after', params)
# => after ctxCd=1012
url = API + "?" + params # 동적으로 할당
print("요청 url", url)
reqData = req.urlopen(url).read().decode('utf-8') # json형태로 ip를 출력
print("출력",reqData)
```
*
## 과제
#### ● 네이버 홈페이지(상단, 우측 배너(동영상) 광고 저장하기)
#### * urlretrieve 를 사용
```python
import sys
import io
import urllib.request as down
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = "utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
imgUrl = "https://ssl.pstatic.net/tveta/libs/1232/1232463/f559a07b762c847abd0e_20190516105853290_2.jpg"
videoUrl = "https://tvetamovie.pstatic.net/libs/1240/1240992/99cc84da2fad76509100_20190524163455876.mp4-pBASE-v0-f82522-20190524163820588.mp4"
savePath1 = "C:/Users/student/Desktop/img1.jpg"
savePath2 = "C:/Users/student/Desktop/video1.mp4"
down.urlretrieve(imgUrl, savePath1)
down.urlretrieve(videoUrl, savePath2)
print("다운로드 완료!")
```
#### *urlopen을 사용
```python
imgUrl = "https://ssl.pstatic.net/tveta/libs/1232/1232463/f559a07b762c847abd0e_20190516105853290_2.jpg"
videoUrl = "https://tvetamovie.pstatic.net/libs/1240/1240992/99cc84da2fad76509100_20190524163455876.mp4-pBASE-v0-f82522-20190524163820588.mp4"
savePath1 = "C:/Users/student/Desktop/img1.jpg"
savePath2 = "C:/Users/student/Desktop/video1.mp4"
f1 = down.urlopen(imgUrl).read()
f2 = down.urlopen(videoUrl).read()
saveFile1 = open(savePath1, 'wb')
saveFile1.write(f1)
saveFile1.close()
saveFile2 = open(savePath2, "wb")
saveFile2.write(f2)
saveFile2.close()
```
#### *with를 사용
```python
imgUrl = "https://ssl.pstatic.net/tveta/libs/1232/1232463/f559a07b762c847abd0e_20190516105853290_2.jpg"
videoUrl = "https://tvetamovie.pstatic.net/libs/1240/1240992/99cc84da2fad76509100_20190524163455876.mp4-pBASE-v0-f82522-20190524163820588.mp4"
savePath1 = "C:/Users/student/Desktop/img1.jpg"
savePath2 = "C:/Users/student/Desktop/video1.mp4"
f1 = down.urlopen(imgUrl).read()
f2 = down.urlopen(videoUrl).read()
with open(savePath1, 'wb') as saveFile1:
saveFile1.write(f1)
with open(savePath2, 'wb') as saveFile2:
saveFile2.write(f2)
```
|
Java
|
UTF-8
| 2,038 | 3.765625 | 4 |
[
"MIT"
] |
permissive
|
import java.util.ArrayList;
import java.util.Collections;
public class Pairings {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<String>();
for(int i = 1; i <= 6; i++){
names.add(Integer.toString(i));
}
printCycles(makePairs(names));
}
static ArrayList<ArrayList<Pair>> makePairs(ArrayList<String> names){
// Result pairs
ArrayList<ArrayList<Pair>> list = new ArrayList<ArrayList<Pair>>();
// Table for making pairs and rotating
int row = names.size()/2;
int[][] rotate = new int[2][row];
// Initialize table with numbers for each person
int count = 0;
for(int i = 0; i < row; i++){
rotate[0][i] = count++;
}
for(int i = row - 1; i >=0; i--){
rotate[1][i] = count++;
}
// make pairs
for(int i = 0; i < names.size()-1; i++) {
ArrayList<Pair> cycle = new ArrayList<Pair>(row);
// produce pairs for current cycle
for(int j = 0; j < row; j++){
Pair p = new Pair(names.get(rotate[0][j]), names.get(rotate[1][j]));
cycle.add(p);
}
// rotate table
int temp;
for(int j = 2; j < row; j++){ // first row
temp = rotate[0][j];
rotate[0][j] = rotate[0][1];
rotate[0][1] = temp;
}
for(int j = row - 1; j >= 0; j--){ // second row
temp = rotate[1][j];
rotate[1][j] = rotate[0][1];
rotate[0][1] = temp;
}
// shows pairs in random order
Collections.shuffle(cycle);
list.add(cycle);
}
// shows cycle in random order
Collections.shuffle(list);
return list;
}
static void printCycles(ArrayList<ArrayList<Pair>> list){
for(int i = 0; i < list.size(); i++){
System.out.println("Week " + (i+1) + ":");
for(Pair p: list.get(i)){
System.out.println(p.toString());
}
System.out.println();
}
}
}
|
TypeScript
|
UTF-8
| 1,279 | 2.546875 | 3 |
[
"Apache-2.0"
] |
permissive
|
const Web3 = require('web3');
import * as Utilities from './utilities';
/**
* Listen new transactions and return its hash when address occurs in 'from' or 'to' property.
* Start listening from latest block.
* Address matching is case insensitive.
* @param {string} nodeUrl url of the Ethereum node to communicate with
* @param {string} address an Ethereum address to watch
* @param {function} newTxCallback function called when a new transaction related to address, appears on the blockchain
* @param {function} errorCallback function called when an error occurs
*/
export function watch(
nodeUrl: string,
address: string,
newTxCallback: (tx: string) => void,
errorCallback: (error: Error) => void,
): void {
const web3 = new Web3(nodeUrl).eth;
// This filter check '.to' and '.from' address from 'transaction'
let filterTransactionsUsingAddress = Utilities.filterTransactionsUsingAddress(address);
let applyOnFilteredBlockTransactions = Utilities.applyOnFilteredBlockTransactions(
filterTransactionsUsingAddress,
newTxCallback,
);
web3
.subscribe('newBlockHeaders')
.on('data', (blockHeader: any) => {
web3.getBlock(blockHeader.number, true).then(applyOnFilteredBlockTransactions);
})
.on('error', errorCallback);
}
|
Markdown
|
UTF-8
| 3,276 | 2.921875 | 3 |
[] |
no_license
|
# Simple-Hide-Show-Accordion
Simple Hide/Show Accordion
a simple light responsive slide toggle accordion.
Demo page coming soon.
***
###Styling
Styling by changing the following classes.
.accordion-tab {
font:bold 12px/35px "Days One",sans-serif;
}
.accordion-tab {
background: #f3f3f3;
}
/* CHANGE OPEN & CLOSE TOGGLE IMAGE to FONTAWESOME */
div.accordion-tab:after {
background:#3276b1 url('../images/toggle_open.png') center right no-repeat;
}
.accordion-tab.active:after {
background: #3276b1 url('../images/toggle_closed.png') center right no-repeat;
}
Change the above CSS to:
div.accordion-tab:after {
content: "\f0fe";
}
.accordion-tab.active:after {
content: "\f146";
}
***
##The Markup
<div id="accordion-container">
<div class="accordion-tab active">Content #1</div>
<div class="accordion-content">
Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec.
</div>
<div class="accordion-tab">Content #2</div>
<div class="accordion-content">
<p><i class="fa fa-quote-left fa-2x pull-left fa-border"></i>
...Lorem ipsum dolor sit amet, consectetur adipiscing elit...
Integer nec odio. Praesent libero. Sed cursus ante dapibus diam.
Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. </p>
</div>
<div class="accordion-tab">Content #3</div>
<div class="accordion-content">
Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
</div>
<div class="accordion-tab">Content #4</div>
<div class="accordion-content">
Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa.
</div>
</div>
***
##The JS
Make sure jquery is loaded.
(function($){
$(document).ready(function() {
$(".accordion-content").hide();
$(".accordion-content:first").show(); // Remove this line to have first item hidden
$(".accordion-tab").click(function(){
if ($(this).is(".active"))
{
$(this).removeClass("active");
$(this).next(".accordion-content").slideUp(400);
}
else
{
$(".accordion-content").slideUp(400);
$(".accordion-tab").removeClass("active");
$(this).addClass("active");
$(this).next(".accordion-content").slideDown(400);
}
});
});
})(jQuery);
***
###Callback Options
$(".accordion-content:first").show(); // Show the first item on accordion (Default)
- Remove the above line to keep all items hidden.
// callback on accordion load
***
###Changelog
**v1** - 6/02/2015
- first release
|
Python
|
UTF-8
| 856 | 2.6875 | 3 |
[] |
no_license
|
import re
#with open('test_data.csv', 'r', encoding="utf8") as f:
with open('List-of-1000-Kanji-converted2.csv', 'r', encoding="utf8") as f:
f.readline()
z = str(f)
i = 0
arr=[]
for line in f:
x = line.split(",")
#for y in x:
#print(y)
if (len(x) == 3):
arr.append(x)
i += 1
j = 0
print(arr[0][0])
#print (arr)
db_data = []
for y in range(0, len(arr)):
#print ("-- {}".format(arr[y]))
item = {
'translation': arr[y][0],
'kanji': arr[y][1],
'pronunciation': arr[y][2],
#'kana': arr[y][3]
}
db_data.append(item)
#db_data = {"translate":arr[0][0]}
#print (db_data)
f2 = open('kanji_db.csv', 'x', encoding="utf8")
f2.write(str(db_data))
|
Python
|
UTF-8
| 20,347 | 2.578125 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""
Copyright 2017 Brocade Communications Systems, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import abc
class Acl(object):
"""
The Acl class holds all the functions assocaiated with the
Access Control list.
Attributes:
None
"""
__metaclass__ = abc.ABCMeta
def __init__(self, callback):
"""
ACL init function.
Args:
callback: Callback function that will be called for each action.
Returns:
ACL Object
Raises:
ValueError
"""
self._callback = callback
@abc.abstractmethod
def create_acl(self, **parameters):
"""
Create an Access Control List.
Args:
parameters contains:
address_type (str): ACL address type, ip or ipv6 or mac.
acl_type (str): ACL type, extended or standard.
acl_name (str): Unique name for ACL.
Returns:
Return value of `string` message.
Examples:
"""
return
@abc.abstractmethod
def delete_acl(self, **parameters):
"""
Delete Access Control List.
Args:
parameters contains:
acl_name (str): Name of the access list.
Returns:
Return value of `string` message.
Examples:
"""
return
@abc.abstractmethod
def parse_params_for_add_l2_acl_rule(self, **parameters):
"""
Parse params of rule to be added to l2 Access Control List.
Args:
parameters contains:
acl_name (str): Name of the access list.
seq_id: integer
action: string enum: - deny - permit
source: string: Source filter, can be 'any' or 'host', or the
actual MAC in HHHH.HHHH.HHHH format.
srchost: string: The source MAC in HHHH.HHHH.HHHH format.
The value is required only when the source is 'host'.
src_mac_addr_mask: string : Mask for the source MAC in
HHHH.HHHH.HHHH format.
dst: string: Destination filter, can be 'any' or 'host',
or the actual MAC of the destination in
HHHH.HHHH.HHHH format.
dsthost: string : Destination MAC in HHHH.HHHH.HHHH format.
The value is required only when the dst is 'host'
dst_mac_addr_mask: string: Mask for the destination MAC
in HHHH.HHHH.HHHH format.
vlan: VLAN IDs - 'any' or 1-4096
ethertype: EtherType, can be 'arp', 'fcoe', 'ipv4-15' 'ipv6' or
custom value between 1536 and 65535.
arp_guard: string : Enables arp-guard for the rule
drop_precedence_force: Matches the specified value against the
drop_precedence value of the packet to filter.
Allowed values are 0 through 2.
log: Enables the logging
mirror: Enables mirror for the rule
priority
priority_force
priority_mapping
Returns:
Return value of `string` message.
Examples:
"""
return
@abc.abstractmethod
def add_l2_acl_rule(self, **parameters):
"""
Delete Access Control List.
Args:
parameters contains:
acl_name (str): Name of the access list.
seq_id: integer
action: string enum: - deny - permit - hard-drop
source: string: Source filter, can be 'any' or 'host',
or the actual MAC in HHHH.HHHH.HHHH format.
src_mac_addr_mask: string : Mask for the source MAC in
HHHH.HHHH.HHHH format.
dst: string: Destination filter, can be 'any' or 'host',
or the actual MAC of the destination in
HHHH.HHHH.HHHH format.
dst_mac_addr_mask: Mask for the destination MAC in
HHHH.HHHH.HHHH format.
vlan: VLAN IDs - 'any' or 1-4096.
ethertype: EtherType can be 'arp', 'fcoe', 'ipv4-15', 'ipv6' or
custom value between 1536 and 65535.
arp_guard: string : Enables arp-guard for the rule
drop_precedence_force: string : Matches the specified value
against the drop_precedence value of the packet to filter.
Allowed values are 0 through 2.
log: Enables the logging
mirror: Enables mirror for the rule
Returns:
Return value of `string` message.
Examples:
"""
return
@abc.abstractmethod
def delete_l2_acl_rule(self, **parameters):
"""
Delete Rule from Access Control List.
Args:
parameters contains:
acl_name: Name of the access list.
seq_id: Sequence number of the rule. For add operation,
if not specified, the rule is added at the end of the list.
Returns:
Return value of `string` message.
Examples:
"""
return
@abc.abstractmethod
def is_valid_seq_id(self, seq_id, acl_name):
"""
is_valid_seq_id checks for existane of seq_id.
Args:
acl_name (str): Name of the access list.
seq_id, action, source, srchost,
Returns:
Return True
Raises:
Exception, ValueError for invalid seq_id.
Examples:
"""
return
@abc.abstractmethod
def apply_acl(self, **parameters):
"""
Apply Access Control List on interface.
Args:
parameters contains:
address_type (str): ACL address type, ip or ipv6 or mac.
acl_name: Name of the access list.
intf_type: - ethernet, ve
intf_name: array of slot/port or ve interfaces
acl_direction: Direction of ACL binding on the specified
interface
Returns:
Return True
Raises:
Exception, ValueError for invalid seq_id.
"""
return
@abc.abstractmethod
def remove_acl(self, **parameters):
"""
Apply Access Control List on interface.
Args:
parameters contains:
address_type (str): ACL address type, ip or ipv6 or mac.
acl_name: Name of the access list.
intf_type: - ethernet, ve
intf_name: array of slot/port or ve interfaces
acl_direction: Direction of ACL binding on the specified
interface
Returns:
Return True
Raises:
Exception, ValueError for invalid seq_id.
"""
return
@abc.abstractmethod
def add_ipv4_rule_acl(self, **parameters):
"""
Add rules to Access Control List of ipv4.
Args:
parameters contains:
acl_name: (string) Name of the access list
seq_id: (integer) Sequence number of the rule,
if not specified, the rule is added at the end of the list.
Valid range is 0 to 4294967290
action: (string) Action performed by ACL rule
- permit
- deny
protocol_type: (string) Type of IP packets to be filtered
based on protocol. Valid values are <0-255> or key words
tcp, udp, icmp or ip
source: (string) Source address filters
{ any | S_IPaddress/mask(0.0.0.255) |
host,S_IPaddress } [ source-operator [ S_port-numbers ] ]
destination: (string) Destination address filters
{ any | S_IPaddress/mask(0.0.0.255) |
host,S_IPaddress } [ source-operator [ S_port-numbers ] ]
dscp: (string) Matches the specified value against the DSCP
value of the packet to filter.
Allowed values are 0 through 63.
drop_precedence_force: (string) Matches the drop_precedence
value of the packet. Allowed values are 0 through 2.
urg: (string) Enables urg for the rule
ack: (string) Enables ack for the rule
push: (string) Enables push for the rule
fin: (string) Enables fin for the rule
rst: (string) Enables rst for the rule
sync: (string) Enables sync for the rule
vlan_id: (integer) VLAN interface to which the ACL is bound
count: (string) Enables statistics for the rule
log: (string) Enables logging for the rule
(Available for permit or deny only)
mirror: (string) Enables mirror for the rule
copy_sflow: (string) Enables copy-sflow for the rule
dscp-marking: (string) dscp-marking number is used to mark the
DSCP value in the incoming packet with the value you
specify to filter. Allowed values are 0 through 63.
fragment: (string) Use fragment keyword to allow the ACL to
filter fragmented packets. Use the non-fragment keyword to
filter non-fragmented packets.
Allowed values are- fragment, non-fragment
precedence: (integer) Match packets with given precedence value
Allowed value in range 0 to 7.
option: (string) Match match IP option packets.
supported values are:
any, eol, extended-security, ignore, loose-source-route
no-op, record-route, router-alert, security, streamid,
strict-source-route, timestamp
Allowed value in decimal <0-255>.
suppress-rpf-drop: (boolean) Permit packets that fail RPF check
priority: (integer) set priority
priority-force: (integer) force packet outgoing priority.
priority-mapping: (integer) map incoming packet priority.
tos: (integer) Match packets with given TOS value.
Allowed value in decimal <0-15>.
Returns:
Return True
Raises:
Exception, ValueError for invalid seq_id.
"""
return
def delete_ipv4_acl_rule(self, **parameters):
"""
Delete Rule from Access Control List.
Args:
parameters contains:
acl_name: Name of the access list.
seq_id: Sequence number of the rule. For add operation,
if not specified, the rule is added at the end of the list.
Returns:
Return value of `string` message.
Raise:
Raises ValueError, Exception
Examples:
"""
return
@abc.abstractmethod
def add_ipv6_rule_acl(self, **parameters):
"""
Add rules to Access Control List of ipv6.
Args:
parameters contains:
acl_name(string): Name of the access list
seq_id(integer): Sequence number of the rule,
if not specified, the rule is added
at the end of the list. Valid range is 0 to 4294967290
action(string): Action performed by ACL rule
- permit (default)
- deny
- hard-drop
protocol_type(string): Type of IP packets to be filtered based
on protocol. Valid values are 0 through 255 or key words
tcp, udp, icmp or ip
source(string): Source address filters
{ any | S_IPaddress mask | host S_IPaddress }
[ source-operator [ S_port-numbers ] ]
destination(string):Destination address filters
{ any | S_IPaddress mask | host S_IPaddress }
[ source-operator [ S_port-numbers ] ]
dscp(string): Matches the specified value against the DSCP
value of the packet to filter.
Can be either a numerical value or DSCP name
drop_precedence_force(string): Matches the drop_precedence
value of the packet. Allowed values are 0 through 2.
urg(string): Enables urg for the rule
ack(string): Enables ack for the rule
push(string): Enables push for the rule
fin(string): Enables fin for the rule
rst(string): Enables rst for the rule
sync(string): Enables sync for the rule
vlan_id:(integer): VLAN interface to which the ACL is bound
count(string): Enables statistics for the rule
log(string): Enables logging for the rule
mirror(string): Enables mirror for the rule
copy_sflow(string): Enables copy-sflow for the rule
Returns:
Return True
Raises:
Exception, ValueError for invalid seq_id.
"""
return
def delete_ipv6_acl_rule(self, **parameters):
"""
Delete Rule from Access Control List.
Args:
parameters contains:
acl_name: Name of the access list.
seq_id: Sequence number of the rule. For add operation,
if not specified, the rule is added at the end of the list.
Returns:
Return value of `string` message.
Raise:
Raises ValueError, Exception
Examples:
"""
return
@abc.abstractmethod
def add_ipv4_rule_acl_bulk(self, **kwargs):
"""
Add ACL rule to an existing IPv4 ACL.
Args:
acl_name (str): Name of the access list.
acl_rules (array): List of ACL sequence rules.
Returns:
True, False or None for Success, failure and no-change respectively
for each seq_ids.
Examples:
>>> from pyswitch.device import Device
>>> with Device(conn=conn, auth=auth,
connection_type='NETCONF') as dev:
>>> print dev.acl.create_acl(acl_name='Acl_1',
acl_type='standard',
address_type='ip')
>>> print dev.acl.add_ip_acl_rule(acl_name='Acl_1',
acl_rules = [{"seq_id": 10, "action": "permit",
"source": "host 192.168.0.3")
"""
return
@abc.abstractmethod
def delete_ipv4_acl_rule_bulk(self, **kwargs):
"""
Delete ACL rules from IPv4 ACL.
Args:
acl_name (str): Name of the access list.
acl_rules (string): Range of ACL sequence rules.
Returns:
True, False or None for Success, failure and no-change respectively
for each seq_ids.
Examples:
>>> from pyswitch.device import Device
>>> with Device(conn=conn, auth=auth,
connection_type='NETCONF') as dev:
>>> print dev.acl.create_acl(acl_name='Acl_1',
acl_type='standard',
address_type='ip')
>>> print dev.acl.add_ip_acl_rule(acl_name='Acl_1',
acl_rules = [{"seq_id": 10, "action": "permit",
"source": "host 192.168.0.3")
"""
return
def _process_cli_output(self, method, config, output):
"""
Parses CLI response from switch.
Args:
output string contains the response from switch.
Returns:
None
Raises:
ValueError, Exception
"""
ret = None
for line in output.split('\n'):
if 'Invalid input ' in line or 'error' in line.lower() or \
'Incomplete command' in line or \
'cannot be used as an ACL name' in line or \
'name can\'t be more than 255 characters' in line:
ret = method + ' [ ' + config + ' ]: failed ' + line
break
if ret:
raise ValueError(ret)
ret = method + ' : Successful'
return ret
def _is_parameter_supported(self, supported_params, parameters):
received_params = [k for k, v in parameters.iteritems() if v]
unsupported_params = list(set(received_params) - set(supported_params))
if len(unsupported_params) > 0:
raise ValueError("unsupported parameters provided: {}"
.format(unsupported_params))
@abc.abstractmethod
def add_l2_acl_rule_bulk(self, **kwargs):
"""
Add ACL rule to an existing L2 ACL.
Args:
acl_name (str): Name of the access list.
acl_rules (array): List of ACL sequence rules.
Returns:
True, False or None for Success, failure and no-change respectively
for each seq_ids.
Examples:
>>> from pyswitch.device import Device
>>> with Device(conn=conn, auth=auth,
connection_type='NETCONF') as dev:
>>> print dev.acl.create_acl(acl_name='Acl_1',
acl_type='standard',
address_type='mac')
>>> print dev.acl.add_mac_acl_rule(acl_name='Acl_1', seq_id=20,
action='permit',
source='host',
srchost='2222.2222.2222')
"""
return
@abc.abstractmethod
def delete_l2_acl_rule_bulk(self, **kwargs):
"""
Delete ACL rules from MAC ACL.
Args:
acl_name (str): Name of the access list.
seq_id(string): Range of ACL sequences seq_id="10,30-40"
Returns:
True, False or None for Success, failure and no-change respectively
for each seq_ids.
Examples:
>>> from pyswitch.device import Device
>>> with Device(conn=conn, auth=auth,
connection_type='NETCONF') as dev:
>>> print dev.acl.create_acl(acl_name='Acl_1',
acl_type='standard',
address_type='ip')
>>> print dev.acl.delete_l2_acl_rule_bulk(acl_name='Acl_1',
seq_id="10,30-40")
"""
return
@abc.abstractmethod
def get_acl_rules(self, **kwargs):
"""
Returns the number of congiured rules
Args:
acl_name (str): Name of the access list.
Returns:
Number of rules configured,
Examples:
>>> from pyswitch.device import Device
>>> with Device(conn=conn, auth=auth,
connection_type='NETCONF') as dev:
>>> print dev.acl.get_acl_rules(acl_name='Acl_1',
seq_id='all')
"""
return
|
JavaScript
|
UTF-8
| 410 | 2.859375 | 3 |
[] |
no_license
|
var main = function()
{
draw = function()
{
stroke(255,255,255);
//noStroke();
//stroke(mouseX,mouseY,(mouseY-mouseX));
fill(mouseY, mouseX, (mouseX-mouseY));
if (mouseIsPressed)
{
ellipse(mouseX, mouseY, mouseX, mouseY);
}
else
{
rect(mouseX-(mouseX/2),mouseY-(mouseY/2),mouseX,mouseY);
}
};
};
$(document).ready(main);
|
Swift
|
UTF-8
| 3,054 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// AnodaGameTimer
//
// Created by Oksana Kovalchuk on 9/10/17.
// Copyright © 2017 Oksana Kovalchuk. All rights reserved.
//
import UIKit
import SwiftySound
import SwiftyUserDefaults
import Crashlytics
class MainVC: UIViewController, TimerDelegate {
let contentView: MainView = MainView(frame: CGRect.zero)
let timer: TimerService = TimerService()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
timer.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = contentView
}
override func viewDidLoad() {
super.viewDidLoad()
contentView.pauseButton.addTargetClosure { (button) in
if self.timer.state == .paused || self.timer.state == .initial {
self.timer.updateTo(state: .running)
} else if self.timer.state == .running {
self.timer.updateTo(state: .paused)
}
}
contentView.restartButton.addTargetClosure { (button) in
Answers.logCustomEvent(withName: "Timer restart",
customAttributes: ["Total": self.timer.timerSecondsValue, "Beep": self.timer.beepValue])
self.timer.updateTo(state: .initial)
self.timer.updateTo(state: .running)
}
contentView.settingsButton.addTargetClosure { (button) in
self.navigationController?.pushViewController(SettingsVC.init(delegate: self.timer), animated: true)
}
}
func updated(state: TimerState) {
switch state {
case .initial:
contentView.pieView.update(to: 0, animated: true)
contentView.updateRestartIcon(visible: false)
case .running:
self.contentView.updatePlay(toPause: true)
case .paused:
self.contentView.updatePlay(toPause: false)
case .isOut:
Answers.logCustomEvent(withName: "Time is out",
customAttributes: ["Total": timer.timerSecondsValue, "Beep": timer.beepValue])
self.contentView.updateRestartIcon(visible: true)
}
}
func updated(progress: CGFloat) {
contentView.pieView.update(to: progress, animated: true)
}
func updated(timeInterval: Int?) {
var text: String
if let time = timeInterval {
text = timeString(time: TimeInterval(time))
} else {
text = ""
}
contentView.timerLabel.text = text
}
func timeString(time: TimeInterval) -> String {
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
if minutes > 0 {
return String(format:"%02i:%02i", minutes, seconds)
} else {
return String(format:"%i", seconds)
}
}
}
|
Java
|
UTF-8
| 1,001 | 2.0625 | 2 |
[] |
no_license
|
package com.web.hyundai.model.usedcars;
import lombok.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UsedCarWeb {
private Long id;
private String model;
private Integer price;
private int year;
private Integer mileage;
private String fuel;
private String extColor;
private String intColor;
private String engine;
private double hp;
private String displayPhoto;
private String transmission;
public UsedCarWeb(Long id, Integer price, int year, Integer mileage, String fuel, String extColor, String intColor, String engine, double hp, String displayPhoto, String transmission) {
this.id = id;
this.price = price;
this.year = year;
this.mileage = mileage;
this.fuel = fuel;
this.extColor = extColor;
this.intColor = intColor;
this.engine = engine;
this.hp = hp;
this.displayPhoto = displayPhoto;
this.transmission = transmission;
}
}
|
Java
|
UTF-8
| 1,947 | 1.648438 | 2 |
[] |
no_license
|
package com.zhihu.android.player.upload2.core;
import com.zhihu.android.player.p1801b.C23607a;
/* renamed from: com.zhihu.android.player.upload2.core.d */
/* compiled from: FileUploadTracker */
public class FileUploadTracker {
/* renamed from: a */
public FileParcel f82618a;
/* renamed from: b */
public String f82619b;
/* renamed from: c */
public int f82620c;
/* renamed from: d */
public int f82621d;
/* renamed from: e */
public C23607a f82622e;
/* renamed from: f */
public AbstractAsyncTaskC23645g f82623f;
/* renamed from: g */
public EnumC23644a f82624g;
/* renamed from: h */
public long f82625h;
/* renamed from: i */
public long f82626i;
/* renamed from: j */
public long f82627j;
/* renamed from: k */
public String f82628k;
/* renamed from: l */
public String f82629l;
/* renamed from: m */
public String f82630m;
/* renamed from: n */
public String f82631n;
/* renamed from: com.zhihu.android.player.upload2.core.d$a */
/* compiled from: FileUploadTracker */
public enum EnumC23644a {
NONE,
COMPRESS_START,
COMPRESSING,
COMPRESS_SUCCESS,
COMPRESS_FAILED,
UPLOAD_START,
UPLOADING,
UPLOAD_SUCCESS,
UPLOAD_FAILED,
TRANSCODE_START,
TRANSCODING,
TRANSCODE_SUCCESS,
TRANSCODE_FAILED
}
public FileUploadTracker(FileParcel bVar) {
this.f82618a = bVar;
FileParcel bVar2 = this.f82618a;
if (bVar2 != null) {
this.f82619b = bVar2.f82616b;
}
this.f82624g = EnumC23644a.NONE;
}
public boolean equals(Object obj) {
FileParcel bVar;
if (!(obj instanceof FileUploadTracker) || (bVar = this.f82618a) == null) {
return false;
}
return bVar.equals(((FileUploadTracker) obj).f82618a);
}
}
|
Markdown
|
UTF-8
| 3,312 | 2.859375 | 3 |
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
---
---
---
title: 一个犹太教徒和珍珠的故事
---
相传从前以色列人中,有个虔诚的信徒,为人忠诚老实,他的家属全靠纺纱糊口。他每天把家人纺线的纱带往市中交易;卖掉纱,然后买棉花,并用赚得的钱买食物带回家去,供家人继续纺纱,并维持家人的生活;一天做了一天吃,生活倒也勉强过得下去。
有一天那个虔诚的信徒照例拿纱到市中去经营买卖。在市中,一个弟兄辈的亲戚和他碰头,向他诉苦、求援。他慈悲为怀,慨然把卖纱所得的钱都给那个亲戚,成全别人,宁可不买棉花和食物,而空着手回家去。
家里的人等着棉花纺纱,并急需食物充饥,见他空手回来,问道:“你买的棉花和食物哪儿去了?”
“一个亲戚向我告急,我把卖纱的钱都给他了。”
“家里没有其他可卖的东西,这该怎么办呢?”家里人表示绝望。
没有吃的,家人陷于挨饿的境地。不得已,信徒只好把家中仅有的一个破木托盘和一个旧瓮拿去市中变卖,可是谁也不肯收买那种破旧器皿。正当他耐心等待顾主的时候,可巧一个和他同命运的卖鱼人,打他面前经过,手中拿着一尾发腐而卖不出去的臭鱼。于是二人交谈起来。卖鱼人说道:“让我们把卖不出去的货物互相交换行吗?”
“行。”信徒慨然同意交换货物。
信徒把用破托盘和旧瓮换来的臭鱼带回家去。家里人见了,感觉失望,问道:“我们拿这尾臭鱼怎么办呀?”
“拿去洗干净,烧烤出来,暂时糊口,然后等候上帝分配我们的生计吧。”
家人遵从吩咐,拿鱼去洗,预备烧烤。他们刚破开鱼肚,发现里面有颗珍珠,于是赶忙把情况告诉信徒。
“你们仔细看吧,”信徒说,“假若那颗珍珠被钻过小孔,显然那是别人的财物;要是没有孔,这便是上帝赏赐我们的衣食了。”
他们仔细斟酌,见珍珠还没钻过孔。
次日信徒把珍珠带到市上,给他认识的一个珠宝商看。商人问道:“你哪儿来的这颗珍珠?”
“是上帝赏赐我们的衣禄。”
“这颗珍珠值一千块钱,我愿出此价收买。如果你不愿卖,那就拿去让别的大商人看看吧!他们比我识货,本钱也比我的多。”
信徒果然把珍珠拿去请顶大的珠宝商估价。商人看了货色,说道:“这颗珍珠值七万块钱。这是最高价格,不可能再加价了。”于是兑七万元给信徒,买下那颗珍珠。
信徒雇脚夫担钱回家。刚到门前,便有个乞丐迎面走来,向他乞讨,说道:“你行行好,把上帝赏赐的衣食赏我一点吧!”
“昨天我们的情况跟你差不离,也是没穿少吃的。现在我把钱分一半给你吧。”信徒说着,把卖珍珠的钱一分为二,慨然给乞丐三万五千块钱。
“愿上帝赐福、保佑你。钱我不要你的,请你收起来吧。我不过是奉上帝之命,前来试验你的心肠罢了。”
信徒听了乞丐之言,怡然说道:“赞美、感谢上帝!恩惠全是他赏赐的。”从此他和家人,过着丰衣足食的幸福生活,直至白发千古。
|
SQL
|
UTF-8
| 199 | 2.6875 | 3 |
[] |
no_license
|
set @d1 = '2013-05-01';
set @d2 = '2013-06-09';
SELECT
COUNT(*)
FROM montages
WHERE montage_status = 'In Progress'
AND montages.montage_date_updated >= @d1 and montages.montage_date_updated < @d2
|
Java
|
UTF-8
| 7,597 | 2.703125 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package downlaodtimemvc;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
/**
*
* @author Andrea
*/
public class View {
private JFrame frame;
private JPanel mainPanel, centralPanel, timePanel, speedPanel, filesizePanel;
private JLabel timeLabel, speedLabel, filesizeLabel, hoursLabel, minutesLabel, secondsLabel;
private JTextField hoursTextField, minutesTextField, secondsTextField, speedTextField, filesizeTextField;
private JComboBox speedComboBox, filesizeComboBox;
private JButton speedToTimeButton, timeToSpeedButton;
private final String [] speedTypes = {"kbit/s","kByte/s","Mbit/s","MByte/s"};
private final String [] filesizeTypes = {"B","kB","MB","GB"};
public View(){
//INITIALIZATIONS
frame = new JFrame("DownloadTime");
mainPanel = new JPanel(new BorderLayout());
centralPanel = new JPanel(new GridLayout(6, 0, 0, 0));
timePanel = new JPanel();
speedPanel = new JPanel();
filesizePanel = new JPanel();
timeLabel = new JLabel("Time", SwingConstants.CENTER);
speedLabel = new JLabel("Speed", SwingConstants.CENTER);
filesizeLabel = new JLabel("Filesize", SwingConstants.CENTER);
hoursLabel = new JLabel("H", SwingConstants.CENTER);
minutesLabel = new JLabel("M", SwingConstants.CENTER);
secondsLabel = new JLabel("S", SwingConstants.CENTER);
hoursTextField = new JTextField();
minutesTextField = new JTextField();
secondsTextField = new JTextField();
speedTextField = new JTextField();
filesizeTextField = new JTextField();
speedComboBox = new JComboBox(speedTypes);
filesizeComboBox = new JComboBox(filesizeTypes);
speedToTimeButton = new JButton("<html><center>Calculate<br>Time<br>(from Speed)</html>");
timeToSpeedButton = new JButton("<html><center>Calculate<br>Speed<br>(from Time)</html>");
//FONT
timeLabel.setFont(new Font(timeLabel.getFont().getFontName(), Font.PLAIN, 18));
speedLabel.setFont(new Font(speedLabel.getFont().getFontName(), Font.PLAIN, 18));
filesizeLabel.setFont(new Font(filesizeLabel.getFont().getFontName(), Font.PLAIN, 18));
hoursLabel.setFont(new Font(hoursLabel.getFont().getFontName(), Font.PLAIN, 18));
minutesLabel.setFont(new Font(minutesLabel.getFont().getFontName(), Font.PLAIN, 18));
secondsLabel.setFont(new Font(secondsLabel.getFont().getFontName(), Font.PLAIN, 18));
hoursTextField.setFont(new Font(hoursTextField.getFont().getFontName(), Font.PLAIN, 18));
minutesTextField.setFont(new Font(minutesTextField.getFont().getFontName(), Font.PLAIN, 18));
secondsTextField.setFont(new Font(secondsTextField.getFont().getFontName(), Font.PLAIN, 18));
speedTextField.setFont(new Font(speedTextField.getFont().getFontName(), Font.PLAIN, 18));
filesizeTextField.setFont(new Font(filesizeTextField.getFont().getFontName(), Font.PLAIN, 18));
speedComboBox.setFont(new Font(speedComboBox.getFont().getFontName(), Font.PLAIN, 18));
filesizeComboBox.setFont(new Font(filesizeComboBox.getFont().getFontName(), Font.PLAIN, 18));
speedToTimeButton.setFont(new Font(speedToTimeButton.getFont().getFontName(), Font.PLAIN, 18));
timeToSpeedButton.setFont(new Font(timeToSpeedButton.getFont().getFontName(), Font.PLAIN, 18));
hoursTextField.setHorizontalAlignment(JTextField.CENTER);
minutesTextField.setHorizontalAlignment(JTextField.CENTER);
secondsTextField.setHorizontalAlignment(JTextField.CENTER);
speedTextField.setHorizontalAlignment(JTextField.CENTER);
filesizeTextField.setHorizontalAlignment(JTextField.CENTER);
speedToTimeButton.setHorizontalAlignment(SwingConstants.CENTER);
timeToSpeedButton.setHorizontalAlignment(SwingConstants.CENTER);
//DIMENSIONS
filesizeTextField.setPreferredSize(new Dimension(150,30));
speedTextField.setPreferredSize(new Dimension(150,30));
hoursTextField.setPreferredSize(new Dimension(40,30));
minutesTextField.setPreferredSize(new Dimension(40,30));
secondsTextField.setPreferredSize(new Dimension(40,30));
//BOUNDS
speedComboBox.setBounds(50, 50, 90, 20);
centralPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
//ASSEMBLY
filesizePanel.add(filesizeTextField);
filesizePanel.add(filesizeComboBox);
speedPanel.add(speedTextField);
speedPanel.add(speedComboBox);
timePanel.add(hoursTextField);
timePanel.add(hoursLabel);
timePanel.add(minutesTextField);
timePanel.add(minutesLabel);
timePanel.add(secondsTextField);
timePanel.add(secondsLabel);
centralPanel.add(filesizeLabel);
centralPanel.add(filesizePanel);
centralPanel.add(speedLabel);
centralPanel.add(speedPanel);
centralPanel.add(timeLabel);
centralPanel.add(timePanel);
mainPanel.add(timeToSpeedButton, BorderLayout.WEST);
mainPanel.add(centralPanel, BorderLayout.CENTER);
mainPanel.add(speedToTimeButton, BorderLayout.EAST);
frame.add(mainPanel);
//LAST SETTINGS AND SHOW
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public JButton getSpeedToTimeButton(){
return speedToTimeButton;
}
public JButton getTimeToSpeedButton(){
return timeToSpeedButton;
}
public JTextField getSpeedTextField(){
return speedTextField;
}
public JTextField getFilesizeTextField(){
return filesizeTextField;
}
public JTextField getHoursTextField(){
return hoursTextField;
}
public JTextField getMinutesTextField(){
return minutesTextField;
}
public JTextField getSecondsTextField(){
return secondsTextField;
}
public void setSpeed(float speed){
speedTextField.setText(""+speed);
}
public void setTime(int hours, int minutes, int seconds){
hoursTextField.setText(""+hours);
minutesTextField.setText(""+minutes);
secondsTextField.setText(""+seconds);
}
public void setSpeedSelection(int selection){
speedComboBox.setSelectedIndex(selection);
}
public void setFilesizeSelection(int selection){
filesizeComboBox.setSelectedIndex(selection);
}
public JComboBox getSpeedComboBox(){
return speedComboBox;
}
public JComboBox getFilesizeComboBox(){
return filesizeComboBox;
}
}
|
Java
|
UTF-8
| 565 | 3.4375 | 3 |
[] |
no_license
|
package com.tony.java8.method.reference;
public class MethodReferenceDemo {
public MethodReferenceDemo(){
System.out.println("Indside constructor!");
}
public void m2() {
System.out.println("Indside M2 mnethod ...!");
}
public static void m3() {
System.out.println("Indside M3 mnethod ...!");
}
public static void main(String args[]) {
MethodReferenceDemo demo=new MethodReferenceDemo();
Myinterface myInter=demo::m2;
myInter.m1();
Myinterface myInter2=MethodReferenceDemo::m3;
myInter2.m1();
}
}
|
Ruby
|
UTF-8
| 1,028 | 3.8125 | 4 |
[] |
no_license
|
#!/usr/bin/env ruby
require_relative '../config/environment'
class Cli
def run_game
puts "Welcome to Tic-Tac-Toe."
puts "Please input your choice (0-2): 0 , 1, or 2 Players."
choice = gets.chomp
case choice
when "0"
Game.new(Computer.new('X'), Computer.new('O')).play
when "1"
puts "Please would be X, player or computer (P/C):"
input = gets.chomp.upcase
Game.new(Human.new('X'), Computer.new('O')).play if input == 'P'
Game.new(Computer.new('X'), Human.new('O')).play if input == 'C'
when "2"
puts " which player wants to be X (1/2):"
input = gets.chomp.to_i
if input == 1
human_1 = Human.new('X')
human_2 = Human.new('O')
elsif input == 2
human_1 = Human.new('O')
human_2 = Human.new('X')
end
Game.new(human_1, human_2).play
end
puts "Do you want to play again (Y/n)?"
input = gets.chomp.upcase
if input == "Y"
Cli.new.run_game
else
puts "Thanks for playing TicTacToe. Have a nice day!"
exit
end
end
end
Cli.new.run_game
|
PHP
|
UTF-8
| 199 | 3.3125 | 3 |
[] |
no_license
|
<?php
class FirstDisplayer implements Displayer {
public function display($array)
{
foreach ($array as $row)
{
echo $row . "<br />\n";
}
}
}
|
Java
|
UTF-8
| 2,100 | 1.84375 | 2 |
[] |
no_license
|
package com.example.chen1.uncom.relationship;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import com.example.chen1.uncom.R;
import com.example.chen1.uncom.application.CoreApplication;
import com.example.chen1.uncom.bean.RelationShipLevelBean;
import com.example.chen1.uncom.chat.PersonChatFragment;
import com.example.chen1.uncom.utils.BadgeMessageUtil;
import java.util.ArrayList;
/**
* Created by chen1 on 2017/6/21.
*/
public class PersonItemOnClickListener implements AdapterView.OnItemClickListener {
private ArrayList<RelationShipLevelBean> personFrendList;
private FragmentManager fragmentManager ;
public PersonItemOnClickListener(FragmentManager fragmentManager ,ArrayList<RelationShipLevelBean> relationShipLevelBeanArrayList){
this.personFrendList=relationShipLevelBeanArrayList;
this.fragmentManager=fragmentManager;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BadgeMessageUtil.setSetPageIsVisible(false);
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
PersonChatFragment person_chat_fragment=PersonChatFragment.newInstance(personFrendList.get(position));
if(person_chat_fragment!=null){
Log.v("第一种","...............ok");
person_chat_fragment.setFrendData(personFrendList.get(position));
fragmentTransaction.addToBackStack(null).replace(R.id.drawer_layout,person_chat_fragment,"chatPage").setCustomAnimations(R.anim.default_fragment_switch_leave_translate, R.anim.default_leave_left, R.anim.default_open_right, R.anim.default_fragment_switch_translate_open).commit();
CoreApplication.newInstance().getRoot().startAnimation(AnimationUtils.loadAnimation(CoreApplication.newInstance().getBaseContext(),R.anim.default_leave_left));
}
}
}
|
Python
|
UTF-8
| 1,514 | 3.734375 | 4 |
[
"BSD-3-Clause",
"CC-BY-SA-4.0"
] |
permissive
|
"""Credit to Eli Bendersky"""
from concurrent.futures import ProcessPoolExecutor, as_completed
import math
def factorize_naive(n):
""" A naive factorization method. Take integer 'n', return list of
factors.
"""
if n < 2:
return []
factors = []
p = 2
while True:
if n == 1:
return factors
r = n % p
if r == 0:
factors.append(p)
n = n // p
elif p * p >= n:
factors.append(n)
return factors
elif p > 2:
# Advance in steps of 2 over odd numbers
p += 2
else:
# If p == 2, get to 3
p += 1
assert False, "unreachable"
def chunked_worker(nums):
""" Factorize a list of numbers, returning a num:factors mapping.
"""
return {n: factorize_naive(n) for n in nums}
def pool_factorizer_chunked(nums, nprocs):
# Manually divide the task to chunks of equal length, submitting each
# chunk to the pool.
chunksize = int(math.ceil(len(nums) / float(nprocs)))
futures = []
with ProcessPoolExecutor() as executor:
for i in range(nprocs):
chunk = nums[(chunksize * i): (chunksize * (i + 1))]
futures.append(executor.submit(chunked_worker, chunk))
resultdict = {}
for f in as_completed(futures):
resultdict.update(f.result())
return resultdict
if __name__ == '__main__':
nums = [25, 36, 42, 88, 99]
print(pool_factorizer_chunked(nums, 2))
|
Java
|
UTF-8
| 799 | 3.140625 | 3 |
[] |
no_license
|
package uk.ac.standrews.cs.cs3099.risk.commands;
public class AttackCommand extends Command {
private String command = "attack";
private int[] payload = new int[3];
public AttackCommand(int playerId, int ackId, int source, int dest, int armies)
{
super(playerId, ackId);
payload[0] = source;
payload[1] = dest;
payload[2] = armies;
}
/**
* @return Integer ID of the territory armies are being moved from.
*/
public int getSource()
{
return payload[0];
}
/**
* @return Integer ID of the territory being attacked.
*/
public int getDest()
{
return payload[1];
}
/**
* @return Integer count of the number of armies attacking.
*/
public int getArmies()
{
return payload[2];
}
@Override
public CommandType getType()
{
return CommandType.ATTACK;
}
}
|
Java
|
UTF-8
| 10,357 | 2.046875 | 2 |
[] |
no_license
|
package com.studentstreet;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.studentstreet.adapter.CartAdapter;
import com.studentstreet.entities.CartEntity;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.dbhelper.OrderDBHelper;
/**
* @author likebamboo
*
*/
public class CartActivity extends ListActivity implements OnGestureListener {
// Title标题
private TextView titleText;
// Login Button登录按钮
private Button login_bt;
// 头部左边的按钮
private ImageButton backImgBt = null;
// 购物车的ListView
private ListView cartListView = null;
// ListView适配器.
private CartAdapter adapter = null;
// ListView更新标识。
private final static int LIST_UPDATE = 1;
// 移除商品的小pop
private PopupWindow popupWindow = null;
// 移除商品按钮
private Button deleteButton = null;
// 下达订单按钮
private Button orderButton = null;
// 去购物
private Button goShoppingBt = null;
private OrderDBHelper dbHelper = null;
private List<CartEntity> cartList = null;
// 用户名
private String userName = "";
// OEM++ 侧边栏菜单的手势效果 @ 2013-1-15
private GestureDetector gestureDetector;
// OEM--
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.cart);
// 将当前Activity压入堆栈中
MyApp.getInstance().addActivity(this);
// OEM++ liwt@2013-1-15
gestureDetector = new GestureDetector(this);
// OEM--
// 初始化数据库工具类对象
dbHelper = new OrderDBHelper(this);
// 初始化购物车实体对象
cartList = new ArrayList<CartEntity>();
// 初始化头部
initHeader();
// 初始化布局
cartListView = getListView();
// 去下单按钮
orderButton = (Button) findViewById(R.id.cart_buy);
// 去购物按钮(针对购物车为空的情况)
goShoppingBt = (Button) findViewById(R.id.cart_go_shopping);
orderButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 下达订单,
Intent intent = new Intent(CartActivity.this,
OrderActivity.class);
startActivity(intent);
}
});
goShoppingBt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 回到首页,
Intent intent = new Intent(CartActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
});
}
// 显示移除商品的popUpWindow
private void showPopup(View parent, int position) {
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
// 显示的位置为:屏幕的宽度的一半-PopupWindow的宽度的一半
int width = windowManager.getDefaultDisplay().getWidth();
int height = windowManager.getDefaultDisplay().getHeight();
if (popupWindow == null) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater
.inflate(R.layout.cart_delete_popup, null);
deleteButton = (Button) view.findViewById(R.id.cart_delete);
// 创建一个PopuWidow对象
popupWindow = new PopupWindow(view, width / 3, height / 7);
}
// 使其聚集
popupWindow.setFocusable(true);
// 设置允许在外点击消失
popupWindow.setOutsideTouchable(true);
// 这个是为了点击“返回Back”也能使其消失,并且并不会影响你的背景
popupWindow.setBackgroundDrawable(new BitmapDrawable());
// 显示的位置为:屏幕的宽度的一半-PopupWindow的宽度的一半
int xPos = width - popupWindow.getWidth() / 2;
popupWindow.showAsDropDown(parent, xPos, 0);
// 这条语句不可放在if(popupWindown==null)中,要不然当popupWindow!=null时就不会执行了,那么就会报错。
// 如果一定要放在里面,那么必须将popupWindow声明为这个方法的局部变量而不是类成员变量。
deleteButton.setOnClickListener(new DeleteListener(position));
}
private void initHeader() {
// 返回按钮
backImgBt = (ImageButton) findViewById(R.id.header_imgBt);
// 头部中间的标题
titleText = (TextView) findViewById(R.id.title);
// 登录按钮
login_bt = (Button) findViewById(R.id.login_bt);
// 返回按钮
backImgBt.setImageResource(R.drawable.back);
backImgBt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// 头部中间的标题
titleText.setText(getResources().getString(R.string.cart));
// 登录按钮
login_bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 显示登录对话框
Intent intent = new Intent(CartActivity.this, LoginDialog.class);
startActivity(intent);
}
});
}
@Override
protected void onResume() {
super.onResume();
// 获得用户名
PreferenceTools prefTools = new PreferenceTools(this);
if (!prefTools.isLogin()) {
return;
}
// 登录后修改登录按钮上的text
String userNameTemp = prefTools.getUserName();
// 当用户名有更新时候
if (!userNameTemp.equals(userName)) {
userName = userNameTemp;
// 修改用户名
if (!userName.equals("")) {
login_bt.setText(userName);
// 去掉登录按钮文本右边的图标
login_bt.setCompoundDrawablesWithIntrinsicBounds(null, null,
null, null);
}
// 创建(更新)适配器
adapter = new CartAdapter(this, userName);
cartListView.setAdapter(adapter);
// 添加ListView的Item点击事件
cartListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter,
View view, int postion, long arg3) {
// 显示移除该商品的popUpWindow
showPopup(view, postion);
}
});
}
// 启动数据查询线程
Thread queryDataThread = new Thread(new QueryDataThread());
queryDataThread.start();
}
// 查询数据库线程
class QueryDataThread implements Runnable {
@Override
public void run() {
// 查询数据库中的订单项信息
cartList = dbHelper.getCart(userName);
// 将数据添加到适配器中
adapter.addCartList(cartList);
Message msg = handler.obtainMessage();
msg.what = LIST_UPDATE;
handler.sendMessage(msg);
}
}
// 移除商品的监听器
class DeleteListener implements OnClickListener {
private int position = 0;
public DeleteListener(int position) {
this.position = position;
}
@Override
public void onClick(View v) {
// 让popupwindow 消失
popupWindow.dismiss();
// 如果移除数据不成功,直接返回null;
if (!adapter.removeCart(position)) {
return;
}
// 移除成功。发送一个消息
Message msg = handler.obtainMessage();
msg.what = LIST_UPDATE;
handler.sendMessage(msg);
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case LIST_UPDATE:
// 通知ListView有更新
adapter.notifyDataSetChanged();
break;
default:
break;
}
super.handleMessage(msg);
}
};
// OEM++手势滑动 李文涛@2013-1-15
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
/**
* 用户按下触摸屏、快速移动后松开
*/
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.i("MyGesture", "onFling");
final int FLING_MIN_DISTANCE = 100, FLING_MIN_VELOCITY = 200;
if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
// Fling right
LeftMenu.prepare(CartActivity.this, R.id.cart_layout);
startActivity(new Intent(CartActivity.this, LeftMenu.class));
overridePendingTransition(0, 0);
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
/**
* 解决ScrollView后不执行左右移动监听事件OnGestureListener
* 在Activity中添加ScrollView实现滚动activity的效果后,activity的滑动效果却无法生效了
* 原因是因为activity没有处理滑动效果,重写以下方法即可解决。
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
gestureDetector.onTouchEvent(ev);
return super.dispatchTouchEvent(ev);
}
//OEM--
// OEM++ 2013-02-27 监听菜单按钮事件,实现与手势相同的滑动效果
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
LeftMenu.prepare(CartActivity.this, R.id.cart_layout);
startActivity(new Intent(CartActivity.this, LeftMenu.class));
overridePendingTransition(0, 0);
return false;
}
// OEM--
}
|
Java
|
UTF-8
| 478 | 2.09375 | 2 |
[] |
no_license
|
package App.Generic;
import org.testng.Assert;
public class ResponseCode {
public int SuccessResponseCode = 200;
public int ServerResponseCode = 500;
public int PageNotFoundResponseCode = 404;
public int PageAuthenticationCode = 401;
/*
* public void SuccessCode(int Code) {
*
* Assert.assertEquals(SuccessResponseCode, Code); }
*
* public void ServerErrorCode(int Code) {
*
* Assert.assertEquals(ServerResponseCode, Code); }
*/
}
|
JavaScript
|
UTF-8
| 1,709 | 2.515625 | 3 |
[] |
no_license
|
const validateUserName = (userName) => {
if (!userName || userName.length === 0) {
return 'هذا الحقل مطلوب';
} else {
return null;
}
};
const validateEmail = (email) => {
if (!email || email.length === 0) {
return 'هذا الحقل مطلوب';
// } else if (
// !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(
// String(email).toLowerCase(),
// )
// ) {
// return 'البريد الالكتروني غير صحيح';
} else {
return null;
}
};
const validatePhone = (phone) => {
var phoneno = /^\d{11}$/;
if (!phone || phone.length === 0) {
return 'هذا الحقل مطلوب';
} else if (!phone.match(phoneno)) {
return 'رقم الهاتف غير صحيح';
} else {
return null;
}
};
const validatePasswordAndConfirm = (password, passwordConfirm) => {
return password != passwordConfirm ? 'رمز المرور غير متطابق' : null;
};
const validatePassword = (password) => {
if (password.length === 0) {
return 'هذا الحقل مطلوب';
} else if (password.length < 6) {
return 'يجب الا يقل رمز المرور عن 6 احرف';
} else {
return null;
}
};
const validatePasswordConfirm = (passwordConfirm) => {
if (passwordConfirm.length === 0) {
return 'هذا الحقل مطلوب';
} else if (passwordConfirm.length < 6) {
return 'يجب الا يقل رمز المرور عن 6 احرف';
} else {
return null;
}
};
export {
validateUserName,
validateEmail,
validatePhone,
validatePassword,
validatePasswordAndConfirm,
validatePasswordConfirm,
};
|
Java
|
UTF-8
| 987 | 1.742188 | 2 |
[] |
no_license
|
package com.pointlion.sys.mvc.common.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseOaBumphOrgUser<M extends BaseOaBumphOrgUser<M>> extends Model<M> implements IBean {
public void setId(java.lang.String id) {
set("id", id);
}
public java.lang.String getId() {
return get("id");
}
public void setUserId(java.lang.String userId) {
set("user_id", userId);
}
public java.lang.String getUserId() {
return get("user_id");
}
public void setUserName(java.lang.String userName) {
set("user_name", userName);
}
public java.lang.String getUserName() {
return get("user_name");
}
public void setBumphOrgId(java.lang.String bumphOrgId) {
set("bumph_org_id", bumphOrgId);
}
public java.lang.String getBumphOrgId() {
return get("bumph_org_id");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.