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
|
|---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 15,633
| 2.8125
| 3
|
[] |
no_license
|
import sklearn.cluster as clus
import sklearn.decomposition as dc
import sklearn.preprocessing as pr
from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pandas as pd
import os
if not(os.path.isdir("tarea")):
os.mkdir("tarea")
# function to scale data acording to different
def dataScaled(data):
# Creating dictionary to store the different data frames
data = {"original":df}
# Standarizing data to have mean 0 and variance 1
scaler = pr.StandardScaler()
scaler.fit(df)
data["standarized"] = pd.DataFrame(scaler.transform(df),index=df.index,columns=df.columns)
# Centering data to have variance 1
scaler = pr.StandardScaler(with_mean=False)
scaler.fit(df)
data["withmean"] = pd.DataFrame(scaler.transform(df),index=df.index,columns=df.columns)
return data
# function to export the PCA coefficient table
def compCoefTable(model,data):
p = len(data.columns)
c = int(np.floor(np.log10(p)+1))
names = ["PC"+"{0}".format(i).zfill(c) for i in range(len(data.columns))]
return pd.DataFrame(model.components_, index = names,columns = data.columns)
# function to export the singular value table
def singvalTable(model,data):
p = len(data.columns)
c = int(np.floor(np.log10(p)+1))
names = ["PC"+"{0}".format(i).zfill(c) for i in range(len(data.columns))]
return pd.DataFrame(model.singular_values_,index =names).transpose()
# function to create the PVE table using the scikit-learn package
def pveTable(model,data):
p = len(data.columns)
c = int(np.floor(np.log10(p)+1))
names = ["PC"+"{0}".format(i).zfill(c) for i in range(len(data.columns))]
return pd.DataFrame(model.explained_variance_ratio_,index=names,columns = ["PVE"]).transpose()
#function to calculate the PVE of the m-th principal component
def pve(m,model,data):
n,p = df.shape
norm = 0
s = 0
for i in range(n):
temp = 0
for j in range(p):
#print("s = {0}".format(s))
#print("norm = {0}".format(norm))
temp = temp + model.components_[m][j]*data.iloc[i][j]
norm = norm + data.iloc[i][j]**2
s = s + temp**2
return s/norm
#function to create the PVE table using the PVE(model,data) function
def pveFromFormulaTable(model,data):
p = len(data.columns)
c = int(np.floor(np.log10(p)+1))
names = ["PC"+"{0}".format(i).zfill(c) for i in range(len(data.columns))]
vals = [pve(i,model,data) for i in range(p)]
return pd.DataFrame(vals,index=names,columns = ["PVE"]).transpose()
# Auxiliar function taken from https://scikit-learn.org/stable/auto_examples/cluster/plot_agglomerative_dendrogram.html
# for plotting dendogram of agglomerative clustering
def plotDendogram(model, **kwargs):
# Create linkage matrix and then plot the dendrogram
# create the counts of samples under each node
counts = np.zeros(model.children_.shape[0])
n_samples = len(model.labels_)
for i, merge in enumerate(model.children_):
current_count = 0
for child_idx in merge:
if child_idx < n_samples:
current_count += 1 # leaf node
else:
current_count += counts[child_idx - n_samples]
counts[i] = current_count
linkage_matrix = np.column_stack([model.children_, model.distances_,
counts]).astype(float)
# Plot the corresponding dendrogram
dendrogram(linkage_matrix, **kwargs)
# function for returning lists with all clusters
def clusters(fit,data):
clu = [[] for i in range(fit.n_clusters_)]
for i in range(fit.n_leaves_):
clu[fit.labels_[i]].append(data.index[i])
return clu
def plotClusteringResults(fit,df,s=20):
#labels = (fit.labels_-fit.labels_[0]) % nclus
labels = fit.labels_
clusColors = ["C{0}".format(i) for i in labels]
normColors = ["C{0}".format(i) for i in df["initG"]]
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122, projection='3d')
ax1.scatter(df.iloc[:,0],df.iloc[:,1],df.iloc[:,2],s=s,c=clusColors)
ax1.view_init(30, 45)
ax1.set_title("Clustering")
ax2.scatter(df.iloc[:,0],df.iloc[:,1],df.iloc[:,2],s=s,c=normColors)
ax2.view_init(30, 45)
ax2.set_title("Normal Groups")
# Exercise 8
# Reading data
df = pd.read_csv("USArrests.csv",header=0,index_col=0)
print(df.head())
df.head().to_latex(buf="tarea/1-head.tex")
# Making PCA over standarized data for effecive PCA
data = dataScaled(df)
print(data["standarized"].head())
model = dc.PCA()
model.fit(data["standarized"])
x = compCoefTable(model,data["standarized"])
print(x)
x.to_latex(buf="tarea/1-coeffTable.tex",float_format = "{:0.4f}".format)
print(singvalTable(model,data["standarized"]))
# calculating PVE table from package
x = pveTable(model,data["standarized"])
print(x)
x.to_latex(buf="tarea/1-pve.tex",float_format = "{:0.4f}".format)
# calculating PVE table using formula
x = pveFromFormulaTable(model,data["standarized"])
print(x)
x.to_latex(buf="tarea/1-pveForm.tex",float_format = "{:0.4f}".format)
# Exercise 9
print(data["withmean"].head())
# Performinc hierarchical clustering over different linkages
res = pd.DataFrame(index=data["original"].index)
for l in ["complete","single","average"]:
for name, df in data.items():
model = clus.AgglomerativeClustering(linkage=l,affinity = "euclidean",distance_threshold=0.0,n_clusters=None)
fit = model.fit(X=df)
plt.figure(figsize=(12,5))
plotDendogram(fit,labels=df.index)
plt.grid()
plt.title("Linkage: {0}, Data: {1}".format(l,name))
plt.tight_layout()
plt.savefig("tarea/2-{0}{1}.pdf".format(l,name))
plt.show()
model = clus.AgglomerativeClustering(linkage=l,affinity = "euclidean",n_clusters=3)
fit = model.fit(X=df)
# making first observation be in cluster 0
res["Cluster {0} {1}".format(l,name)] = (fit.labels_ - fit.labels_[0]) % 3
tabs = "c"
for i in range(0,res.shape[1]):
tabs = tabs + "p{1.5cm}"
res.index = [a[0:7] for a in res.index]
res.to_latex(buf = "tarea/2-clusresults.tex",column_format=tabs,longtable=True)
# Exercise 10
n=50
ng = 3
gobs = 20
g = []
df = pd.DataFrame()
for i in range(ng):
mean = np.zeros(n)
mean[i] = 1.0
obs = np.array([np.random.rand(n) + mean for i in range(gobs)])
aux = pd.DataFrame(obs)
aux["initG"] = i
df = df.append(aux,ignore_index=True)
print(df.head())
data = dataScaled(df.drop(columns="initG"))
for name,df1 in data.items():
df1["initG"] = df["initG"]
model = clus.KMeans(n_clusters=3)
fit = model.fit(X=data["original"].drop(columns="initG"))
fig = plt.figure(figsize=(12,6))
plotClusteringResults(fit,data["original"],s=80)
plt.tight_layout()
plt.savefig("tarea/3-initClus.pdf")
plt.show()
model = dc.PCA()
model.fit(data["original"].drop(columns="initG"))
compCoefTable(model,data["original"].drop(columns="initG"));
trans = model.transform(data["original"].drop(columns="initG"))
trans = pd.DataFrame(trans,columns = pveTable(model,data["original"].drop(columns="initG")).columns)
trans["initG"] = data["original"]["initG"]
normColors = ["C{0}".format(i) for i in data["original"]["initG"]]
plt.figure()
plt.title("Principal components")
plt.xlabel("PC0")
plt.ylabel("PC1")
plt.scatter(trans["PC00"],trans["PC01"], color = normColors)
plt.grid()
plt.tight_layout()
plt.savefig("tarea/3-pca.pdf")
plt.show()
print(pveTable(model,data["original"].drop(columns="initG")))
res = pd.DataFrame(index = data["original"].index)
for name,df in data.items():
for j in [3,2,4]:
model = clus.KMeans(n_clusters=j)
fit = model.fit(X=df.drop(columns="initG"))
labels = (fit.labels_ - fit.labels_[0] )% j
res["K: {0} , data: {1}".format(j,name)] = labels
fig = plt.figure(figsize=(12,6))
plotClusteringResults(fit,df,s=80)
plt.suptitle("N clusters = {0}, data: {1}".format(j,name),fontsize=20)
plt.tight_layout()
plt.savefig("tarea/3-{1}-{0}.pdf".format(j,name))
plt.show()
tabs = "c"
for i in range(0,res.shape[1]):
tabs = tabs + "p{1.5cm}"
res.to_latex(buf = "tarea/3-clusresults.tex",column_format=tabs,longtable=True)
for j in [3,2,4]:
model = clus.KMeans(n_clusters=j)
fit = model.fit(X=trans.drop(columns="initG"))
fig = plt.figure(figsize=(12,6))
plotClusteringResults(fit,trans,s=50)
plt.suptitle("N clusters = {0}, data: transformed to PC".format(j,name),fontsize=20)
plt.tight_layout()
plt.savefig("tarea/3-fullpcs-{0}.pdf".format(j))
plt.show()
res = pd.DataFrame(index=data["original"].index)
for j in [3,2,4]:
model = clus.KMeans(n_clusters=j)
fit = model.fit(X=trans.iloc[:,[0,1]])
labels = (fit.labels_ - fit.labels_[0]) % j
res["data: pca 2 vars, K={0}".format(j)] = labels
fig = plt.figure(figsize=(12,6))
plotClusteringResults(fit,trans,s=50)
plt.suptitle("N clusters = {0}, data: transformed to PC".format(j,name),fontsize=20)
plt.tight_layout()
plt.savefig("tarea/3-2pcs-{0}.pdf".format(j))
plt.show()
tabs = "c"
for i in range(0,res.shape[1]):
tabs = tabs + "p{3cm}"
res.to_latex(buf = "tarea/3-clusresults-pca.tex",column_format=tabs,longtable=True)
# Exercise 11
# Reading Data
df = pd.read_csv("Ch10Ex11.csv",header=None)
df = df.transpose()
data = dataScaled(df)
print(df.head().iloc[:,0:5])
df.head().iloc[:,0:5].to_latex("tarea/4-initData.tex",float_format="{:0.4f}".format)
res = pd.DataFrame(index=data["original"].index)
for l in ["complete","single","average"]:
for name, df in data.items():
model = clus.AgglomerativeClustering(linkage=l,affinity = "correlation",distance_threshold=0.0,n_clusters=None)
fit = model.fit(X=df)
plt.figure(figsize=(12,5))
plotDendogram(fit,labels=df.index)
plt.grid()
plt.title("Linkage: {0}, Data: {1}".format(l,name))
plt.tight_layout()
plt.savefig("tarea/4-{0}{1}.pdf".format(l,name))
plt.show()
model = clus.AgglomerativeClustering(linkage=l,affinity = "correlation",n_clusters=2)
fit = model.fit(X=df)
# making first observation be in cluster 0
res["Cluster {0} {1}".format(l,name)] = (fit.labels_ - fit.labels_[0]) % 2
tabs = "c"
for i in range(0,res.shape[1]):
tabs = tabs + "p{1.5cm}"
res.to_latex(buf="tarea/4-clusres.tex",longtable=True,column_format=tabs)
# method 1: calculating variance and getting gen that maximizes it
df = data["standarized"]
genDif = {}
for name,df in data.items():
health = df.iloc[0:20,:]
sick = df.iloc[20:,:]
norms = []
for i in data["original"].columns:
diffvec = [health.loc[n,i] - sick.loc[m,i] for n in health.index for m in sick.index]
norms.append(np.linalg.norm(diffvec))
genDif[name] = norms.index(max(norms))
print(genDif)
for name,gen in genDif.items():
plt.figure()
plt.title("Gen that maximizes |A_k|: {0} \n Linkage: {1}".format(gen,name))
plt.hist(health.loc[:,gen],alpha=0.7)
plt.hist(sick.loc[:,gen],alpha=0.7)
plt.grid()
plt.tight_layout()
plt.savefig("tarea/4-Ak-{0}.pdf".format(name))
plt.show()
# Method 1: calculating variance and getting 20 gens that maximize it
genDif = {}
dists = {}
n=20
for name,df in data.items():
health = df.iloc[0:20,:]
sick = df.iloc[20:,:]
norms = []
for i in data["original"].columns:
diffvec = [health.loc[n,i] - sick.loc[m,i] for n in health.index for m in sick.index]
norms.append(np.linalg.norm(diffvec))
genDif[name] = list(np.argsort(norms))[-n:]
dists[name] = list(sorted(norms))[-n:]
print(genDif)
res = pd.DataFrame()
for name,lis in genDif.items():
res[name] = lis
res[name + " variance distance"] = dists[name]
tabs = "c"
for i in range(res.shape[1]):
tabs += "p{2cm}"
res.to_latex("tarea/4-variance-distance.tex",column_format=tabs,longtable=True,float_format="{:0.2f}".format)
# Method 2: looking for a gen which removing it causes clustering fail
df = data["standarized"]
for l in ["complete","single","average"]:
for i in df.columns:
aux = df.drop(columns=i)
model = clus.AgglomerativeClustering(linkage=l,affinity = "correlation",n_clusters=2)
fit = model.fit(X=aux)
cluslabels = [0 for i in range(20)] + [1 for i in range(20)]
labels = list((fit.labels_ - fit.labels_[0] ) % 2)
if cluslabels != labels:
print("Whitout this gen, clustering fails")
print(cluslabels)
print(labels)
print(i)
# Looking for the gene that makes posible the clustering with only with him as variable
genDif = {}
for l in ["complete","single","average"]:
for i in df.columns:
aux = pd.DataFrame(df[i])
# distance has to be euclidean in order to avoid problems
model = clus.AgglomerativeClustering(linkage=l,affinity = "euclidean",n_clusters=2)
fit = model.fit(X = aux)
cluslabels = [0 for i in range(20)] + [1 for i in range(20)]
labels = list((fit.labels_ - fit.labels_[0] ) % 2)
if cluslabels == labels:
print("With this gene, clustering works ")
print(i)
# Method 3: Looking for the gene that minimizes the classification error
genDif = {}
for l in ["complete","single","average"]:
vec = []
for i in df.columns:
aux = pd.DataFrame(df[i])
# distance has to be euclidean in order to avoid problems
model = clus.AgglomerativeClustering(linkage=l,affinity = "euclidean",n_clusters=2)
fit = model.fit(X = aux)
cluslabels = [0 for i in range(20)] + [1 for i in range(20)]
labels = list((fit.labels_ - fit.labels_[0] ) % 2)
errors = 0
for i,lab in enumerate(cluslabels):
if labels[i] != lab:
errors = errors + 1
vec.append(errors/df.shape[0])
mingens = [x[0] for x in enumerate(vec) if vec[x[0]]==min(vec)]
if len(mingens) == 1:
genDif[l] = mingens[0]
else:
print("These gens minimize error:")
print(mingens)
print(genDif)
for name,gen in genDif.items():
plt.figure()
plt.title("Gen with minimal classification error: {0} \n Linkage: {1}".format(gen,name))
plt.hist(health.loc[:,gen],alpha=0.7)
plt.hist(sick.loc[:,gen],alpha=0.7)
plt.grid()
plt.tight_layout()
plt.savefig("tarea/4-minimal-{0}.pdf".format(name))
plt.show()
# Looking for the 20 genes that minimizes the classification error
genDif = {}
errs = {}
n = 20
for l in ["complete","single","average"]:
vec = []
for i in df.columns:
aux = pd.DataFrame(df[i])
# distance has to be euclidean in order to avoid problems
model = clus.AgglomerativeClustering(linkage=l,affinity = "euclidean",n_clusters=2)
fit = model.fit(X = aux)
cluslabels = [0 for i in range(20)] + [1 for i in range(20)]
labels = list((fit.labels_ - fit.labels_[0] ) % 2)
errors = 0
for i,lab in enumerate(cluslabels):
if labels[i] != lab:
errors = errors + 1
vec.append(errors/df.shape[0])
mingens = list(np.argsort(vec)[0:n])
genDif[l] = mingens
errs[l] = sorted(vec)[0:n]
print(genDif)
res = pd.DataFrame()
for name,lis in genDif.items():
res[name] = lis
res[name + " error ratio"] = errs[name]
tabs = "c"
for i in range(res.shape[1]):
tabs += "p{2cm}"
res.to_latex("tarea/4-errors-ratio.tex",column_format=tabs,longtable=True)
res = pd.DataFrame(index = data["original"].index)
|
TypeScript
|
UTF-8
| 926
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
import { Constants } from '../runtime/defs';
import { stop } from '../runtime/run';
import { add } from './add';
import { double } from './bignum';
import { multiply } from './multiply';
// power function for double precision floating point
export function dpow(base: number, expo: number) {
// divide by zero?
if (base === 0.0 && expo < 0.0) {
stop('divide by zero');
}
// nonnegative base or integer power?
if (base >= 0.0 || expo % 1.0 === 0.0) {
return double(Math.pow(base, expo));
}
const result = Math.pow(Math.abs(base), expo);
const theta = Math.PI * expo;
let a = 0.0;
let b = 0.0;
// this ensures the real part is 0.0 instead of a tiny fraction
if (expo % 0.5 === 0.0) {
a = 0.0;
b = Math.sin(theta);
} else {
a = Math.cos(theta);
b = Math.sin(theta);
}
return add(
double(a * result),
multiply(double(b * result), Constants.imaginaryunit)
);
}
|
Python
|
UTF-8
| 3,030
| 3.203125
| 3
|
[] |
no_license
|
'''
# NOTES
df access/structure mimics dictionary access (see ex. below) w/ keys being columns and values being arrays
sample df:
df1 = pd.DataFrame({"HPI":[80,85,88,85],
"Index": [0,1,2,3]})
# pickling serializes and saves bytecode of code modules/objects.
df = read_csv("newcsv4.csv", names=["Date", "Austin_HPI"], index_col=0)
#convert to HTML table
df.to_html("example.html")
df.rename(columns={"Austin_HPI": "78756_HPI"}, in_place=True)
print(df.head()
'''
import pandas as pd
import quandl, pickle
import matplotlib.pyplot as plt
from matplotlib import style
style.use("fivethirtyeight")
# get list of 50 states from wikipedia, states is a list of pandas dataframes
def get_states():
states = pd.read_html("https://simple.wikipedia.org/wiki/List_of_U.S._states")
return states[0][0][1:]
#populate dataframe
def get_housing_data():
states = get_states()
main_df = pd.DataFrame()
state_abrvs = []
for ste in states:
state_abrvs.append(ste)
query = "FMAC/HPI_"+str(ste)
df = quandl.get(query, auth_token="-pj7iy-RshhTAs4i2J89")
df.columns = [str(ste)]
df["United States"] = (df["United States"] - df["United States"][0])/ df["United States"][0] * 100.0
if main_df.empty:
main_df = df
else:
main_df = main_df.join(df)
main_df.to_csv("housing_data.csv")
# pickle data
pickle_out = open("50_states.pickle", "wb")
pickle.dump(main_df, pickle_out)
pickle_out.close()
#pickle_in = open("50_states.pickle", "rb")
#HPI_data = pickle.load(pickle_in)
# pickling with pandas
# HPI_data.to_pickle("pickle.pickle")
# HPI_data2 = pd.read_pickle("pickle.pickle")
# print(HPI_data2)
def get_ATX_data():
df = quandl.get("ZILLOW/Z78756_ZRISFRR", authtoken="-pj7iy-RshhTAs4i2J89")
df.columns = ["Austin"]
df["Austin"] = (df["Austin"] - df["Austin"][0])/ df["Austin"][0] * 100.0
return df
#get housing index benchmark data
def get_HPI_benchmark():
df = quandl.get("FMAC/HPI_USA", auth_token="-pj7iy-RshhTAs4i2J89")
df.columns = ["United States"]
df["United States"] = (df["United States"] - df["United States"][0])/ df["United States"][0] * 100.0
return df
# DATA ACQUIRED! - comment out get function
#get_housing_data()
def plotter():
HPI_data = pd.read_pickle("50_states.pickle")
# PLOTTING - works!
benchmark = get_HPI_benchmark()
# create plotting instance
fig = plt.figure()
# plot Austin housing market data against benchmark
ax2 = fig.add_subplot(212)
get_ATX_data().plot(ax=ax2, color = "k", linewidth=7)
plt.legend(loc=4)
ax2.xaxis.set_visible(True)
ax2.set_title("Austin Housing Market % Increase")
ax2.set_xlabel("")
# plot HPI data for all 50 states + benchmark avg
ax1 = fig.add_subplot(211)
HPI_data.plot(ax = ax1)
benchmark.plot(ax=ax1, color = "k", linewidth=7)
plt.legend().remove()
ax1.xaxis.set_visible(True)
ax1.set_title("State Housing Markets % Increase")
ax1.set_xlabel("")
# show plots
plt.show()
plotter()
# descriptive stats
#HPI_State_Correlation = HPI_data.corr()
#print(HPI_State_Correlation)
#print(HPI_State_Correlation.describe())
|
Python
|
UTF-8
| 2,360
| 2.90625
| 3
|
[] |
no_license
|
import sys
import re
class jsParser:
jsStringRe = "(?:\s*)(?:"\
"(?:'((?:(?:[^\\']|.'))*?)')|(?:\"((?:(?:[^\\\"]|.\"))*?)\")"\
")(?:\s*)(?:,*)(?:\s*)"
doubleChecker = re.compile("Localize\s*\(")
tables = {}
def __init__(self):
self.matcher = re.compile("Localize(?:\s*)\((?:" + self.jsStringRe + ")(?:" + self.jsStringRe + ")?(?:" + self.jsStringRe + ")?\)", re.VERBOSE)
def startFileProcessing(self, contents):
pass
def tablesForData(self, string, comment, table):
return [table]
def processFile(self, path, filename):
file = open(path, "r")
text = file.read()
file.close()
self.startFileProcessing(text)
found = 0
doubleCheckerMatches = self.doubleChecker.findall(text)
for m in self.matcher.finditer(text):
found += 1
self.processMatch(m.groups(), filename, m.start())
if found != len(doubleCheckerMatches):
print >> sys.stderr, "Only found %d out of %d. %s" % (found, len(doubleCheckerMatches), path)
def processMatch(self, match, filename, position):
string = match[0]
comment = match[2] if len(match) > 2 else None
table = match[4] if len(match) > 4 else None
if string is None or len(string) <= 0:
string = match[1]
if len(match) > 2:
if comment is None or len(comment) <= 0:
comment = match[3]
if len(match) > 4:
if table is None or len(table) <= 0:
table = match[5]
if string is None or len(string) == 0:
return
string = string.decode("string-escape")
if table is None or len(table) <= 0:
table = 'Default'
for table in self.tablesForData(string, comment, table):
if not table in self.tables:
self.tables[table] = {}
if not string in self.tables[table]:
self.tables[table][string] = {'comments': [], 'occurrences': []}
if not comment is None and not comment in self.tables[table][string]['comments']:
self.tables[table][string]['comments'].append(comment)
self.tables[table][string]['occurrences'].append((filename, position))
return (string, comment, table)
|
Python
|
UTF-8
| 625
| 3.328125
| 3
|
[] |
no_license
|
import requests
from bs4 import BeautifulSoup
n = str(input("masukkan link/url: "))
url = n
#membuat requests
r = requests.get(url)
#hasil response
request = r.content
filename = "tes.txt"
f = open(filename, "w")
headers = "sumber : "+ url + "\n"
f.write(headers)
soup = BeautifulSoup(request, 'html.parser')
#extract element
title = soup.find_all('a', attrs={'class':'bookTitle'})
author = soup.find_all('a', attrs={'class':'authorName'})
count = 0
for x in range(0, len(title)):
count += 1
print("{0}. {1}\n -{2}".format(count, title[x].text.strip(), author[x].text.strip()))
|
Java
|
UTF-8
| 1,624
| 2.140625
| 2
|
[] |
no_license
|
package br.com.milebrito.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.google.appengine.api.utils.SystemProperty;
import br.com.milebrito.beans.Galeria;
import br.com.milebrito.services.StorageServiceImpl;
/**
* Spring MVC Controller
* <br>
* Controla as chamadas das telas
* @author Felipe Brito
*
*/
@Controller
public class MileBritoController {
private Log log = LogFactory.getLog(MileBritoController.class);
private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ssss");
/**
* Inicia o sistema
* @return
*/
@RequestMapping("/")
public String index(Model model) {
String horaInicial = sdf.format(new Date());
log.info(horaInicial);
String ambiente = SystemProperty.Environment.environment.get();
log.info("[INDEX] - Ambiente: " + ambiente);
try {
StorageServiceImpl storageServiceImpl = new StorageServiceImpl();
List<Galeria> galerias = storageServiceImpl.listarGalerias();
List<String> carrossel = storageServiceImpl.listarUrlsImagensCarrossel();
model.addAttribute("galerias", galerias);
model.addAttribute("carrossel", carrossel);
String horaFinal = sdf.format(new Date());
log.info(horaFinal);
return "index";
} catch (Exception e) {
log.error(e);
throw new RuntimeException(e);
}
}
}
|
Java
|
UTF-8
| 1,202
| 2.46875
| 2
|
[] |
no_license
|
package com.example.kwy2868.practice.network;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class APIManager {
private static final String BASE_URL = "http://203.252.166.230";
private static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
private static OkHttpClient client = new OkHttpClient.Builder().addInterceptor(getInterceptor()).build();
public static HttpLoggingInterceptor getInterceptor() {
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return interceptor;
}
private static Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
private static UserService userService = retrofit.create(UserService.class);
public static UserService getUserService() {
return userService;
}
private static MusicService musicService = retrofit.create(MusicService.class);
public static MusicService getMusicService() {
return musicService;
}
}
|
Java
|
UTF-8
| 6,507
| 2.34375
| 2
|
[] |
no_license
|
package uit.cnpm02.dkhp.controllers;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import uit.cnpm02.dkhp.model.TrainClass;
import uit.cnpm02.dkhp.service.IFileUploadService;
import uit.cnpm02.dkhp.service.ITrainClassService;
import uit.cnpm02.dkhp.service.impl.FileUploadServiceImpl;
import uit.cnpm02.dkhp.service.impl.TrainClassServiceImpl;
import uit.cnpm02.dkhp.model.FileInfo;
import uit.cnpm02.dkhp.utilities.MultipartMap;
import uit.cnpm02.dkhp.utilities.StringUtils;
/**
*
* @author LocNguyen
*/
@WebServlet(name = "FileUploadController", urlPatterns = {"/FileUploadController"})
public class FileUploadController extends HttpServlet {
private IFileUploadService fuService = new FileUploadServiceImpl();
private ITrainClassService trainClassService = new TrainClassServiceImpl();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
session.removeAttribute("msg");
try {
String action = request.getParameter("function");
if (action.equalsIgnoreCase(FileUploadSupport
.DEFAULT.getValue())) {
doDefaultAction(request, response);
} else if (action.equalsIgnoreCase(FileUploadSupport
.VALIDATE_FILENAME.getValue())) {
doValidateFileName(request, response);
} else if (action.equalsIgnoreCase(FileUploadSupport
.UPLOAD_FILE.getValue())) {
doUploadFile(request, response);
}
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private void doUploadFile(HttpServletRequest request,
HttpServletResponse response) throws IOException {
try {
MultipartMap multiPart = new MultipartMap(request, this);
doDefaultAction(request, response);
} catch (ServletException ex) {
Logger.getLogger(FileUploadController.class.getName())
.log(Level.SEVERE, null, ex);
}
}
private void doDefaultAction(HttpServletRequest request,
HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
if (!StringUtils.isEmpty(username)) {
List<FileInfo> files = new ArrayList<FileInfo>(10);
fuService.getFile(username, files, username);
if (!files.isEmpty()) {
session.setAttribute("files", files);
}
}
String path = "./jsps/GiangVien/FileManager.jsp";
response.sendRedirect(path);
}
private void doValidateFileName(HttpServletRequest request,
HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
// Validate file name
// Lecturer upload file score must in specified format
// The name of file must be class code
String fileName = (String) request.getParameter("txtPath");
String lecturerId = (String) request.getSession().getAttribute("username");
// C:/CAR.001.xls ==> CAR.001
fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length() - 4);
List<TrainClass> trainClass = trainClassService.getCurrentTrainClass(lecturerId);
if ((trainClass == null) || trainClass.isEmpty()) {
out.append("error - GV hiện không dạy lớp nào.");
return;
}
for (TrainClass tc : trainClass) {
if (fileName.equalsIgnoreCase(tc.getId().getClassCode())) {
out.append("Oh, Success.");
return;
}
}
out.append("error - Tên file không đúng định dạng.");
}
//#############################################
public enum FileUploadSupport {
DEFAULT("default"),
VALIDATE_FILENAME("validate-filename"),
UPLOAD_FILE("upload");
private String description;
FileUploadSupport(String description) {
this.description = description;
}
public String getValue() {
return description;
}
}
}
|
SQL
|
UTF-8
| 5,428
| 2.90625
| 3
|
[] |
no_license
|
CREATE TABLE profesion (
codigo tinyint(3) unsigned primary key,
descripcion varchar(40) not null,
status tinyint(1) unsigned not null default 1,
cod_usr_reg int unsigned not null,
fec_reg timestamp not null default current_timestamp,
cod_usr_mod int unsigned not null,
fec_mod timestamp not null DEFAULT 0,
foreign key (cod_usr_reg)
references usuario(codigo)
on update cascade
on delete restrict,
foreign key (cod_usr_mod)
references usuario(codigo)
on update cascade
on delete restrict
)
CHARACTER SET utf8
COLLATE utf8_general_ci;
INSERT INTO profesion
(codigo, descripcion, cod_usr_reg, cod_usr_mod, fec_mod)
values
(1, 'ABOGADO', 1, 1, current_timestamp),
(2, 'ACTOR, ACTRIZ', 1, 1, current_timestamp),
(3, 'ADMINISTRADOR', 1, 1, current_timestamp),
(4, 'AGENTE VIAJERO', 1, 1, current_timestamp),
(5, 'AGRICULTOR', 1, 1, current_timestamp),
(6, 'ALBAÑIL', 1, 1, current_timestamp),
(7, 'AMA DE CASA', 1, 1, current_timestamp),
(8, 'ANALISTA', 1, 1, current_timestamp),
(9, 'ARQUITECTO', 1, 1, current_timestamp),
(10, 'ATLETA', 1, 1, current_timestamp),
(11, 'AUDITOR', 1, 1, current_timestamp),
(12, 'AUXILIAR DE LABORATORIO', 1, 1, current_timestamp),
(13, 'AUXILIAR DE ENFERMERIA', 1, 1, current_timestamp),
(14, 'AUXILIAR DE FARMACIA', 1, 1, current_timestamp),
(15, 'AZAFATA', 1, 1, current_timestamp),
(16, 'BAILARIN', 1, 1, current_timestamp),
(17, 'BARBERO', 1, 1, current_timestamp),
(18, 'BARMAN', 1, 1, current_timestamp),
(19, 'BOMBERO', 1, 1, current_timestamp),
(20, 'BOTANICO', 1, 1, current_timestamp),
(21, 'CAJERO', 1, 1, current_timestamp),
(22, 'CAMARERO, CAMARERA', 1, 1, current_timestamp),
(23, 'CAMAROGRAFO', 1, 1, current_timestamp),
(24, 'CAMILLERO', 1, 1, current_timestamp),
(25, 'CANTANTE', 1, 1, current_timestamp),
(26, 'CARNICERO', 1, 1, current_timestamp),
(27, 'CARPINTERO', 1, 1, current_timestamp),
(28, 'CARTERO', 1, 1, current_timestamp),
(29, 'CERRAJERO', 1, 1, current_timestamp),
(30, 'CIENTIFICO', 1, 1, current_timestamp),
(31, 'COMERCIANTE', 1, 1, current_timestamp),
(32, 'COMPOSITOR', 1, 1, current_timestamp),
(33, 'COCINERO', 1, 1, current_timestamp),
(34, 'CHOFER', 1, 1, current_timestamp),
(35, 'CONTADOR', 1, 1, current_timestamp),
(36, 'CONTRATISTA DE OBRA', 1, 1, current_timestamp),
(37, 'COSTURERA', 1, 1, current_timestamp),
(38, 'DECORADOR', 1, 1, current_timestamp),
(39, 'DENTISTA', 1, 1, current_timestamp),
(40, 'DIRECTOR DE ESCUELA', 1, 1, current_timestamp),
(41, 'DIRECTOR DE ORQUESTA', 1, 1, current_timestamp),
(42, 'DISEÑADOR GRAFICO', 1, 1, current_timestamp),
(43, 'DOCENTE', 1, 1, current_timestamp),
(44, 'ECONOMISTA', 1, 1, current_timestamp),
(45, 'EDITOR', 1, 1, current_timestamp),
(46, 'ELECTRICISTA', 1, 1, current_timestamp),
(47, 'ENFERMERO/A', 1, 1, current_timestamp),
(48, 'ESCOLTA', 1, 1, current_timestamp),
(49, 'ESCRITOR', 1, 1, current_timestamp),
(50, 'ESCULTOR', 1, 1, current_timestamp),
(51, 'FARMACEUTICO', 1, 1, current_timestamp),
(52, 'FISICO', 1, 1, current_timestamp),
(53, 'FLORISTA', 1, 1, current_timestamp),
(54, 'FOTOGRAFO', 1, 1, current_timestamp),
(55, 'FRUTERO', 1, 1, current_timestamp),
(56, 'GEOLOGO', 1, 1, current_timestamp),
(57, 'GUARDA-PARQUES', 1, 1, current_timestamp),
(58, 'HERRERO', 1, 1, current_timestamp),
(59, 'INGENIERO', 1, 1, current_timestamp),
(60, 'JARDINERO', 1, 1, current_timestamp),
(61, 'JOYERO', 1, 1, current_timestamp),
(62, 'JUEZ', 1, 1, current_timestamp),
(63, 'LATONERO', 1, 1, current_timestamp),
(64, 'LICENCIADO', 1, 1, current_timestamp),
(65, 'LOCUTOR', 1, 1, current_timestamp),
(66, 'MAQUINISTA', 1, 1, current_timestamp),
(67, 'MATEMATICO', 1, 1, current_timestamp),
(68, 'MECANICO', 1, 1, current_timestamp),
(69, 'MEDICO', 1, 1, current_timestamp),
(70, 'MEDICO VETERINARIO', 1, 1, current_timestamp),
(71, 'MILITAR', 1, 1, current_timestamp),
(72, 'MODELO', 1, 1, current_timestamp),
(73, 'MODISTA', 1, 1, current_timestamp),
(74, 'MUSICO', 1, 1, current_timestamp),
(75, 'NIÑERA', 1, 1, current_timestamp),
(76, 'NUTRICIONISTA', 1, 1, current_timestamp),
(77, 'OBRERO', 1, 1, current_timestamp),
(78, 'OFICIAL DE POLICIA', 1, 1, current_timestamp),
(79, 'OFICIAL DE SEGURIDAD', 1, 1, current_timestamp),
(80, 'PANADERO', 1, 1, current_timestamp),
(81, 'PASTELERO', 1, 1, current_timestamp),
(82, 'PEDIATRA', 1, 1, current_timestamp),
(83, 'PELUQUERO', 1, 1, current_timestamp),
(84, 'PERIODISTA', 1, 1, current_timestamp),
(85, 'PERITO MERCANTIL', 1, 1, current_timestamp),
(86, 'PESCADOR', 1, 1, current_timestamp),
(87, 'PILOTO', 1, 1, current_timestamp),
(88, 'PLOMERO', 1, 1, current_timestamp),
(89, 'PINTOR', 1, 1, current_timestamp),
(90, 'POLITICO', 1, 1, current_timestamp),
(91, 'PROFESOR UNIVERSITARIO', 1, 1, current_timestamp),
(92, 'PROGRAMADOR', 1, 1, current_timestamp),
(93, 'PSICOLOGO', 1, 1, current_timestamp),
(94, 'PSICOTERAPEUTA', 1, 1, current_timestamp),
(95, 'PSIQUIATRA', 1, 1, current_timestamp),
(96, 'PUBLICISTA', 1, 1, current_timestamp),
(97, 'QUIMICO', 1, 1, current_timestamp),
(98, 'RADIOLOGO', 1, 1, current_timestamp),
(99, 'RECEPCIONISTA', 1, 1, current_timestamp),
(100, 'SACERDOTE, MONJA', 1, 1, current_timestamp),
(101, 'SASTRE', 1, 1, current_timestamp),
(102, 'SECRETARIO/A', 1, 1, current_timestamp),
(103, 'SIN PROFESION', 1, 1, current_timestamp),
(104, 'SUPERVISOR/A', 1, 1, current_timestamp),
(105, 'TAXISTA', 1, 1, current_timestamp),
(106, 'TEOLOGO', 1, 1, current_timestamp),
(107, 'TRADUCTOR DE IDIOMA', 1, 1, current_timestamp),
(108, 'ZAPATERO', 1, 1, current_timestamp),
(255,'OTRO', 1, 1, current_timestamp);
|
Java
|
UTF-8
| 2,753
| 2.390625
| 2
|
[] |
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 pClases;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author luis
*/
public class Correo {
private String remitente;
private String contra;
private String destinatario;
private String asunto;
private String mensaje;
public Correo(String destinatario, String asunto, String mensaje) {
this.remitente = "store.kleidung@gmail.com";
this.contra = "holahola123";
this.destinatario = destinatario;
this.asunto = asunto;
this.mensaje = mensaje;
}
public String getRemitente() {
return remitente;
}
public void setRemitente(String remitente) {
this.remitente = remitente;
}
public String getContra() {
return contra;
}
public void setContra(String contra) {
this.contra = contra;
}
public String getDestinatario() {
return destinatario;
}
public void setDestinatario(String destinatario) {
this.destinatario = destinatario;
}
public String getMensaje() {
return mensaje;
}
public void setMensaje(String mensaje) {
this.mensaje = mensaje;
}
public String getAsunto() {
return asunto;
}
public void setAsunto(String asunto) {
this.asunto = asunto;
}
public void Enviar() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session sesion = Session.getInstance(props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getRemitente(), getContra());
}
});
try {
Message message = new MimeMessage(sesion);
message.setFrom(new InternetAddress(getRemitente()));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(getDestinatario()));
message.setSubject(getAsunto());
message.setText(getMensaje());
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
|
JavaScript
|
UTF-8
| 45,393
| 2.5625
| 3
|
[] |
no_license
|
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Meal = require('../../models/Meal');
const Child = require('../../models/Child');
const passport = require('passport');
router.get("/seed", async (req, res)=>{
const password_digest = "$2a$10$jjDnk0HSqgl2fEUsYdnnbOv7EqWVH.UJQoOYdWU9xmN.Cu.JGa/1y";
const users = await Promise.all([
{
handle: "userA",
email: "userA@google.com",
password: password_digest,
firstName: "usera",
lastName: "a"
},
{
handle: "demo-user",
email: "demoUser@demo.com",
password: password_digest,
firstName: "demo",
lastName: "user"
}
].map(u => new User(u).save()));
const childs = await Promise.all([
{
user: users[0].id,
name: "Francis",
age: 3,
category: ["Chinese", "American"],
ingredient: ["Rice", "Bacon", "Salami"]
}
].map(c => new Child(c).save()));
const meals = await Promise.all([
{
title: "Sesame Chicken",
category: "Chinese",
ingredients: [
"5 ounce skinless, boneless chicken breast halves",
"1 clove garlic"
],
photoUrl: "https://www.ndtv.com/cooks/images/sesame.chik.20.000%281%29.jpg",
cookingInstruction: [
"Combine the 2 tablespoons soy sauce, the dry sherry, dash of sesame oil, flour, 2 tablespoons cornstarch, 2 tablespoons water, baking powder, baking soda, and canola oil in a large bowl.Mix well; stir in the chicken.Cover and refrigerate for 20 minutes.",
"Heat oil in a deep- fryer or large saucepan to 375 degrees F(190 degrees C).",
"Combine the 1/2 cup water, chicken broth, vinegar, 1/4 cup cornstarch, sugar, 2 tablespoons soy sauce, 2 tablespoons sesame oil, red chili paste, and garlic in a small saucepan.Bring to a boil, stirring constantly.Turn heat to low and keep warm, stirring occasionally.",
"Fry the marinated chicken in batches until cooked through and golden brown, 3 to 5 minutes.Drain on paper towels.",
"Transfer the chicken to a large platter, top with sauce, and sprinkle with sesame seeds."
],
nutritionFacts: "Per Serving: 745 calories; 37.1 g total fat; 88 mg cholesterol; 1405 mg sodium. 68.6 g carbohydrates; 34.3 g protein."
},
{
title: "Bibimbap",
category: "Korean",
ingredients: [
"1 English cucumber",
"1 bunch fresh spinach",
"2 carrots",
"1 clove garlic",
"1 pinch red pepper",
"1 pound thinly-sliced beef top round steak",
"4 large eggs"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/3961066.jpg",
cookingInstruction: [
"Stir cucumber pieces with 1/4 cup gochujang paste in a bowl; set aside.",
"Bring about 2 cups of water to a boil in a large nonstick skillet and stir in spinach; cook until spinach is bright green and wilted, 2 to 3 minutes. Drain spinach and squeeze out as much moisture as possible; set spinach aside in a bowl and stir soy sauce into spinach.",
"Heat 1 teaspoon olive oil in large nonstick skillet and cook and stir carrots until softened, about 3 minutes; stir in garlic and cook just until fragrant, about 1 more minute. Stir in cucumber pieces with gochujang paste; sprinkle with red pepper flakes, and set the mixture aside in a bowl.",
"Brown beef in a clean nonstick skillet over medium heat, about 5 minutes per side, and set aside. In a separate nonstick skillet, heat 1 more teaspoon olive oil over medium-low heat and fry the eggs just on one side until yolks are runny but whites are firm, 2 to 4 minutes each.",
"To assemble the dish, divide cooked rice into 4 large serving bowls; top with spinach mixture, a few pieces of beef, and cucumber mixture. Place 1 egg atop each serving. Drizzle each bowl with 1 teaspoon of sesame oil, a sprinkle of sesame seeds, and a small amount of gochujang paste if desired."
],
nutritionFacts: "Per Serving: 569 calories; 19.3 g fat; 63 g carbohydrates; 34.9 g protein; 243 mg cholesterol; 574 mg sodium."
},
{
title: "Chile Garlic BBQ Salmon",
category: "Chinese",
ingredients: [
"3 pounds whole salmon",
"1 clove garlic",
"3 green onions",
"2 limes"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/5536279.jpg",
cookingInstruction: [
"Prepare outdoor grill for high heat.",
"Trim the tail and fins off of the salmon. Make several shallow cuts across the salmon's skin. Place salmon on 3 large, slightly overlapping sheets of aluminum foil.",
"In a bowl, stir together soy sauce, chile sauce, ginger, and garlic. Mix in lime juice, lime zest, and brown sugar. Spoon sauce over the salmon.",
"Fold the foil over the salmon, and crimp the edges to seal.",
"If using hot coals, move them to one side of the grill. Place the fish on the side of the grill that does not have coals directly underneath it, and close the lid. If using a gas grill, place the fish on one side, and turn off the flames directly underneath it; close the lid. Cook for 25 to 30 minutes. Remove to a serving platter, and pour any juices that may have collected in the foil over the top of the fish. Sprinkle with green onions."
],
nutritionFacts: "Per Serving: 438 calories; 24.7 g fat; 5.3 g carbohydrates; 46.2 g protein; 134 mg cholesterol; 738 mg sodium."
},
{
title: "California Roll Sushi",
category: "Japanese",
ingredients: [
"1/2 cup imitation crabmeat",
"8 sheets nori (dry seaweed)",
"1 cucumber",
"2 avocados"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/250x250/907484.jpg",
cookingInstruction: [
"Wash the rice in several changes of water until the rinse water is no longer cloudy, drain well, and place in a covered pan or rice cooker with 1 cup water. Bring to a boil, reduce heat to a simmer, and cover the pan. Allow the rice to simmer until the top looks dry, about 15 minutes. Turn off the heat, and let stand for 10 minutes to absorb the rest of the water.",
"Mix the rice vinegar and sugar in a small bowl until the sugar has dissolved, and stir the mixture into the cooked rice until well combined. Allow the rice to cool, and set aside.",
"Mix the imitation crabmeat with mayonnaise in a bowl, and set aside. To roll the sushi, cover a bamboo rolling mat with plastic wrap. Lay a sheet of nori, shiny side down, on the plastic wrap. With wet fingers, firmly pat a thin, even layer of prepared rice over the nori, leaving 1/4 inch uncovered at the bottom edge of the sheet. Sprinkle the rice with about 1/2 teaspoon of sesame seeds, and gently press them into the rice. Carefully flip the nori sheet over so the seaweed side is up.",
"Place 2 or 3 long cucumber spears, 2 or 3 slices of avocado, and about 1 tablespoon of imitation crab mixture in a line across the nori sheet, about 1/4 from the uncovered edge. Pick up the edge of the bamboo rolling sheet, fold the bottom edge of the sheet up, enclosing the filling, and tightly roll the sushi into a cylinder about 1 1/2 inch in diameter. Once the sushi is rolled, wrap it in the mat and gently squeeze to compact it tightly.",
"Cut each roll into 1 inch pieces with a very sharp knife dipped in water."
],
nutritionFacts: "Per Serving: 232 calories; 14.4 g fat; 23.7 g carbohydrates; 3.9 g protein; 5 mg cholesterol; 135 mg sodium. "
},
{
title: "General Tsao's Chicken",
category: "Chinese",
ingredients: [
"1 egg",
"1 ½ pounds boneless, skinless chicken thighs",
"1 pinch white pepper",
"1 green onion",
"1 clove garlic",
"6 dried whole red chilies",
"1 ginger"
],
photoUrl: "https://spicysouthernkitchen.com/wp-content/uploads/general-tsau-chicken-15.jpg",
cookingInstruction: [
"Heat 4 cups vegetable oil in a deep-fryer or large saucepan to 375 degrees F (190 degrees C).",
"Beat the egg in a mixing bowl. Add the chicken cubes; sprinkle with salt, 1 teaspoon sugar, and white pepper; mix well. Mix in 1 cup of cornstarch a little bit at a time until the chicken cubes are well coated.",
"In batches, carefully drop the chicken cubes into the hot oil one by one, cooking until they turns golden brown and begin to float, about 3 minutes. Remove the chicken and allow to cool as you fry the next batch. Once all of the chicken has been fried, refry the chicken, starting with the batch that was cooked first. Cook until the chicken turns deep golden brown, about 2 minutes more. Drain on a paper towel-lined plate.",
"Heat 2 tablespoons vegetable oil in a wok or large skillet over high heat. Stir in the green onion, garlic, whole chiles, and orange zest. Cook and stir a minute or two until the garlic has turned golden and the chiles brighten. Add 1/2 cup sugar, the ginger, chicken broth, vinegar, soy sauce, sesame oil, and peanut oil; bring to a boil and cook for 3 minutes.",
"Dissolve 2 teaspoons of cornstarch into the water, and stir into the boiling sauce. Return to a boil and cook until the sauce thickens and is no longer cloudy from the cornstarch, about 1 minute. Stir the chicken into the boiling sauce. Reduce heat to low and cook for a few minutes until the chicken absorbs some of the sauce."
],
nutritionFacts: "Per Serving: 634 calories; 36.5 g total fat; 101 mg cholesterol; 1192 mg sodium. 54.9 g carbohydrates; 24.3 g protein."
},
{
title: "Fresh Spring Rolls",
category: "Vietnamese",
ingredients: [
"8 rice wrappers (8.5 inch diameter)",
"2 ounces rice vermicelli",
"8 large shrimps",
"1 bunch thai basil",
"2 leaves lettuce",
"1 clove garlic"
],
photoUrl: "https://www.recipetineats.com/wp-content/uploads/2014/07/Vietnamese-Rice-Paper-Rolls-7.jpg",
cookingInstruction: [
"Bring a medium saucepan of water to boil. Boil rice vermicelli 3 to 5 minutes, or until al dente, and drain.",
"Fill a large bowl with warm water. Dip one wrapper into the hot water for 1 second to soften. Lay wrapper flat. In a row across the center, place 2 shrimp halves, a handful of vermicelli, basil, mint, cilantro and lettuce, leaving about 2 inches uncovered on each side. Fold uncovered sides inward, then tightly roll the wrapper, beginning at the end with the lettuce. Repeat with remaining ingredients.",
"In a small bowl, mix the fish sauce, water, lime juice, garlic, sugar and chili sauce.",
"In another small bowl, mix the hoisin sauce and peanuts.",
"Serve rolled spring rolls with the fish sauce and hoisin sauce mixtures."
],
nutritionFacts: "Per Serving: 82 calories; 0.7 g fat; 15.8 g carbohydrates; 3.3 g protein; 11 mg cholesterol; 305 mg sodium."
},
{
title: "Kim's Lasagna",
category: "Italian",
ingredients: [
"1 pound bulk Italian sausage",
"1 pound ground beef",
"1 onion",
"4 cloves garlic",
"1 bunch parsley",
"12 lasagna noodles",
"1 egg",
"1 pinch ground nutmeg"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/1113127.jpg",
cookingInstruction: [
"Brown sausage and ground beef with onion and garlic in a large Dutch oven or heavy pot over medium heat, cooking and stirring until meat is cooked through, 10 to 15 minutes. Drain and discard grease. Stir tomato sauce, crushed tomatoes, Italian-style crushed tomatoes, tomato paste, basil, 2 tablespoons parsley, brown sugar, salt, Italian seasoning, black pepper, fennel seeds, and 1/2 cup Parmesan cheese into meat mixture. Bring to a boil, reduce heat to low, and simmer sauce for at least 1 hour (up to 6 for best flavor). Stir occasionally.",
"Place lasagna noodles into a deep bowl and cover with very hot tap water; let soak for 30 minutes.",
"Beat egg in a bowl and stir ricotta cheese, 2 tablespoons parsley, 1/2 teaspoon salt, and nutmeg into egg until thoroughly combined.",
"Preheat oven to 375 degrees F (190 degrees C).",
"Cover bottom of a 9x13-inch baking dish with 1 cup sauce. Layer 4 soaked lasagna noodles, 1/3 of the ricotta cheese mixture, 1/3 of the shredded mozzarella cheese, and 1/4 cup Parmesan cheese in the dish. Repeat layers twice more, ending with mozzarella and Parmesan cheeses. Cover dish with aluminum foil.",
"Bake until lasagna noodles are tender and casserole is bubbling, about 50 minutes. Remove foil and bake until cheese topping is lightly browned, 15 to 20 more minutes. Let stand 15 minutes before serving."
],
nutritionFacts: "Per Serving: 594 calories; 29.1 g fat; 43.4 g carbohydrates; 41.2 g protein; 115 mg cholesterol; 1898 mg sodium."
},
{
title: "Melissa's Chicken Cacciatore",
category: "Italian",
ingredients: [
"1 (12 ounce) jar marinated artichoke hearts",
"2 large skinless, boneless chicken breast halves",
"1 large onion",
"3 cloves garlic",
"8 ounces fresh mushrooms",
"1 (14.5 ounce) can diced tomatoes in juice",
"⅓ cup black olives",
"8 ounces shredded mozzarella cheese"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/889256.jpg",
cookingInstruction: [
"Preheat oven to 350 degrees F (175 degrees C).",
"Place half the artichoke marinade into a large skillet over medium-high heat, and brown the chicken pieces until the liquid has almost evaporated, 8 to 10 minutes. Remove the chicken pieces with a slotted spoon, and place into a 9x13-inch baking dish.",
"Pour the remaining marinade into the same skillet, and cook and stir the onions, garlic, mushrooms, oregano, basil, salt, rosemary, and black pepper until the onions are translucent, 5 to 8 minutes. Mix in diced tomatoes with their juice, tomato sauce, black olives, and chopped artichoke hearts. Stir the sauce well, and pour over the chicken in the baking dish. Cover the dish with foil.",
"Bake the chicken until the sauce is bubbling, about 45 minutes. Uncover, and drizzle the Madeira wine over the dish; top with mozzarella cheese. Return to oven, uncovered, and bake until the cheese is melted, about 10 more minutes."
],
nutritionFacts: "Per Serving: 320 calories; 12 g total fat; 63 mg cholesterol; 1428 mg sodium. 21.2 g carbohydrates; 29.2 g protein."
},
{
title: "French Toast",
category: "American",
ingredients: [
"6 thick slices bread",
"2 eggs"
],
photoUrl: "https://www.momables.com/wp-content/uploads/2013/12/Egg-free-french-toast_post.jpg",
cookingInstruction: [
"Beat together egg, milk, salt, desired spices and vanilla.",
"Heat a lightly oiled griddle or skillet over medium-high heat.",
"Dunk each slice of bread in egg mixture, soaking both sides. Place in pan, and cook on both sides until golden. Serve hot."
],
nutritionFacts: "Per Serving: 240 calories; 6.4 g fat; 33.6 g carbohydrates; 10.6 g protein; 128 mg cholesterol; 478 mg sodium."
},
{
title: "Easy Chicken Pasta Alfredo",
category: "American",
ingredients: [
"4 skinless, boneless chicken breast halves",
"½ pound fresh mushrooms",
"⅓ cup grated Parmesan cheese"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/1105549.jpg",
cookingInstruction: [
"Bring a large pot of lightly salted water to a boil. Add tortellini. Cook, stirring occasionally, until tortellini float to the top and the filling is hot, about 5 minutes. Drain.",
"Heat vegetable oil in a large skillet over medium heat; cook and stir chicken breast in hot oil until no longer pink in the center, about 10 minutes. Remove from heat.",
"Melt butter in another skillet over medium heat; cook and stir mushrooms and garlic powder until mushrooms begin to soften, about 3 minutes. Stir heavy cream into mushrooms and bring to a boil. Reduce heat to medium-low and simmer until slightly thickened, about 3 minutes. Add Parmesan cheese, parsley, and salt. Continue to cook until cheese is melted, about 1 minute.",
"Stir tortellini and chicken into mushroom-cream sauce. Simmer until heated through, about 2 minutes."
],
nutritionFacts: "Per Serving: 686 calories; 46.9 g total fat; 201 mg cholesterol; 843 mg sodium. 38.4 g carbohydrates; 30.2 g protein."
},
{
title: "Beef and Sweet Potato Stew",
category: "American",
ingredients: [
"1 1/2 pounds top round beef",
"2 large sweet potatoes",
"2 carrots",
"2 stalks celery",
"1 (8 ounce) package pearl onions",
"1 (4.5 ounce) can mushrooms",
"1 (28 ounce) can tomato puree",
"1 clove garlic"
],
photoUrl: "https://www.diabetesfoodhub.org/system/thumbs/system/images/recipes/Recid_78_beef_sweet_potato_stew_iStock585609020_022118_2959761669.jpg",
cookingInstruction: [
"Preheat the oven to 300 degrees F (150 degrees C).",
"Place chunks of meat into a large baking pan. Add sweet potatoes, carrots, celery, onions, and mushrooms.",
"Combine tomato puree, water, gravy mix, garlic, thyme, garlic salt, and black pepper in a bowl. Pour over meat and vegetables in the baking pan. Cover with aluminum foil.",
"Bake in the preheated oven for about 3 hours."
],
nutritionFacts: "Per Serving: 384 calories; 7.5 g fat; 55.3 g carbohydrates; 25.9 g protein; 50 mg cholesterol; 1255 mg sodium."
},
{
title: "Orange and Milk-Braised Pork Carnitas",
category: "American",
ingredients: [
"3 1/2 pounds boneless pork shoulder",
"2 bay leaves",
"1 orange"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/250x250/2280918.jpg",
cookingInstruction: [
"Season pork with pepper and salt.",
"Heat oil in large pot over high heat. Working in batches, cook pork in the hot oil until browned on all sides, about 5 minutes. Return all cooked pork and accumulated juice to pot.",
"Season pork with bay leaves, cumin, dried oregano, and cayenne pepper. Stir in fresh orange juice, orange zest, and milk. Bring mixture to a boil over high heat; reduce heat to low. Cover and simmer, stirring occasionally, until meat is fork tender but not falling apart, about 2 hours.",
"Preheat oven to 450 degrees F (230 degrees C).",
"Remove pork from liquid. Skim some fat from the pot to grease a baking dish. Transfer the pieces of pork to the baking dish. Drizzle about 2 more tablespoons of the floating fat over the meat. Season with more salt, if needed.",
"Bake in preheated oven until pork is browned, about 15 minutes. Stir pork.",
"Turn on oven's broiler. Cook pork under broiler until crisp, 2 to 3 minutes."
],
nutritionFacts: "Per Serving: 325 calories; 24.1 g fat; 3.7 g carbohydrates; 22.4 g protein; 84 mg cholesterol; 805 mg sodium."
},
{
title: "Chef John's Shrimp Etouffee",
category: "American",
ingredients: [
"2 pounds shrimp",
"1 green bell pepper",
"1 pound celery",
"2 tomatoes",
"3 green onions"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/560x315/5118524.jpg",
cookingInstruction: [
"Whisk paprika, thyme, oregano, cayenne pepper, garlic powder, onion powder, white pepper, and black pepper together in a small bowl.",
"Drain shrimp in a colander for at least 15 minutes. Transfer to a bowl lined with paper towels and dry shrimp for about 3 minutes. Remove paper towels from bowl and season shrimp with 1 teaspoon salt and 1 teaspoon spice blend. Toss to coat shrimp with spice blend.",
"Heat vegetable oil a large heavy skillet over high heat until oil is smoking hot. Cook shrimp in the hot oil without stirring for 1 minute; stir, and cook 1 minute more.",
"Transfer shrimp to a large bowl. Let stand until juice forms in bowl. Strain shrimp juices into chicken stock to total 2 cups, adding more chicken stock if necessary.",
"Melt butter in large skillet over medium heat until butter begins to turn tan at the edges. Saute onion, celery, and green pepper in hot butter until softened, about 5 minutes. Pour in remaining spice blend.",
"Sprinkle flour into vegetable mixture and saute until combined, 3 to 4 minutes. Stir in tomatoes; cook until tomato juices begin to brown on bottom of pan, about 3 minutes. Whisk stock into vegetable mixture, stirring until smooth. Bring to a simmer and cook until slightly thickened and reduced to a gravy consistency, 3 to 5 minutes. Stir in Worcestershire sauce and hot sauce. Season with salt to taste.",
"Stir shrimp into etouffee sauce; let simmer until shrimp are cooked all the way through and no longer translucent, about 1 minute.",
"Garnish with green onions and a dusting of cayenne pepper. Pour over rice in large, shallow bowls."
],
nutritionFacts: "Per Serving: 424 calories; 14.7 g fat; 30.2 g carbohydrates; 40.8 g protein; 369 mg cholesterol; 1114 mg sodium."
},
{
title: "Thai Curry Tofu",
category: "Thai",
ingredients: [
"1 (12 ounce) package extra-firm tofu",
"1 small onion",
"3 cloves garlic",
"¼ cup fresh cilantro"
],
photoUrl: "https://res.cloudinary.com/hksqkdlah/image/upload/ar_1:1,c_fill,dpr_2.0,f_auto,fl_lossy.progressive.strip_profile,g_faces:auto,q_auto:low,w_344/8132_sfs-skillet-thai-curry-with-sweet-potatoes-and-tofu-article",
cookingInstruction: [
"Heat oil in a large skillet over medium-high heat. Add tofu cubes, season with seasoned salt and fry until golden on all sides, stirring occasionally, about 15 minutes. Remove to paper towels, and set aside.",
"Melt butter or margarine in the same skillet over medium heat. Add the onion and garlic; cook and stir until tender. Stir in coconut milk, curry powder, salt, pepper and cilantro. Return the tofu to the skillet. Simmer over low heat for 15 minutes, stirring occasionally."
],
nutritionFacts: "Per Serving: 424 calories; 14.7 g fat; 30.2 g carbohydrates; 40.8 g protein; 369 mg cholesterol; 1114 mg sodium."
},
{
title: "Lori's Famous Crab Cakes",
category: "American",
ingredients: [
"1 green bell pepper",
"2 green onions",
"4 sprigs fresh parsley",
"1 egg",
"3 (6 ounce) cans crabmeat"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/560x315/1649402.jpg",
cookingInstruction: [
"In a bowl, toss together the 1/3 cup bread crumbs, green bell pepper, red bell pepper, green onions, and parsley. Mix in the egg white, mayonnaise, lemon juice, Worcestershire sauce, and Dijon mustard. Season with Old Bay seasoning, dry mustard, and onion powder. Fold crabmeat into the mixture. Form into 6 large cakes. Coat in the remaining 1/2 cup bread crumbs.",
"Heat the oil in a large, heavy skillet. Fry the cakes 5 minutes on each side, or until evenly brown. Drain on paper towels."
],
nutritionFacts: "Per Serving: 225 calories; 9.4 g fat; 13.8 g carbohydrates; 20.7 g protein; 77 mg cholesterol; 508 mg sodium."
},
{
title: "Broccoli in Roast Chicken Drippings",
category: "American",
ingredients: [
"¼ cup roast chicken drippings",
"1 head broccoli",
"2 cloves garlic"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/1019848.jpg",
cookingInstruction: [
"After roasting a chicken, remove it from the roasting pan and place on a serving tray to rest. Leave the oven on. Pour off excess drippings from the roasting pan, leaving just enough to coat the broccoli. Toss broccoli and garlic in the drippings until coated and place in the still hot oven. Roast for 5 to 8 minutes, until tender."
],
nutritionFacts: "Per Serving: 225 calories; 9.4 g fat; 13.8 g carbohydrates; 20.7 g protein; 77 mg cholesterol; 508 mg sodium."
},
{
title: "Pork Dumplings",
category: "Chinese",
ingredients: [
"100 (3.5 inch square) wonton wrappers",
"1 3/4 pounds ground pork",
"4 cloves garlic",
"1 egg",
"1 Chinese cabbage"
],
photoUrl: "https://www.garlicandzest.com/wp-content/uploads/2016/02/pork-dumplings-6.jpg",
cookingInstruction: [
"In a large bowl, combine the pork, ginger, garlic, green onion, soy sauce, sesame oil, egg and cabbage. Stir until well mixed.",
"Place 1 heaping teaspoon of pork filling onto each wonton skin. Moisten edges with water and fold edges over to form a triangle shape. Roll edges slightly to seal in filling. Set dumplings aside on a lightly floured surface until ready to cook.",
"To Cook: Steam dumplings in a covered bamboo or metal steamer for about 15 to 20 minutes. Serve immediately."
],
nutritionFacts: "Per Serving: 752 calories; 28.8 g fat; 81.1 g carbohydrates; 39.2 g protein; 129 mg cholesterol; 1449 mg sodium."
},
{
title: "Yakisoba Chicken",
category: "Japanese",
ingredients: [
"2 cloves garlic",
"4 skinless, boneless chicken breast halves",
"1 onion",
"½ medium head cabbage",
"2 carrots",
"8 ounces soba noodles"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/2220105.jpg",
cookingInstruction: [
"In a large skillet combine sesame oil, canola oil and chili paste; stir-fry 30 seconds. Add garlic and stir fry an additional 30 seconds. Add chicken and 1/4 cup of the soy sauce and stir fry until chicken is no longer pink, about 5 minutes. Remove mixture from pan, set aside, and keep warm.",
"In the emptied pan combine the onion, cabbage, and carrots. Stir-fry until cabbage begins to wilt, 2 to 3 minutes. Stir in the remaining soy sauce, cooked noodles, and the chicken mixture to pan and mix to blend. Serve and enjoy!"
],
nutritionFacts: "Per Serving: 752 calories; 28.8 g fat; 81.1 g carbohydrates; 39.2 g protein; 129 mg cholesterol; 1449 mg sodium."
},
{
title: "Pork Fried Rice",
category: "Chinese, American",
ingredients: [
"1 (6 ounce) boneless pork loin chop",
"1 carrot",
"1 broccoli",
"1 green onion",
"1 egg",
"rice",
"1 bag peas"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/1353688.jpg",
cookingInstruction: [
"Melt butter in a large non-stick skillet over medium heat. Cook and stir pork, carrot, broccoli, peas, and green onion in melted butter until pork is cooked through, 7 to 10 minutes. Remove pork mixture to a bowl and return skillet to medium heat.",
"Scramble egg in the skillet until completely set. Return the pork mixture to the skillet. Stir rice, peas, soy sauce, garlic powder, and ground ginger into the pork mixture; cook and stir until heated through, 7 to 10 minutes."
],
nutritionFacts: "Per Serving: 557 calories; 13.3 g fat; 80.7 g carbohydrates; 26.1 g protein; 137 mg cholesterol; 815 mg sodium."
},
{
title: "Shrimp Fried Rice",
category: "Chinese, American",
ingredients: [
"1 ounce bean sprouts",
"1 onion",
"2 ounces medium shrimp",
"1 green onion",
"2 eggs",
"rice"
],
photoUrl: "https://hips.hearstapps.com/del.h-cdn.co/assets/17/24/1497458825-delish-shrimp-fried-rice-1-1024.jpg",
cookingInstruction: [
"In a saucepan bring water to a boil. Add rice and stir. Reduce heat, cover and simmer for 20 minutes. Set aside and allow rice to cool.",
"Heat a large skillet or wok for 2 minutes. When the skillet or wok is hot, pour in vegetable oil, bean sprouts and onions. Mix well and cook for 3 minutes.",
"Mix in cooled rice and shrimp and cook for another 3 minutes. Stirring constantly.",
"Mix in green onions, eggs, salt, pepper, soy sauce and sesame oil. Cook for another 4 minutes, stirring continuously, until eggs are cooked and everything is blended evenly."
],
nutritionFacts: "Per Serving: 483 calories; 17.5 g fat; 60.3 g carbohydrates; 20 g protein; 187 mg cholesterol; 1638 mg sodium."
},
{
title: "Avocado Toast",
category: "American",
ingredients: [
"2 slices bread",
"2 ounces Cheddar cheese",
"1 avocado"
],
photoUrl: "https://s23209.pcdn.co/wp-content/uploads/2016/04/5MinuteAvocadoToastIMG_8273edit-360x360.jpg",
cookingInstruction: [
"Preheat oven to 300 degrees F (150 degrees C).",
"Heat a large skillet or wok for 2 minutes. When the skillet or wok is hot, pour in vegetable oil, bean sprouts and onions. Mix well and cook for 3 minutes.",
"Bake in the preheated oven until cheese melts, about 5 minutes. Cover each bread slice with sliced avocado."
],
nutritionFacts: "Per Serving: 483 calories; 17.5 g fat; 60.3 g carbohydrates; 20 g protein; 187 mg cholesterol; 1638 mg sodium."
},
{
title: "Turkey Sandwiches",
category: "American",
ingredients: [
"1 loaf French bread",
"8 ounces sliced deli turkey meat",
"8 slices provolone cheese",
"8 slices precooked bacon",
"1 pound tomatoes",
"4 lettuce leaves"
],
photoUrl: "https://wearychef.com/wp-content/uploads/2016/01/turkey-sandwich-with-goat-cheese-and-jam-6.jpg",
cookingInstruction: [
"Preheat the oven broiler.",
"Cut the bread into four pieces, and split lengthwise almost all the way through for four sandwiches. Spread margarine on the inside of each piece. Place on a baking sheet, cut side up.",
"Toast bread under preheated broiler until lightly browned, 1 to 2 minutes. Remove pan from the oven.",
"Layer 4 pieces of bread with 2 slices each of the turkey, cheese, and bacon. Remove the remaining 4 slices of bread from the baking sheet and reserve for sandwich tops. Cool bread slightly, and spread mayonnaise onto the cut side of each of the 4 top slices.",
"Place the bread with turkey and cheese under the broiler just until the cheese melts, about 1 minute. Remove from the broiler, and spread 1 tablespoon cranberry sauce over each sandwich. Layer with the tomatoes and lettuce. Place a top bread slice over each half, and serve."
],
nutritionFacts: "Per Serving: 1068 calories; 65.8 g fat; 70.1 g carbohydrates; 49.5 g protein; 128 mg cholesterol; 3322 mg sodium."
},
{
title: "Ignacio's Super Peanut Butter and Jelly Sandwich",
category: "American",
ingredients: [
"3 slices bread"
],
photoUrl: "https://www.readersdigest.ca/wp-content/uploads/sites/14/2017/04/peanut-butter-and-jelly-facts.jpg",
cookingInstruction: [
"Toast 1 bread slice, allow to cool. Spread one side of each of the two remaining slices with preserves. Spread both sides of the toasted slice with peanut butter. Form a sandwich with the toasted slice in the center."
],
nutritionFacts: "Per Serving: 1068 calories; 65.8 g fat; 70.1 g carbohydrates; 49.5 g protein; 128 mg cholesterol; 3322 mg sodium."
},
{
title: "Shrimp Scampi with Pasta",
category: "American",
ingredients: [
"1 (16 ounce) package linguine pasta",
"2 shallots",
"2 cloves garlic",
"1 pound shrimp",
"1 lemon",
"1 ounce parsley leaves"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/2606852.jpg",
cookingInstruction: [
"Bring a large pot of salted water to a boil; cook linguine in boiling water until nearly tender, 6 to 8 minutes. Drain.",
"Melt 2 tablespoons butter with 2 tablespoons olive oil in a large skillet over medium heat. Cook and stir shallots, garlic, and red pepper flakes in the hot butter and oil until shallots are translucent, 3 to 4 minutes. Season shrimp with kosher salt and black pepper; add to the skillet and cook until pink, stirring occasionally, 2 to 3 minutes. Remove shrimp from skillet and keep warm.",
"Pour white wine and lemon juice into skillet and bring to a boil while scraping the browned bits of food off of the bottom of the skillet with a wooden spoon. Melt 2 tablespoons butter in skillet, stir 2 tablespoons olive oil into butter mixture, and bring to a simmer. Toss linguine, shrimp, and parsley in the butter mixture until coated; season with salt and black pepper. Drizzle with 1 teaspoon olive oil to serve."
],
nutritionFacts: "Per Serving: 511 calories; 19.4 g fat; 57.5 g carbohydrates; 21.9 g protein; 135 mg cholesterol; 260 mg sodium."
},
{
title: "Cream Cheese and Crab Sushi Rolls",
category: "Japanese",
ingredients: [
"2 sheets nori seaweed sheets",
"1 cucumber",
"2 pieces imitation crab legs",
"1/2 (3 ounce) package cream cheese",
"rice"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/4208534.jpg",
cookingInstruction: [
"Bring the rice and water to a boil in a saucepan over high heat. Reduce heat to medium-low, cover, and simmer until the rice is tender, and the liquid has been absorbed, 20 to 25 minutes. Stir in rice vinegar and salt. Allow to cool completely.",
"Lay out seaweed sheets. Moisten hands with water, then spread the rice evenly on each sheet, leaving a 1/2 inch gap along one edge, lengthwise. Arrange strips of cucumber, imitation crabmeat, and cream cheese in a straight line along the side opposite of the gap. Roll the sushi from the toppings to the exposed end of the the seaweed sheet.",
"Using a sharp wet knife, slice each roll into 5 or 6 pieces. Serve with minced ginger on the side."
],
nutritionFacts: "Per Serving: 444 calories; 8.2 g fat; 79.9 g carbohydrates; 10.7 g protein; 29 mg cholesterol; 1475 mg sodium."
},
{
title: "Gyoza",
category: "Japanese",
ingredients: [
"1 cabbage",
"5 onions",
"1 clove garlic",
"1 carrot",
"1/2 pound ground pork",
"1 egg",
"1 (10 ounce) package wonton wrappers"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/250x250/313346.jpg",
cookingInstruction: [
"Heat sesame oil in a large skillet over medium high heat. Mix in cabbage, onion, garlic and carrot. Cook and stir until cabbage is limp. Mix in ground pork and egg. Cook until pork is evenly brown and egg is no longer runny.",
"Preheat vegetable oil in a large skillet over medium high heat.",
"Place approximately 1 tablespoon of the cabbage and pork mixture in the center of each wrapper. Fold wrappers in half over filling, and seal edges with moistened fingers.",
"In the preheated vegetable oil, cook gyoza approximately 1 minute per side, until lightly browned. Place water into skillet and reduce heat. Cover and allow gyoza to steam until the water is gone.",
"In a small bowl, mix soy sauce and rice vinegar. Use the mixture as a dipping sauce for the finished wrappers."
],
nutritionFacts: "Per Serving: 184 calories; 8.5 g fat; 18.5 g carbohydrates; 7.9 g protein; 37 mg cholesterol; 546 mg sodium."
},
{
title: "Soba with Toasted Sesame Seed Sauce",
category: "Japanese",
ingredients: [
"8 ounces dried soba noodles",
"5 onions",
"1 clove garlic",
"5 green onions",
"1 broccoli"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/1167296.jpg",
cookingInstruction: [
"Preheat the oven to 375 degrees F (190 degrees C).",
"Pour the sesame seeds onto a rimmed baking sheet. Toast the seeds in the oven for 10 to 12 minutes, until they are a rich brown around the edges.",
"Meanwhile, bring a large pot of salted water to a boil. Add the noodles and cook them for 5 to 6 minutes, or until they are just tender. Drain them, rinse them well with cold water, and drain them again.",
"In a large mixing bowl, mix together the vinegar, sugar, soy sauce, garlic, sesame oil and green onions. Add the noodles, and the toasted sesame seeds. Toss well, then stir in the broccoli. Let the dish sit for 30 minutes at room temperature before serving."
],
nutritionFacts: "Per Serving: 355 calories; 10.9 g fat; 57.3 g carbohydrates; 14.2 g protein; 0 mg cholesterol; 1037 mg sodium."
},
{
title: "Miso Salmon",
category: "Japanese",
ingredients: [
"2 pounds salmon",
"rice"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/6538331.jpg",
cookingInstruction: [
"Preheat the oven to 400 degrees F (200 degrees C). Fill a large skillet with about 1 inch of water and bring to a boil. Poach fish just until cooked on the outside, about 2 minutes per side. Transfer fillets to a broiler pan.",
"In a small bowl, stir together the miso paste, sake, brown sugar, sesame seeds, sesame oil, water, salad dressing and rice vinegar. Spread this over the tops of the salmon fillets.",
"Bake for 15 minutes in the preheated oven, or until almost cooked through. Switch the oven to broil, and broil until the top is browned and bubbly, about 5 more minutes. Cut fillets into portions to serve."
],
nutritionFacts: "Per Serving: 719 calories; 40.5 g fat; 34.9 g carbohydrates; 50.5 g protein; 132 mg cholesterol; 2247 mg sodium."
},
{
title: "Inside Out Ravioli",
category: "American",
ingredients: [
"16 ounces pasta",
"1 package spinach",
"2 ounces bread crumbs",
"2 eggs",
"1 ounce shredded mozzarella cheese",
"1 pound lean ground beef",
"4 onions",
"1 clove garlic",
"1 (8 ounce) can tomato sauce",
"1 (6 ounce) can tomato paste",
"1 (16 ounce) jar spaghetti sauce"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/663068.jpg",
cookingInstruction: [
"In a medium pot cook pasta in boiling salted water until al dente. Drain well.",
"Cook spinach according to package directions.",
"Meanwhile, brown ground beef, chopped onion, and minced garlic in a large skillet over medium heat. Stir in tomato sauce, tomato paste, and pasta sauce. Simmer for 10 minutes.",
"Combine cooked spinach, cooked pasta, bread crumbs, shredded cheese, beaten eggs, and olive oil.",
"Spread spinach mixture evenly into the bottom of a 9x13 inch baking dish. Top with meat mixture.",
"Bake in a preheated 350 degree F oven (175 degree C) for 30 minutes."
],
nutritionFacts: "Per Serving: 545 calories; 26.4 g fat; 51.7 g carbohydrates; 25.7 g protein; 142 mg cholesterol; 779 mg sodium."
},
{
title: "Shortcut Beef Noodle Bowl",
category: "Chinese,American",
ingredients: [
"1 (16 ounce) package linguine pasta",
"1 broccoli ",
"3 carrots",
"1 pound beef sirloin steak"
],
photoUrl: "https://images.media-allrecipes.com/userphotos/720x405/4458795.jpg",
cookingInstruction: [
"Bring a large pot of lightly salted water to a boil. Cook linguine until firm to the bite, about 9 minutes. Add broccoli and carrots; cook until linguine is tender, about 2 minutes more. Drain.",
"Heat oil in a large nonstick skillet or wok. Add steak slices; cook and stir until browned on all sides, about 4 minutes. Stir in sesame dressing and teriyaki sauce. Cook until sauce is thickened, about 2 minutes.",
"Stir linguine, broccoli, and carrots into the sauce. Increase heat to high and cook until noodles are slightly browned, 2 to 3 minutes."
],
nutritionFacts: "Per Serving: 1055 calories; 56.2 g fat; 101.8 g carbohydrates; 40.1 g protein; 60 mg cholesterol; 1716 mg sodium."
}
].map(m => new Meal(m).save()));
const selectedMeals = await Promise.all([
{
child: childs[0].id,
meals: [{
meal: meals[0].id,
title: "Candy with added sugar",
category: "Bacon",
ingredients: "Double the amount of sugar"
}]
}
].map(sm => new SelectedMeal(sm).save()));
res.status(200).json({
users,
childs,
meals,
selectedMeals,
});
});
router.get("/clear_db", async (req, res)=>{
const collections = await mongoose.connection.db.collections()
const names = collections.map(c => c.collectionName);
for (let collection of collections) {
await collection.drop()
}
res.status(200).json({collections_dropped: names});
});
module.exports = router
|
Java
|
UTF-8
| 11,273
| 2.15625
| 2
|
[] |
no_license
|
package thegirlsteam.whatshappening.tabs;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import thegirlsteam.whatshappening.R;
import thegirlsteam.whatshappening.adapters.LectureListAdapter;
import thegirlsteam.whatshappening.utility.Utility;
/**
* Created by Dona Maria on 11/26/2016.
* Fragment that manages tab for lectures
*/
public class LectureTab extends Fragment{
private ListView lectureListView;
final static List<Lecture> lectures = new ArrayList<Lecture>();
static LectureListAdapter lectureListAdapter;
private String url ="https://mavspace.uta.edu/people/d/dx/dxj2757/output.json";
private TextView noLecture;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.tab_lectures, container, false);
super.onCreate(savedInstanceState);
//rootView.setContentView(R.layout.activity_tabbed);
lectureListView = (ListView) rootView.findViewById(R.id.lecturelist);
lectureListAdapter = new LectureListAdapter(getActivity().getApplicationContext(),R.layout.lecture_list_layout,lectures);
lectureListView.setAdapter(lectureListAdapter);
final String beaconUrl = TabbedActivity.getBeaconUrl();
// Getting the lecture information from URL in the form of JSON data and parsing it.
StringRequest stringRequest = new StringRequest(url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject obj = null,sensorObj,sensorObj2 = null;
JSONArray data = null,sensorArr=null;
String sensorLat = null;
String sensorLon = null;
try {
obj = new JSONObject(response);
data = obj.getJSONArray("class");
sensorObj = obj.getJSONObject("sensor");
System.out.println("Beacon object : " + sensorObj);
sensorArr = sensorObj.getJSONArray(beaconUrl);
if(sensorArr!=null)
sensorObj2 = sensorArr.getJSONObject(0);
System.out.print(data);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < data.length(); i++) {
try {
JSONObject jsonObject = data.getJSONObject(i);
String classroom = jsonObject.getString("Classroom");
String course = jsonObject.getString("Course");
String professor = jsonObject.getString("Professor");
String timing = jsonObject.getString("Timing");
String startTime = jsonObject.getString("Start Time");
String section = jsonObject.getString("Section");
String lat = jsonObject.getString("Latitude");
String lon = jsonObject.getString("Longitude");
//String imageUrl = jsonObject.getString("Image");
Lecture temp = new Lecture();
// Calculating the distance
if(sensorArr!=null && !(lat.equals("")))
{
sensorLat = sensorObj2.getString("latitude");
sensorLon = sensorObj2.getString("longitude");
double dist = Utility.calculateDistance(Double.parseDouble(sensorLat),Double.parseDouble(lat),Double.parseDouble(sensorLon),Double.parseDouble(lon));
double eventDistance = Math.round(dist* 100) / 100;
temp.setDistance(eventDistance);
}
else
{
temp.setDistance(0);
}
// Setting the time left for the lecture to start.
long timeToEvent = 0;
try {
timeToEvent = Utility.timeToStart(startTime);
} catch (ParseException e) {
e.printStackTrace();
}
// To avoid display the lectures that are already done
if(timeToEvent > 30) {
temp.setClassroom(classroom);
temp.setCourse(course);
temp.setProfessor(professor);
temp.setSection(section);
temp.setSensorLat(sensorLat);
temp.setSensorLon(sensorLon);
temp.setTimeToEvent(timeToEvent);
temp.setStartTime(startTime);
temp.setTiming(timing);
temp.setLat(lat);
temp.setLon(lon);
//temp.setImageUrl(imageUrl);
lectures.add(temp);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if(lectures.size()==0)
{
noLecture = (TextView) rootView.findViewById(R.id.no_lectures);
noLecture.setText("No lectures!");
}
else
{
noLecture = (TextView) rootView.findViewById(R.id.no_lectures);
noLecture.setText("");
}
lectureListAdapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(stringRequest);
lectureListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Lecture selectedLecture = lectureListAdapter.getItem(position);
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
//TextView textView = new TextView(getActivity());
//textView.setText(selectedLecture.getCourse()+" - " +selectedLecture.getSection());
alertDialog.setTitle(selectedLecture.getCourse().split("-")[0] +"- " +selectedLecture.getSection());
//alertDialog.setCustomTitle(textView);
String message =null;
if(selectedLecture.getDistance()!=0)
{
if(selectedLecture.getTimeToEvent() > 0)
message = "Lecture starts in "+selectedLecture.getTimeToEvent()+" minutes.\nDistance from you : "
+ selectedLecture.getDistance() + " miles\n\n";
else
message = "Lecture started "+((-1)*selectedLecture.getTimeToEvent())+" minutes ago.\n" +
"Distance from you : " + selectedLecture.getDistance() + "\n\n";
}
else
{
if(selectedLecture.getTimeToEvent() > 0)
message = "Lecture starts in "+selectedLecture.getTimeToEvent()+" minutes.\n";
else
message = "Lecture started "+((-1)*selectedLecture.getTimeToEvent())+" minutes ago.\n";
message += "Distance is information not available\n\n";
}
alertDialog.setMessage(message + selectedLecture.getCourse().split("- ")[1] + "\n" +selectedLecture.getProfessor() + "\n" +selectedLecture.getClassroom() + "\n" + selectedLecture.getStartTime()+"\n");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Got it!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
final Button positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
LinearLayout.LayoutParams positiveButtonLL = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
positiveButtonLL.gravity = Gravity.CENTER;
positiveButton.setLayoutParams(positiveButtonLL);
}
});
return rootView;
}
// SOrting the list
public static void sortList(final int item, String order){
Comparator<Lecture> comparator = new Comparator<Lecture>() {
@Override
public int compare(Lecture e1, Lecture e2) {
if (item == 1)
return Double.compare(e1.getDistance() , e2.getDistance());
else
return Double.compare(e1.getTimeToEvent() , e2.getTimeToEvent());
}
};
if(order.equals("asc")) {
Collections.sort(lectures, comparator);
}
else
{
Collections.sort(lectures, Collections.reverseOrder(comparator));
}
lectureListAdapter.notifyDataSetChanged();
}
}
|
C++
|
UTF-8
| 1,661
| 2.984375
| 3
|
[] |
no_license
|
#include "header.h"
#include "globals.h"
// determines if a critter can view given coordinates
bool in_line_of_sight(int critter_id, int level_id, int x, int y) {
int critter_x = game.critters[critter_id].x;
int critter_y = game.critters[critter_id].y;
int critter_level = game.critters[critter_id].level_id; // not its hit dice
// obvious fail condition
if (level_id != critter_level) return false;
// bresenham setup
int x0, x1, y0, y1;
x0 = critter_x; x1 = x;
y0 = critter_y; y1 = y;
int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1;
int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1;
int err = (dx>dy ? dx : -dy)/2, e2;
// bresenham loop
for(;;){
// check if something blocks vision
if (x0==x1 && y0==y1) return true; // can see, even if final tile is non-transparent
if (!(game.levels[level_id].tiles[x0][y0].transparent)) break; // can't see
e2 = err;
if (e2 >-dx) { err -= dy; x0 += sx; }
if (e2 < dy) { err += dx; y0 += sy; }
}
return false; // default
}
int distance_between_tiles(int x0, int x1, int y0, int y1) {
// assumes same level
return sqrt(pow(x0 - x1,2) + pow(y0 - y1,2));
}
// reveals all the player critter can currently see, use in turn determination
void reveal_los() {
for (int i=0;i<MAP_MAXX;i++) {
for (int j=0;j<MAP_MAXY;j++) {
// can see? reveal
if (distance_between_tiles(player.x,i,player.y,j) < 10)
if (in_line_of_sight(PLAYER_CRITTER,player.level_id,i,j)) {
game.levels[player.level_id].tiles[i][j].explored = true;
}
}
}
}
|
Python
|
UTF-8
| 892
| 2.65625
| 3
|
[] |
no_license
|
#1-car-navigation
def name():
return '1-car navigation'
def problem():
# Discretize the navigation system at https://publish.illinois.edu/c2e2-tool/example/navigation-system/
A = [[1,0,0.1,0],
[0,1,0,0.1],
[0,0,0.8870, 0.0089],
[0,0, 0.0089, 0.8870]
]
B = [[0,0],[0,0],[1,0],[0,1]]
u_range = 5
u_space = (True, [(-u_range, u_range) for i in range(2)])
avoid_5 = (True, [(-2, 5), (-5, 3), (None, None), (None, None)])
avoid_list = [avoid_5]
target = (True, [(1,4), (3,6), (None, None), (None, None)])
initial_size = 0.8
center = [-3,-3,0,0]
num_steps = 10
u_dim = 2
avoid_dynamic = None
Theta = (True, [(c - 0.5, c + 0.5) for c in [-3,-3]] + [(0, 0), (0, 0)])
safe_rec = (True, [(-5, 5), (-5, 5), (None, None), (None, None)])
return initial_size, center, A, B, u_space, target, avoid_list, num_steps,u_dim, avoid_dynamic, Theta, safe_rec
|
JavaScript
|
UTF-8
| 1,108
| 4.6875
| 5
|
[] |
no_license
|
// ==========================================
// FIND
// ==========================================
// returns the value of the first element in the provided array that satisfies the provided testing function
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
// ==========================================
var array = ["puppies", "dogs", "puppy", "my dog", "doggo"];
var output = array.find((dog)=>{ return dog === "my dog"; });
//output: "my dog"
// ==========================================
// Syntax
// ==========================================
// // Arrow function
// find((element) => { ... } )
// find((element, index) => { ... } )
// find((element, index, array) => { ... } )
// // Callback function
// find(callbackFn)
// find(callbackFn, thisArg)
// // Inline callback function
// find(function callbackFn(element) { ... })
// find(function callbackFn(element, index) { ... })
// find(function callbackFn(element, index, array){ ... })
// find(function callbackFn(element, index, array) { ... }, thisArg)
|
C++
|
UTF-8
| 2,610
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include <cstdint>
#include <glm/glm.hpp>
#include <vector>
#include "QuadTreeDefines.h"
class PlanetTileServer;
class QuadTreeNode
{
private:
public:
// Top-left bound of the node
glm::dvec2 min_point;
double size;
PlanetSide planetside;
QuadTreeQuadrant quad;
// Can be in another side of the cube, so be careful
// North, East, South, West
QuadTreeNode* neighbors[4];
// Children
// Northwest, Northeast, SoutWest, SouthEast
QuadTreeNode* children[4];
// Parent
QuadTreeNode* parent;
// Patch (Renderable mesh)
// 0 is a root node
size_t depth;
// Returns true if split was possible
bool split(bool get_neighbors = true);
// Merges all children, destroying them
bool merge();
// A leaf node has no children
bool has_children() const;
bool is_children_of(const QuadTreeNode* b) const;
// Recursively splits until we get a node with depth equal to maxDepth
// It will automatically merge not-neccesary nodes, this is
// the central function of the planet rendering system
QuadTreeNode* get_recursive(glm::dvec2 coord, size_t maxDepth);
// Simpler method that ignores diagonal detail, used by physics
QuadTreeNode* get_recursive_simple(glm::dvec2 coord, size_t maxDepth);
glm::dvec2 get_center();
// Returns a equivalent to QuadTreeQuadrant if inside, -1 if outside
int get_quadrant(glm::dvec2 coord);
// Gets given quadrant, splits if neccesary
QuadTreeNode* get_or_split(QuadTreeQuadrant quad, bool nosplit = false);
void merge_all_but(QuadTreeNode* node);
void obtain_neighbors(QuadTreeQuadrant quad, bool nosplit = false);
// Draws a "widget" of the subdivided quad tree nodes
void draw_gui(int guiSize, PlanetTileServer* server);
QuadTreeSide find_touching_side(QuadTreeNode* node);
bool touches_any_edge();
// Gets the path to this quad tree node, from its parent to the node
// For example, a node may be {NW, NW, NE}, the first quadrant is the
// root, second is parent of the parent and last is the parent
std::vector<QuadTreeQuadrant> get_path() const;
// Gets all nodes with no children, sons of this node
std::vector<QuadTreeNode*> get_all_leaf_nodes();
std::vector<std::vector<QuadTreeQuadrant>> get_all_leaf_paths() const;
std::vector<QuadTreeNode*> get_all();
std::vector<std::vector<QuadTreeQuadrant>> get_all_paths() const;
QuadTreeNode* follow_path(std::vector<QuadTreeQuadrant> path);
QuadTreeNode();
QuadTreeNode(QuadTreeNode* n_nbor, QuadTreeNode* e_nbor, QuadTreeNode* s_nbor, QuadTreeNode* w_nbor);
QuadTreeNode(QuadTreeNode* parent, QuadTreeQuadrant quad);
~QuadTreeNode();
};
|
Java
|
UTF-8
| 499
| 3.171875
| 3
|
[] |
no_license
|
package com.basic;
import java.util.*;
public class DuplicateSample{
public static void main(String a[])
{
int count=0;
Scanner scan=new Scanner(System.in);
System.out.println("enter something");
String one=scan.nextLine();
String two[]=one.split("\\s");
for(int i=0;i<two.length-1;i++)
{
for(int j=0;j<two.length-1;j++)
{
if(two[i].equalsIgnoreCase(two[j]))
{
if(i!=j)
count++;
}
}
}
System.out.println(count);
}
}
|
C++
|
UTF-8
| 1,770
| 2.53125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
#pragma once
#include "rbtree.h"
#include "VKRenderer.h"
typedef enum VkResourceType {
VK_RESOURCE_TYPE_FREE = 0,
VK_RESOURCE_TYPE_UNKNOW,
VK_RESOURCE_TYPE_BUFFER,
VK_RESOURCE_TYPE_IMAGE_LINEAR,
VK_RESOURCE_TYPE_IMAGE_OPTIMAL,
} VkResourceType;
typedef struct mem_node {
mem_node(CVKMemory* pFreeMemory);
~mem_node(void);
rb_node node;
CVKMemory* pMemory;
} mem_node;
class CVKMemory
{
friend struct mem_node;
friend class CVKMemoryAllocator;
friend class CVKMemoryManager;
private:
CVKMemory(CVKDevice* pDevice, CVKMemoryAllocator* pAllocator, VkDeviceSize memorySize, VkDeviceSize memoryOffset);
virtual ~CVKMemory(void);
private:
CVKMemoryAllocator* GetAllocator(void) const;
public:
VkDeviceSize GetSize(void) const;
VkDeviceSize GetOffset(void) const;
public:
bool BindImage(VkImage vkImage) const;
bool BindBuffer(VkBuffer vkBuffer) const;
public:
bool BeginMap(void);
bool CopyData(VkDeviceSize offset, VkDeviceSize size, const void* data);
bool EndMap(void);
public:
bool IsDeviceLocal(void) const;
bool IsHostVisible(void) const;
bool IsHostCoherent(void) const;
bool IsHostCached(void) const;
bool IsLazilyAllocated(void) const;
private:
// Memory Block
//
// | Memory Size |
// |-------------------------------------|
// | | |
// | Padding | Valid Size |
// |_________|___________________________|
// | |
// Offset |
// AlignmentOffset
VkDeviceSize m_memorySize;
VkDeviceSize m_memoryOffset;
VkDeviceSize m_memoryPadding;
private:
CVKMemoryAllocator* m_pAllocator;
private:
CVKDevice* m_pDevice;
private:
VkResourceType type;
CVKMemory* pNext;
CVKMemory* pPrev;
private:
mem_node* pMemoryNode;
};
|
C#
|
UTF-8
| 9,981
| 2.59375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace CSP_SemestralWork
{
/// <summary>
/// Interaction logic for Edit.xaml
/// </summary>
public partial class Edit : Window
{ //varibale type of meeting center expecting an object
private MeetingCenter EditCenter = null;
private MeetingRoom EditRoom = null;
private MeetingCenter NewCenter = null;
private MeetingCenter NewRoom_center = null;
public Edit()
{
InitializeComponent();
}
// when class is instanciated with parameter type MeetingCenter edit window will start
// object MeetingCenter editing mode
public Edit(MeetingCenter obj)
{
EditCenter = obj;
InitializeComponent();
FormWindow.Title = "Edit Meeting Centre";
EditBtns.Visibility = Visibility.Visible;
tboxName.Text = EditCenter.Name;
tboxCode.IsEnabled = false;
tboxCode.Text = EditCenter.Code;
tboxDesc.Text = EditCenter.Description;
//Extra dunction load elements in windows specific to Meeting center
}
//Edit MeetingRoom
public Edit(MeetingRoom obj)
{
InitializeComponent();
EditRoom = obj;
InitializeComponent();
EditBtns.Visibility = Visibility.Visible;
tboxName.Text = EditRoom.Name;
tboxCode.Text = EditRoom.Code;
tboxDesc.Text = EditRoom.Description;
//Extra function load elements in windows specific to Meeting center
EditMeetingRoom();
}
//Edit method - if varible room is included object type MeetingRoom throughout constructor
private void EditMeetingRoom()
{
FormWindow.Title = "Edit Meeting Room";
RoomTextBox.Visibility = Visibility.Visible;
tboxCapacity.Text = EditRoom.Capacity.ToString();
MRVideoConferenceCheckBox.IsChecked = EditRoom.VideoConference;
//Method part prepared for editing function change of Meeting cetentre in a room
CBoxEditCentre.ItemsSource = Data.MeetingCenters;
//Varible EditRoom is passed through constructor by selescting meeting room nad pressing edit button in the main window
CBoxEditCentre.IsEnabled = true;
CBoxEditCentre.Text = EditRoom.Centre.Code;
}
//Method creates a new MeetingCenter
public void NewMeetingCentre()
{
FormWindow.Title = "Add New Meeting Centre";
NewBtns.Visibility = Visibility.Visible;
NewCenter = new MeetingCenter();
}
//Method prepares environmet for a new MeetingCenter
public void NewMeetingRoom(MeetingCenter obj)
{
FormWindow.Title = "Add New Meeting Room";
NewRoom_center = obj;
RoomTextBox.Visibility = Visibility.Visible;
NewBtns.Visibility = Visibility.Visible;
//Code of meeting centre in room detail
CBoxEditCentre.IsEnabled = false;
CBoxEditCentre.ItemsSource = Data.MeetingCenters;
CBoxEditCentre.Text = NewRoom_center.Code;
}
//Method id called to save data
private void save()
{
if(EditCenter != null)
{
EditCenter.Name = tboxName.Text;
EditCenter.Code = tboxCode.Text;
EditCenter.Description = tboxDesc.Text;
}
//EditRoom Saving data
else if(EditRoom != null)
{
EditRoom.Name = tboxName.Text;
EditRoom.Code = tboxCode.Text;
EditRoom.Description = tboxDesc.Text;
EditRoom.Capacity = int.Parse(tboxCapacity.Text);
EditRoom.VideoConference = MRVideoConferenceCheckBox.IsChecked.ToString() == "True" ? true : false;
if ((CBoxEditCentre.SelectedItem as MeetingCenter).Code != EditRoom.Centre.Code)
{
EditRoom.MoveToMeetingCenter((CBoxEditCentre.SelectedItem as MeetingCenter).Code);
}
}
//Saving New MeetingCentre
else if(NewCenter != null)
{
NewCenter.Name = tboxName.Text;
NewCenter.Code = tboxCode.Text;
NewCenter.Description = tboxDesc.Text;
Data.MeetingCenters.Add(NewCenter);
}
// Saving new Room in meeting centre
else if (NewRoom_center != null)
{
MeetingRoom NewRoom = new MeetingRoom();
NewRoom.Name = tboxName.Text;
NewRoom.Code = tboxCode.Text;
NewRoom.Description = tboxDesc.Text;
NewRoom.VideoConference = MRVideoConferenceCheckBox.IsChecked.ToString() == "True" ? true : false;
CBoxEditCentre.IsEnabled = false;
try
{
NewRoom.Capacity = int.Parse(tboxCapacity.Text);
}
catch
{
MessageBox.Show("Error of capacity input type.");
}
NewRoom.Centre = NewRoom_center;
NewRoom_center.MeetingRooms.Add(NewRoom);
}
//When data saved, let main window know to show "Savechages" on exit.
MainWindow.DataChanged = true;
}
private void btSave_Click(object sender, RoutedEventArgs e)
{
try
{
//Validate data before saving
if (validate())
{
save();
this.Close();
}
}
catch
{
MessageBox.Show("Error");
}
}
//This method does validation according to which type of form is used nad wich data are being saved
private bool validate()
{ //isvalid - a varible which indicates, whether the form is valid
bool isvalid = true;
Regex regex = null;
Match match = null;
//Validation of NewCenter and EditingCenter, NewRoom and EditRoom form - their common textboxes
if (NewCenter != null || EditCenter != null || NewRoom_center !=null || EditRoom != null)
{
//Name textbox validation on edit or new center
regex = new Regex(@"(.){2,200}");
match = regex.Match(tboxName.Text);
if (!match.Success)
{
isvalid = false;
tboxName.Background = Brushes.LightPink;
}
else
{
tboxName.Background = Brushes.White;
}
//Code textbox validation on editing or creating center
regex = new Regex(@"^(?:[a-zA-Z:._]){5,50}?$");
match = regex.Match(tboxCode.Text);
if (!match.Success)
{
isvalid = false;
tboxCode.Background = Brushes.LightPink;
}
else
{
tboxCode.Background = Brushes.White;
}
//Description textbox validation on edit or new center
regex = new Regex(@"(.){10,300}");
match = regex.Match(tboxDesc.Text);
if (!match.Success)
{
isvalid = false;
tboxDesc.Background = Brushes.LightPink;
}
else
{
tboxDesc.Background = Brushes.White;
}
}
//**New Meeeting Centre is being created
if(NewCenter != null) {
//This Conditions checks duplicity of fille New Centre code
if (Data.GetMeetingCenterByCode(tboxCode.Text) != null)
{
isvalid = false;
tboxCode.Background = Brushes.LightPink;
}
}
//**New / Edit a Meeting Room
if (NewRoom_center != null || EditRoom != null)
{
//Capacity textbox validation on edit or new center
regex = new Regex(@"^([1-9]|[1-9][0-9]|1[0]{2})$");
match = regex.Match(tboxCapacity.Text);
if (!match.Success)
{
isvalid = false;
tboxCapacity.Background = Brushes.LightPink;
}
else
{
tboxCapacity.Background = Brushes.White;
}
}
//****Result of validation return true or false****
if (isvalid == true) { return true; } else { return false; }
}//end of validation function
private void Cancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btCreate_Click(object sender, RoutedEventArgs e)
{
if (validate())
{
save();
this.Close();
}
}
// If strted typing into form detects changes and validates them
private void StackPanel_KeyUp(object sender, KeyEventArgs e)
{
validate();
}
}
}
|
Python
|
UTF-8
| 1,786
| 3.484375
| 3
|
[] |
no_license
|
from io import StringIO
import string
plaintext_ = string.ascii_lowercase
ciphertext_ = string.ascii_uppercase
#加密算法
def encryption(plaintext):
cipherarr = [0 for i in range(len(plaintext))]
plaintext_list = list(plaintext)
j = 0
for plaintext_item in plaintext_list:
for i in range(len(plaintext_)):
if plaintext_item == plaintext_[i]:
ciphertext = (11*i+4)%26
cipherarr[j] = ciphertext_[ciphertext]
j = j+1
cipher = (''.join('%s'%id for id in cipherarr))
return cipher
#解密算法
def decryption(ciphertext):
plaintext_arr = [0 for i in range(len(ciphertext))]
cipherlist = list(ciphertext)
j = 0
for cipheritem in cipherlist:
for i in range(len(ciphertext_)):
if cipheritem == ciphertext_[i]:
plaintext = (19*i-24)%26
plaintext_arr[j] = plaintext_[plaintext]
j = j+1
else:
pass
plain =(''.join('%s'%id for id in plaintext_arr))
return plain
def main():
while True:
#print('请输入需要的操作(encrypt/decrypt)')
choice=input('请输入需要的操作(encrypt/decrypt):')
if choice=='encrypt':
plaintext = input('请输入明文:')
cipher = encryption(plaintext)
if plaintext == 'exit':
break
print ('密文输出:%s'%cipher)
elif choice=='decrypt':
ciphertext = input('请输入密文:')
plain = decryption(ciphertext)
if ciphertext == 'exit':
break
print ('明文输出:%s'%plain)
else:
print('功能输入错误')
if __name__=='__main__':
main()
|
Java
|
UTF-8
| 2,799
| 2.296875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package io.smallrye.reactive.messaging.providers.connectors;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import jakarta.enterprise.context.ApplicationScoped;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.reactive.messaging.Message;
import org.eclipse.microprofile.reactive.messaging.spi.Connector;
import org.eclipse.microprofile.reactive.messaging.spi.IncomingConnectorFactory;
import org.eclipse.microprofile.reactive.messaging.spi.OutgoingConnectorFactory;
import org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder;
import org.eclipse.microprofile.reactive.streams.operators.ReactiveStreams;
import org.eclipse.microprofile.reactive.streams.operators.SubscriberBuilder;
import io.reactivex.Flowable;
import io.smallrye.reactive.messaging.OutgoingMessageMetadata;
@ApplicationScoped
@Connector("dummy")
public class MyDummyConnector implements IncomingConnectorFactory, OutgoingConnectorFactory {
private final List<String> list = new CopyOnWriteArrayList<>();
private final List<Config> configs = new CopyOnWriteArrayList<>();
private boolean completed = false;
public void reset() {
list.clear();
completed = false;
}
public List<String> list() {
return list;
}
@Override
public SubscriberBuilder<? extends Message<?>, Void> getSubscriberBuilder(Config config) {
this.configs.add(config);
return ReactiveStreams.<Message<?>> builder()
.peek(x -> list.add(x.getPayload().toString()))
.peek(x -> x.getMetadata(OutgoingMessageMetadata.class).ifPresent(m -> m.setResult(x.getPayload())))
.peek(x -> {
try {
x.ack().toCompletableFuture().get();
} catch (InterruptedException | ExecutionException e) {
try {
x.nack(e).toCompletableFuture().get();
} catch (InterruptedException | ExecutionException ex) {
throw new RuntimeException(ex);
}
}
})
.onComplete(() -> completed = true)
.ignore();
}
@Override
public PublisherBuilder<? extends Message<?>> getPublisherBuilder(Config config) {
this.configs.add(config);
int increment = config.getOptionalValue("increment", Integer.class).orElse(1);
return ReactiveStreams
.fromPublisher(Flowable.just(1, 2, 3).map(i -> i + increment).map(Message::of));
}
boolean gotCompletion() {
return completed;
}
List<Config> getConfigs() {
return configs;
}
}
|
Java
|
UTF-8
| 3,171
| 2.25
| 2
|
[
"MIT"
] |
permissive
|
package ua.com.fielden.platform.web.centre.api.actions.multi;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import ua.com.fielden.platform.dom.DomElement;
import ua.com.fielden.platform.web.centre.api.actions.EntityActionConfig;
import ua.com.fielden.platform.web.centre.api.crit.impl.AbstractCriterionWidget;
import ua.com.fielden.platform.web.centre.api.resultset.impl.FunctionalActionElement;
import ua.com.fielden.platform.web.centre.api.resultset.impl.FunctionalActionKind;
import ua.com.fielden.platform.web.interfaces.IImportable;
import ua.com.fielden.platform.web.interfaces.IRenderable;
/**
* {@link IRenderable} and {@link IImportable} element that represents multiple action element and it is renderable into tg-egi-multi-action component instance.
*
* @author TG Team
*
*/
public class FunctionalMultiActionElement implements IRenderable, IImportable {
private final String widgetName;
private final String widgetPath;
private final List<FunctionalActionElement> actionElements = new ArrayList<>();
/**
* Creates new muti action element based on config, action number and it's kind. This element is rendered into tg-egi-multi-action with set of simple tg-ui-action inside shadow dom.
*
* @param entityMultiActionConfig
* @param numberOfAction
* @param actionKind
*/
public FunctionalMultiActionElement(final EntityMultiActionConfig entityMultiActionConfig, final int numberOfAction, final FunctionalActionKind actionKind) {
this.widgetPath = "egi/tg-egi-multi-action";
this.widgetName = AbstractCriterionWidget.extractNameFrom(this.widgetPath);
for (int configIndex = 0; configIndex < entityMultiActionConfig.actions().size(); configIndex++) {
final EntityActionConfig entityActionConfig = entityMultiActionConfig.actions().get(configIndex);
actionElements.add(new FunctionalActionElement(entityActionConfig, numberOfAction + configIndex, actionKind));
}
}
@Override
public DomElement render() {
final DomElement multiActionElement = new DomElement(widgetName);
for(final FunctionalActionElement el: actionElements) {
multiActionElement.add(el.render().attr("slot", "multi-action-item"));
}
return multiActionElement;
}
/**
* Creates a string representation for the object which holds attributes, pre- and post-actions.
*
* @return
*/
public String createActionObject(final LinkedHashSet<String> importPaths) {
final String prefix = ",\n";
final StringBuilder actionsObjects = new StringBuilder();
for(final FunctionalActionElement el: actionElements) {
importPaths.add(el.importPath());
actionsObjects.append(prefix + el.createActionObject());
}
final int prefixLength = prefix.length();
final String actionString = actionsObjects.toString();
return actionString.length() > prefixLength ? actionString.substring(prefixLength) : actionString;
}
@Override
public String importPath() {
return widgetPath;
}
}
|
C
|
UTF-8
| 4,502
| 2.6875
| 3
|
[] |
no_license
|
/*******************************************************************************
* @file Thread_LED.c
* @author Ashraf Suyyagh
* @version V1.0.0
* @date 17-January-2016
* @brief This file initializes one LED as an output, implements the LED thread
* which toggles and LED, and function which creates and starts the thread
******************************************************************************
*/
#include "cmsis_os.h" // ARM::CMSIS:RTOS:Keil RTX
#include "stm32f4xx_hal.h"
#include "main.h"
#include "gpio.h"
#include "adc.h"
#include "accelerometer.h"
#include "UART.h"
extern UART_HandleTypeDef UARTHandle;
extern uint32_t pData1[300];
extern float yArray[300];
extern float xArray[300];
extern float zArray[300];
int accelerometerValuesReady = 0;
void USARTThread(void const *argument);
osThreadDef(USARTThread, osPriorityNormal, 1, 0);
void DACThread(void const *argument);
osThreadDef(DACThread, osPriorityNormal, 1, 0);
void accelThread(void const *argument);
osThreadDef(accelThread, osPriorityNormal, 1, 0);
void buttonThread(void const *argument);
osThreadDef(buttonThread, osPriorityNormal, 1, 0);
/*----------------------------------------------------------------------------
* USART Thread Context creation
*---------------------------------------------------------------------------*/
osThreadId startUSARTThread(osThreadId USARTThreadID){
USARTThreadID = osThreadCreate(osThread(USARTThread ), NULL);
if(!USARTThreadID) return NULL;
else return(USARTThreadID);
}
/*----------------------------------------------------------------------------
* USART thread content
*---------------------------------------------------------------------------*/
void USARTThread(void const *argument){
uint8_t received;
int i;
float *xAnglesOut;
float *yAnglesOut;
float *zAnglesOut;
static const uint8_t Data = 0x01;
configureUSARTGPIO();
configureUART();
UART_Transmit(Data);
HAL_UART_Receive_IT(&UARTHandle,(uint8_t*) pData1, 1200);
while(1){
//UART_Transmit(Data);
//received = UART_Receive();
//osDelay(10);
if(areAnglesReady())
{
UART_Transmit_Float(xArray);
osDelay(500);
UART_Transmit_Float(yArray);
osDelay(500);
UART_Transmit_Float(zArray);
anglesSent();
}
}
}
/*----------------------------------------------------------------------------
* USART Thread Context creation
*---------------------------------------------------------------------------*/
osThreadId startDACThread(osThreadId DACThreadID){
DACThreadID = osThreadCreate(osThread(USARTThread ), NULL);
if(!DACThreadID) return NULL;
else return(DACThreadID);
}
/*----------------------------------------------------------------------------
* USART thread content
*---------------------------------------------------------------------------*/
void DACThread(void const *argument){
}
/*----------------------------------------------------------------------------
* Accelerometer Thread Context creation
*---------------------------------------------------------------------------*/
osThreadId startAccelThread(osThreadId accelThreadID){
accelThreadID = osThreadCreate(osThread(accelThread ), NULL);
if(!accelThreadID) return NULL;
else return(accelThreadID);
}
/*----------------------------------------------------------------------------
* Accelerometer thread content
*---------------------------------------------------------------------------*/
void accelThread(void const *argument){
initAccelerometer(getHandleSPI());
while(1){
if(accelerometerValuesReady && isCollectingAngles())
{
collectXYZ();
accelerometerValuesReady = 0;
}
}
}
/*----------------------------------------------------------------------------
* Accelerometer Thread Context creation
*---------------------------------------------------------------------------*/
osThreadId startButtonThread(osThreadId buttonThreadID){
buttonThreadID = osThreadCreate(osThread(buttonThread ), NULL);
if(!buttonThreadID) return NULL;
else return(buttonThreadID);
}
/*----------------------------------------------------------------------------
* Accelerometer thread content
*---------------------------------------------------------------------------*/
void buttonThread(void const *argument)
{
while(1)
{
osDelay(10);
if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0))
{
startCollectingAngles();
}
}
}
void setAccelerometerValuesReady(void)
{
accelerometerValuesReady = 1;
}
|
Java
|
UTF-8
| 1,759
| 2.234375
| 2
|
[] |
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 eapli.ecafeteria.persistence.inmemory;
import eapli.ecafeteria.domain.pos.POS;
import eapli.ecafeteria.domain.pos.POSState;
import eapli.ecafeteria.persistence.POSRepository;
import eapli.framework.persistence.DataConcurrencyException;
import eapli.framework.persistence.DataIntegrityViolationException;
import eapli.framework.persistence.repositories.impl.inmemory.InMemoryRepositoryWithLongPK;
import java.util.ArrayList;
import java.util.Optional;
/**
*
* @author hugod
*/
public class InMemoryPOSRepository extends InMemoryRepositoryWithLongPK<POS> implements POSRepository {
@Override
public Iterable<POS> findByState(POSState s) {
ArrayList<POS> list_pos = new ArrayList<>();
list_pos = (ArrayList<POS>) match(pos -> pos.state().equalsIgnoreCase(s.toString()));
return list_pos;
}
@Override
public Iterable<POS> findAll() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Optional<POS> findOne(Long id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public long count() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public POS saveWithDelete(POS p) {
super.delete(p);
super.save(p);
return p;
}
}
|
C#
|
UTF-8
| 4,061
| 2.734375
| 3
|
[] |
no_license
|
using SQLite4Unity3d;
using UnityEngine;
#if !UNITY_EDITOR
using System.Collections;
using System.IO;
#endif
using System.Collections.Generic;
public class DataService {
private SQLiteConnection _connection;
public DataService(string DatabaseName){
#if UNITY_EDITOR
var dbPath = string.Format(@"Assets/StreamingAssets/{0}", DatabaseName);
#else
// check if file exists in Application.persistentDataPath
var filepath = string.Format("{0}/{1}", Application.persistentDataPath, DatabaseName);
if (!File.Exists(filepath))
{
Debug.Log("Database not in Persistent path");
// if it doesn't ->
// open StreamingAssets directory and load the db ->
#if UNITY_ANDROID
var loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + DatabaseName); // this is the path to your StreamingAssets in android
while (!loadDb.isDone) { } // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
// then save to Application.persistentDataPath
File.WriteAllBytes(filepath, loadDb.bytes);
#elif UNITY_IOS
var loadDb = Application.dataPath + "/Raw/" + DatabaseName; // this is the path to your StreamingAssets in iOS
// then save to Application.persistentDataPath
File.Copy(loadDb, filepath);
#elif UNITY_WP8
var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
// then save to Application.persistentDataPath
File.Copy(loadDb, filepath);
#elif UNITY_WINRT
var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
// then save to Application.persistentDataPath
File.Copy(loadDb, filepath);
#elif UNITY_STANDALONE_OSX
var loadDb = Application.dataPath + "/Resources/Data/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
// then save to Application.persistentDataPath
File.Copy(loadDb, filepath);
#else
var loadDb = Application.dataPath + "/StreamingAssets/" + DatabaseName; // this is the path to your StreamingAssets in iOS
// then save to Application.persistentDataPath
File.Copy(loadDb, filepath);
#endif
Debug.Log("Database written");
}
var dbPath = filepath;
#endif
_connection = new SQLiteConnection(dbPath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
Debug.Log("Final PATH: " + dbPath);
}
public void CreateDB(){
Debug.Log("Create DB called ");
_connection.DropTable<User> ();
_connection.CreateTable<User> ();
_connection.DropTable<Session> ();
_connection.CreateTable<Session> ();
_connection.DropTable<Cordinates> ();
_connection.CreateTable<Cordinates> ();
_connection.DropTable<Attempts> ();
_connection.CreateTable<Attempts> ();
}
public IEnumerable<User> GetUsers(){
return _connection.Table<User>();
}
public IEnumerable<Session> GetSessions(){
return _connection.Table<Session>();
}
public User CreateGivenUser(User p){
User tmp = null;
tmp = _connection.Table<User>().Where(x => x.Name == p.Name).FirstOrDefault();
if (tmp == null){
_connection.Insert(p);
tmp = _connection.Table<User>().Where(x => x.Name == p.Name).FirstOrDefault();
}
return tmp;
}
public Session CreateGivenSession(Session s){
_connection.Insert(s);
var m = QueryValuations(_connection,s);
foreach (var per in m) {
return per;
}
return s;
}
public Cordinates CreateGivenCordinates(Cordinates cord){
_connection.Insert(cord);
return cord;
}
public Attempts CreateGivenAttempt(Attempts attmpt){
_connection.Insert(attmpt);
return attmpt;
}
public static IEnumerable<Session> QueryValuations(SQLiteConnection db, Session sess)
{
return db.Query<Session> ("select * from Session where UserID = ? order by SessionId desc", sess.UserID);
}
}
|
Markdown
|
UTF-8
| 736
| 2.75
| 3
|
[] |
no_license
|
# [RPS Multiplayer](https://github.com/LMBoyle/rpsMultiplayer)
Play the game of rock, paper, scissors in the style of Avatar the Last Airbender
## Instructions
Enter your name then wait for someone else to join.
When there are two players choose your element, wait for your opponent to choose theirs and find out who won.
To use chat, type whatever you want and send it for your opponent to see.
## Built With
* HTML
* CSS
* JavaScript
* jQuery
* Firebase
## Demo

## Future Development/Improvements
- [ ] Mobile Responsive
- [ ] Have chat clear out previous session text
- [ ] Center game more in the middle of the page instead of the top
© 2019 [Luke Boyle](https://lmboyle.github.io/)
|
Python
|
UTF-8
| 1,450
| 3.5
| 4
|
[] |
no_license
|
'''
Created on 2018. 12. 6.
MLP (다층 신경망) : 입력층과 출력층 사이에 중간층을
'''
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
x = [[0,0], [0,1], [1,0], [1,1]]
y = [0,1,1,0]
clf = MLPClassifier(hidden_layer_sizes=(3,2), random_state=0)
print(clf)
clf.fit(x,y)
x = [[1,1],[1,1],[1,0],[1,2]]
print(clf.predict(x))
print('정확도 : ', clf.score(x, y))
print('**' * 50)
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
print(cancer.keys())
x = cancer['data']
y = cancer['target']
print(x[0])
print(y[0])
print(x.shape) # (569, 30)
print(y.shape) # (569,)
x_train, x_test, y_train, y_test = train_test_split(x,y)
print(x_train.shape) # (426, 30)
print(x_test.shape) # (143, 30)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(x_train)
scaler.fit(x_test)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)
print(x_train[:1])
mlp = MLPClassifier(hidden_layer_sizes=(30, 30, 30), random_state=1)
mlp.fit(x_train, y_train)
pred = mlp.predict(x_test)
print(x_test)
print('예측값 : ', pred)
print()
print('실제값 : ', y_test[:50])
print('예측값 : ', pred[:50])
print('정확도 : ', mlp.score(x_test, y_test)) # mlp에 있는 모델과 x,y_test와 비교해 정확도를 보여줌.
from sklearn.metrics import classification_report
print(classification_report(y_test, pred))
|
Java
|
UTF-8
| 793
| 3.265625
| 3
|
[] |
no_license
|
package prg.clxmm;
import java.util.ArrayList;
import java.util.List;
/**
* @author clxmm
* @version 1.0
* @date 2021/1/27 8:06 下午
*/
public class Test02Atomicity {
/**
* 5个线程各执行1000次 i++;
* @param args
*/
private static int number = 0;
public static void main(String[] args) throws InterruptedException {
Runnable inc = () -> {
for (int i = 0; i < 1000; i++) {
number ++;
}
};
List<Thread> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Thread t = new Thread(inc);
t.start();
list.add(t);
}
for (Thread thread : list) {
thread.join();
}
System.out.println(number);
}
}
|
Java
|
UTF-8
| 18,598
| 1.890625
| 2
|
[] |
no_license
|
package com.example.a29149.yuyuan.ModelStudent.Me.Reward;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.a29149.yuyuan.DTO.RewardDTO;
import com.example.a29149.yuyuan.ModelStudent.Discovery.Adapter.RewardAdapter;
import com.example.a29149.yuyuan.R;
import com.example.a29149.yuyuan.Util.AdapterManager;
import com.example.a29149.yuyuan.Util.Annotation.AnnotationUtil;
import com.example.a29149.yuyuan.Util.Annotation.ViewInject;
import com.example.a29149.yuyuan.Util.Const;
import com.example.a29149.yuyuan.Util.GlobalUtil;
import com.example.a29149.yuyuan.controller.course.reward.UpdateController;
import com.example.a29149.yuyuan.AbstractObject.AbstractActivity;
import com.google.gson.Gson;
import org.json.JSONObject;
/**
* 修改个人悬赏信息
* Created by GR on 2017/5/26.
*/
public class RewardModifyActivity extends AbstractActivity implements View.OnClickListener {
private static final String TAG = "RewardModifyActivity";
private RewardDTO mRewardDTO;//悬赏信息
// private String topic; //悬赏标题
// private String description; //悬赏描述
// private String technicTagEnum; // 悬赏的领域
// private String price; // 悬赏的价格
// private String courseTimeDayEnum; // 悬赏需要的上课时间
// private String studentBaseEnum; //学生基础
// private String teachMethodEnum; //授课方法
// private String teacherRequirementEnum; //对老师的要求
// private String rewardId; // 悬赏的id
private RewardDTO rewardDTO; // 悬赏的DTO
// private int position; // listView里的位置
// 0-topic
// 1-technicTag
// 2-description
// 3-price
// 4-上课时间
// 5-学生基础
// 6-上课方式
// 7-老师类型
private String[] rewardChooseContent = GlobalUtil.getInstance().getRewardChooseContent();
//悬赏标题
@ViewInject(R.id.et_topic)
private EditText mTopic;
//详情
@ViewInject(R.id.et_description)
private EditText mDescription;
//悬赏标签
@ViewInject(R.id.tv_technicTag)
private TextView mTechnicTag;
//金额
@ViewInject(R.id.et_reward_price)
private EditText mRewardPrice;
//===上课时间====
//工作日
@ViewInject(R.id.cb_workday)
private CheckBox mWorkday;
//节假日
@ViewInject(R.id.cb_holiday)
private CheckBox mHoliday;
//不限
@ViewInject(R.id.cb_everyday)
private CheckBox mEveryday;
//====个人基础====
//小白
@ViewInject(R.id.cb_whiteman)
private CheckBox mWhiteman;
//入门
@ViewInject(R.id.cb_littleman)
private CheckBox mLittleman;
//熟练
@ViewInject(R.id.cb_muchman)
private CheckBox mMuchman;
//====教学方式====
//线上
@ViewInject(R.id.cb_onLine)
private CheckBox mOnline;
//线下
@ViewInject(R.id.cb_offLine)
private CheckBox mOffline;
//都可以
@ViewInject(R.id.cb_onAndOff)
private CheckBox mOnAndOff;
//====老师要求====
//认证的
@ViewInject(R.id.cb_onlyTeacher)
private CheckBox mOnlyTeacher;
//都可以
@ViewInject(R.id.cb_everybady)
private CheckBox mEverybody;
//返回按钮
@ViewInject(R.id.iv_return)
private ImageView mReturn;
@ViewInject(R.id.tv_go)
private TextView mSubmit;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reward_modify);
AnnotationUtil.injectViews(this);
AnnotationUtil.setClickListener(this);
rewardDTO = ( RewardDTO ) getIntent().getSerializableExtra("DTO");
mSubmit.setOnClickListener(this);
mReturn.setOnClickListener(this);
mTechnicTag.setOnClickListener(this);
mWorkday.setOnClickListener(this);
mHoliday.setOnClickListener(this);
mEveryday.setOnClickListener(this);
mWhiteman.setOnClickListener(this);
mLittleman.setOnClickListener(this);
mOnline.setOnClickListener(this);
mOffline.setOnClickListener(this);
mOnAndOff.setOnClickListener(this);
mMuchman.setOnClickListener(this);
mOnlyTeacher.setOnClickListener(this);
mEverybody.setOnClickListener(this);
initData();
}
private void initData() {
//展示
mTopic.setText(rewardDTO.getTopic());
mDescription.setText(rewardDTO.getDescription());
mTechnicTag.setText(rewardDTO.getTechnicTagEnum().toString() + "");
mRewardPrice.setText(rewardDTO.getPrice() + "");
//教学时间
// String courseTimeEnumStr = mRewardDTO.getCourseTimeDayEnum().toString();
switch (rewardDTO.getCourseTimeDayEnum()) {
case 工作日 : {
mWorkday.setChecked(true);
mHoliday.setChecked(false);
mEveryday.setChecked(false);
}
break;
case 节假日: {
mWorkday.setChecked(false);
mHoliday.setChecked(true);
mEveryday.setChecked(false);
}
break;
case 不限: {
mWorkday.setChecked(false);
mHoliday.setChecked(false);
mEveryday.setChecked(true);
}
break;
default:
break;
}
//学生基础
// StudentBaseEnum.
// String studentBaseEnumStr = mRewardDTO.getStudentBaseEnum().toString();
switch (rewardDTO.getStudentBaseEnum()) {
case 小白: {
mWhiteman.setChecked(true);
mLittleman.setChecked(false);
mMuchman.setChecked(false);
}
break;
case 入门: {
mWhiteman.setChecked(false);
mLittleman.setChecked(true);
mMuchman.setChecked(false);
}
break;
case 熟练: {
mWhiteman.setChecked(false);
mLittleman.setChecked(false);
mMuchman.setChecked(true);
}
break;
default:
break;
}
//教学方式
// String teachMethodEnumStr = mRewardDTO.getTeachMethodEnum().toString();
switch (rewardDTO.getTeachMethodEnum()) {
case 线上: {
mOnline.setChecked(true);
mOffline.setChecked(false);
mOnAndOff.setChecked(false);
}
break;
case 线下: {
mOnline.setChecked(false);
mOffline.setChecked(true);
mOnAndOff.setChecked(false);
}
break;
case 不限: {
mOnline.setChecked(false);
mOffline.setChecked(false);
mOnAndOff.setChecked(true);
}
break;
default:
break;
}
//老师要求
// String teacherRequirementEnumStr = mRewardDTO.getTeacherRequirementEnum().toString();
switch (rewardDTO.getTeacherRequirementEnum()) {
case 认证老师: {
mOnlyTeacher.setChecked(true);
mEverybody.setChecked(false);
}
break;
case 不限: {
mOnlyTeacher.setChecked(false);
mEverybody.setChecked(true);
}
break;
default:
break;
}
}
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.iv_return:
finish();
break;
case R.id.tv_go:
goNext();
break;
case R.id.tv_technicTag:
chooseTag();
break;
case R.id.cb_workday:
chooseWeekday();
break;
case R.id.cb_holiday:
chooseHoliday();
break;
case R.id.cb_everyday:
chooseEveryday();
break;
case R.id.cb_whiteman:
choosewhiteMan();
break;
case R.id.cb_littleman:
chooseLittleMan();
break;
case R.id.cb_onLine:
chooseOnLine();
break;
case R.id.cb_offLine:
chooseOffLine();
break;
case R.id.cb_onAndOff:
chooseOnAndOff();
break;
case R.id.cb_muchman:
chooseMuchMan();
break;
case R.id.cb_onlyTeacher:
chooseOnlyTeacher();
break;
case R.id.cb_everybady:
chooseEveryBady();
break;
default:
break;
}
}
private void goNext() {
//提交用户的信息
GlobalUtil.getInstance().setRewardChooseContent(rewardChooseContent);
rewardChooseContent[0] = mTopic.getText().toString();
rewardChooseContent[1] = mTechnicTag.getText().toString();
rewardChooseContent[2] = mDescription.getText().toString();
rewardChooseContent[3] = mRewardPrice.getText().toString();
//Log.i("malei",rewardChooseContent.toString());
//发布到服务器
ModifyRewardAction modifyRewardAction = new ModifyRewardAction();
modifyRewardAction.execute();
}
//弹出悬赏选择标签
private AlertDialog alertDialogChooseTag;
public void chooseTag() {
TextView customTitle = new TextView(this);
customTitle.setPadding(0, 20, 0, 0);
customTitle.setText("请选择内容标签");
customTitle.setTextColor(getResources().getColor(R.color.colorPrimary));
customTitle.setTextSize(18);
customTitle.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
customTitle.setGravity(Gravity.CENTER);
ArrayAdapter<String> teachTypeItem = new ArrayAdapter<>(this,
R.layout.dialog_team_project_item,
Const.REWARD_TAG);
alertDialogChooseTag = new AlertDialog.Builder(this)
.setCustomTitle(customTitle)
.setAdapter(teachTypeItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mTechnicTag.setText("标签:" + Const.REWARD_TAG[which]);
rewardChooseContent[1] = Const.REWARD_TAG[which];
dialog.dismiss();
}
}).create();
alertDialogChooseTag.show();
}
//选择了工作日
private void chooseWeekday() {
rewardChooseContent[4] = mWorkday.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mHoliday.setChecked(false);
mEveryday.setChecked(false);
}
//选择了休息日
private void chooseHoliday() {
rewardChooseContent[4] = mHoliday.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mWorkday.setChecked(false);
mEveryday.setChecked(false);
}
//选择了不限
private void chooseEveryday() {
rewardChooseContent[4] = mEveryday.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mWorkday.setChecked(false);
mHoliday.setChecked(false);
}
//选择了小白
private void choosewhiteMan() {
rewardChooseContent[5] = mWhiteman.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mLittleman.setChecked(false);
mMuchman.setChecked(false);
}
//选择了入门
private void chooseLittleMan() {
rewardChooseContent[5] = mLittleman.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mWhiteman.setChecked(false);
mMuchman.setChecked(false);
}
//选择了熟练
private void chooseMuchMan() {
rewardChooseContent[5] = mMuchman.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mWhiteman.setChecked(false);
mLittleman.setChecked(false);
}
//选择线上
private void chooseOnLine() {
rewardChooseContent[6] = mOnline.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mOffline.setChecked(false);
mOnAndOff.setChecked(false);
}
//选择线下
private void chooseOnAndOff() {
rewardChooseContent[6] = mOnAndOff.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mOffline.setChecked(false);
mOnline.setChecked(false);
}
//选择线下或线上
private void chooseOffLine() {
rewardChooseContent[6] = mOffline.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mOnline.setChecked(false);
mOnAndOff.setChecked(false);
}
//选择了仅老师
private void chooseOnlyTeacher() {
rewardChooseContent[7] = mOnlyTeacher.getText().toString();
//mWorkday.setTextColor(Integer.parseInt("9ccc65"));
mEverybody.setChecked(false);
}
//选择了不限
private void chooseEveryBady() {
rewardChooseContent[7] = mEverybody.getText().toString();
mOnlyTeacher.setChecked(false);
}
/**
* 发布悬赏请求Action
*/
public class ModifyRewardAction extends AsyncTask<String, Integer, String> {
private UpdateController updateController = new UpdateController();
private String[] mChooseContent;
public ModifyRewardAction() {
super();
}
/**
* 先获取需要的信息
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
mChooseContent = GlobalUtil.getInstance().getRewardChooseContent();
}
/**
* 发出更新请求
* @param params
* @return
*/
@Override
protected String doInBackground(String... params) {
//默认选择
String courseTimeDayEnumStr;
if ( mChooseContent[4] != null && !mChooseContent[4].equals(""))
;
else
mChooseContent[4] = "不限";
courseTimeDayEnumStr = mChooseContent[4];
String studentBaseEnumStr;
if ( mChooseContent[5] != null && !mChooseContent[5].equals(""))
;
else
mChooseContent[5] = "小白";
studentBaseEnumStr = mChooseContent[5];
String teachMethodEnumStr;
if ( mChooseContent[6] != null && !mChooseContent[6].equals(""))
;
else
mChooseContent[6] = "不限";
teachMethodEnumStr = mChooseContent[6];
String teachRequirementEnumStr;
if ( mChooseContent[7] != null && !mChooseContent[7].equals(""))
;
else
mChooseContent[7] = "不限";
teachRequirementEnumStr = mChooseContent[7];
return
UpdateController.execute(
rewardDTO.getId() + "",
mChooseContent[1],
mChooseContent[0],
mChooseContent[2],
mChooseContent[3],
mChooseContent[4],
mChooseContent[6],
mChooseContent[7],
mChooseContent[5]
);
}
/**
* 对更新请求的结果进行操作
* @param result
*/
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
try {
JSONObject jsonObject = new JSONObject(result);
String resultFlag = jsonObject.getString("result");
if (resultFlag.equals("success")) {
Toast.makeText(RewardModifyActivity.this, "修改成功!", Toast.LENGTH_SHORT).show();
//获取更新后的悬赏信息
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<RewardDTO>() {
}.getType();
RewardDTO rewardDTO = new Gson().fromJson(jsonObject.getString("courseStudentDTO"), type);
//更新到缓存
Intent intent = new Intent();
//把从网络获取到的rewardDTO返回到上一个DTO
Bundle bundle = new Bundle();
bundle.putSerializable("DTO", rewardDTO);
intent.putExtras(bundle);
//通知结果
setResult(RESULT_OK, intent);
finish();
//更新各个Adapter里面的数据
AdapterManager.getInstance().updateData(RewardAdapter.class, rewardDTO);
return;
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(RewardModifyActivity.this, "网络连接失败T_T", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(RewardModifyActivity.this, "网络连接失败T_T", Toast.LENGTH_SHORT).show();
}
setResult(RESULT_CANCELED);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}
|
C#
|
UTF-8
| 812
| 2.53125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Radiator.Core
{
public abstract class CommandValidator<TCommand> where TCommand : Command
{
ValidationContext<TCommand> _context = new ValidationContext<TCommand>();
public ValidationContext<TCommand> ValidationContext { get{return _context;} }
public abstract void ValidateCommand(TCommand command);
public void AddError<TError>(TError error) where TError : class
{
_context.AddError(error);
}
public void AddErrorFor<TError>(TError error, Expression<Func<TCommand, object>> expression) where TError : class
{
_context.AddErrorFor(error, expression);
}
}
}
|
C++
|
UTF-8
| 5,009
| 3.46875
| 3
|
[] |
no_license
|
#include "FileHandler.h"
#include "Customers.h"
#include "Items.h"
#include <sstream>
#include <string>
FileHandler::FileHandler() {}
FileHandler ::~FileHandler() {}
bool FileHandler::isCustomerFile() // function to check for the customer file
{
ifstream _fcount;
_fcount.open("customers.txt");
if (_fcount) // check if file can be open
{
_fcount.close();
return true;
}
else // check if file can be open
{
cout << "Customer file doesn't exist" << endl;
_fcount.close();
return false;
}
}
bool FileHandler::writeCustomersFile(vector<Customer *> customers, string customerFile) // write to customers text file
{
ofstream f;
// f.open("customers.txt");
f.open(customerFile);
for (int i = 0; i < customers.size(); i++)
{
string line = customers[i]->toText();
f << line << endl;
vector<string> items = customers[i]->getItems();
if (items.size() > 0)
{
for (int j = 0; j < items.size(); j++)
{
f << items[j] << endl;
}
}
}
f.close();
return true;
}
vector<Customer *> FileHandler::readCustomerFile(string customerFile) // function read customer file
{
string line;
vector<string> strBuff;
vector<Customer *> customers;
FileHandler FileHandler;
if (!FileHandler.isCustomerFile())
{
cout << "isCustomerFile : NO" << endl;
return customers;
}
ifstream _fcount; //input customers text file
// _fcount.open("customers.txt");
_fcount.open(customerFile);
while (_fcount)
{
getline(_fcount, line); // if file is open get and store value in line
if (line == "-1")
{
cout << "can't open file" << endl;
break; // if file is not found
}
strBuff.push_back(line);
// line = "";
}
_fcount.close();
for (int i = 0; i < strBuff.size(); i++)
{
// maybe its possible to use number of rentals in order to take the next items
if (strBuff[i][0] == 'I')
{
int cusLen = customers.size();
customers[cusLen - 1]->populateBorrowedItems(strBuff[i]);
}
if (strBuff[i][0] == 'C')
{
stringstream ss(strBuff[i]);
vector<string> customerVector;
while (ss.good())
{
string substr;
getline(ss, substr, ',');
customerVector.push_back(substr);
}
// int subStrLength = customerVector[5].length() - 1; //This handles unwanted whitespace in Type of Customer
if (customerVector[5] == "Guest")
{
Guest *guest = new Guest(customerVector[0], customerVector[1], customerVector[2], customerVector[3]);
customers.push_back(guest);
}
else if (customerVector[5] /*.substr(0, subStrLength)*/ == "Regular")
{
Regular *regular = new Regular(customerVector[0], customerVector[1], customerVector[2], customerVector[3]);
customers.push_back(regular);
}
else if (customerVector[5] == "VIP")
{
VIP *vip = new VIP(customerVector[0], customerVector[1], customerVector[2], customerVector[3]);
customers.push_back(vip);
}
else
{
cout << "No type found. Error." << endl;
}
}
}
return customers;
}
bool FileHandler::isItemFile()
{
ifstream _fcount;
_fcount.open("items.txt");
if (_fcount) // check if item text file can be open
{
_fcount.close();
return true;
}
else
{
cout << "Items file doesn't exist" << endl;
_fcount.close();
return false;
}
}
vector<Item *> FileHandler::readItemsFile(string itemFile)
{
string line;
vector<string> strBuff;
vector<Item *> items;
FileHandler fileHandler;
if (!fileHandler.isItemFile())
{
cout << "isItemFile : NO" << endl;
return items;
}
ifstream _fcount; //input customers text file
// _fcount.open("items.txt");
_fcount.open(itemFile);
while (_fcount)
{
getline(_fcount, line); // if file is open get and store value in line
if (line == "-1")
{
cout << "can't open file" << endl;
break; // if file is not found
}
strBuff.push_back(line);
line = "";
}
_fcount.close();
for (int i = 0; i < strBuff.size(); i++)
{
if (strBuff[i][0] == 'I')
{
stringstream ss(strBuff[i]);
vector<string> itemVector;
while (ss.good())
{
string substr;
getline(ss, substr, ',');
itemVector.push_back(substr);
}
string type = itemVector[2];
if (itemVector[2] == "Game")
{
VideoGames *videoGame = new VideoGames(itemVector[0], itemVector[1], itemVector[3], stoi(itemVector[4]), stof(itemVector[5]));
items.push_back(videoGame);
}
else if (itemVector[2] == "DVD")
{
DVD *dvd = new DVD(itemVector[0], itemVector[1], itemVector[3], stoi(itemVector[4]), stof(itemVector[5]), itemVector[6]);
items.push_back(dvd);
}
else if (itemVector[2] == "Record")
{
Record *record = new Record(itemVector[0], itemVector[1], itemVector[3], stoi(itemVector[4]), stof(itemVector[5]), itemVector[6]);
items.push_back(record);
}
}
}
return items;
}
bool FileHandler::writeItemsFile(vector<Item *> items, string itemFile)
{
ofstream f;
// f.open("items.txt");
f.open(itemFile);
for (int i = 0; i < items.size(); i++)
{
string line = items[i]->toText();
f << line << endl;
}
f.close();
return true;
}
|
Java
|
UTF-8
| 4,554
| 2.640625
| 3
|
[] |
no_license
|
package ciclo3.doctor.entidades;
/**
* Entidad o modelo que define la tabla Doctor y sus relaciones con las demás
* entidades o tablas de la "base de datos" para el proyecto:
* Servicios médicos especializados.
* Esta tabla relaciona los nombres de los médicos, el departamento al cual
* pertenecen y su año de graduación.
* La tabla se relaciona con una tabla de especialidades médicas, las reservas
* de citas médicas y los mensajes de calificación de las citas.
*/
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Define la entidad Doctor así como la tabla doctor en la base de datos y sus
* relaciones con las demás tablas del esquema.
* @author William David Ramírez Blauvelt
*/
@Entity
@Table(name = "doctor")
public class Doctor implements Serializable {
/**
* Campo de identificador único de registros en la tabla.
* Define el identificador único de los campos de la tabla e indica que es
* autoincremental.
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", length = 10, updatable = false)
private Integer id;
/**
* Campo para los nombres de los médicos.
*/
@Column(name = "name", length = 45, updatable = true)
private String name;
/**
* Campo para indicar el Departamento al que pertenece cada médico.
*/
@Column(name = "department", length = 45, updatable = true)
private String department;
/**
* Campo para indicar el año de graduación de cada médico.
*/
@Column(name = "year", length = 4, updatable = true)
private Integer year;
/**
* Campo para descripción del médico.
*/
@Column(name = "description", length = 250, updatable = true)
private String description;
/**
* Establece relación muchos a uno con el listado de especialidades.
* Muchos doctores pueden tener la misma especialidad.
*/
@ManyToOne
@JoinColumn(name = "specialtyId")
@JsonIgnoreProperties("doctors")
private Especialidad specialty;
/**
* Establece relación uno a muchos con el listado de mensajes.
* Un doctor puede recibir muchos mensajes.
*/
@OneToMany(cascade = {CascadeType.PERSIST}, mappedBy = "doctor")
@JsonIgnoreProperties({"doctor", "client"})
private List<Mensaje> messages;
/**
* Establece relación uno a muchos con el listado de reservas.
* Un doctor puede ser asignado a muchas reservas.
*/
@OneToMany(cascade = {CascadeType.PERSIST}, mappedBy = "doctor")
@JsonIgnoreProperties({"doctor", "client"})
private List<Reservaciones> reservations;
/**
* Gets y Sets para cada atributo de la clase
* @return: lo que corresponde, según el caso
*/
public Integer getId() {
return id;
}
/**
* Gets y Sets para cada atributo de la clase
* @return: lo que corresponde, según el caso
*/
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Especialidad getSpecialty() {
return specialty;
}
public void setSpecialty(Especialidad specialty) {
this.specialty = specialty;
}
public List<Mensaje> getMessages() {
return messages;
}
public void setMessages(List<Mensaje> messages) {
this.messages = messages;
}
public List<Reservaciones> getReservations() {
return reservations;
}
public void setReservations(List<Reservaciones> reservations) {
this.reservations = reservations;
}
}
|
Markdown
|
UTF-8
| 2,113
| 2.984375
| 3
|
[] |
no_license
|
---
title: Django September Meetup
date: 2016-09-13 19:00:00 +0100
links:
meetup: http://www.meetup.com/djangolondon/events/233252435/
skills_matter: https://skillsmatter.com/meetups/8047-london-django-september-meetup
talks:
- title: Scaling task processing with Celery
speaker: Viren Rajput
description: >
(Unfortunately this talk was postponed due to ill health.)
Earthmiles have been using Celery in their production environment for over a year
now, for performing variety of periodic and scheduled tasks. It processes 200,000
tasks per day. These include sending notifications, emails, 3rd party API calls to
complex DB operations. In this talk, Viren will tell us about the things he learned
from his experiences during the development phase.
Viren Rajput is co-founder at Earthmiles. Have been developing with Python for 6 years.
In his free time, he contributes to open source libraries in Python.
- title: Using type checking in Django projects with mypy
speaker: Daniel Moisset
description: >
Python has always been one of the most dynamic languages, and that's the most important factor in
making it as flexible and expressive as it is. However, some recent efforts being done to also bring
the world of static typing into Python, initially as a 3rd party project called mypy, and currently with
some support in the core language in the form of PEP-484. From some experiences with it, mypy improved
Daniel's Python code, but its main blocker now is supporting the libraries and frameworks we all use.
He is currently working on bringing support for Django to be able to have type annotations in web development
projects. This talk will describe the status of this work, what could be improved, and how it can already
make your web development better.
slides: https://github.com/machinalis/slides/tree/master/mypy-django
- title: Scalable end to end testing using Selenium, a cheat sheet
speaker: Prashant Tiwari
description: >
A cheat sheet of tips, tricks and limitations to functionally test Django applications with Selenium.
---
|
TypeScript
|
UTF-8
| 674
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import Graph, {Attributes} from 'graphology-types';
type SubGraphFilter<NodeAttributes extends Attributes = Attributes> = (
key: string,
attributes: NodeAttributes
) => boolean;
type SubGraphNodes<NodeAttributes extends Attributes = Attributes> =
| Array<string>
| Set<string>
| SubGraphFilter<NodeAttributes>;
export default function subgraph<
NodeAttributes extends Attributes = Attributes,
EdgeAttributes extends Attributes = Attributes,
GraphAttributes extends Attributes = Attributes
>(
graph: Graph<NodeAttributes, EdgeAttributes, GraphAttributes>,
nodes: SubGraphNodes<NodeAttributes>
): Graph<NodeAttributes, EdgeAttributes, GraphAttributes>;
|
Java
|
UTF-8
| 2,251
| 1.976563
| 2
|
[] |
no_license
|
package bean;
public class CheckListBean {
private int RNUM;
private String CHECKLIST_ID;
private String CHECKLIST_DISCRIPTION;
private String AUDIT_KIND_ID;
private int CHECKLIST_FULLSCORE;
private String CHECKLIST_VALID;
private int AUDIT_SCORE;
private String AUDIT_ID;
public CheckListBean() {
super();
}
public CheckListBean(int rNUM, String cHECKLIST_ID, String cHECKLIST_DISCRIPTION, String aUDIT_KIND_ID,
int cHECKLIST_FULLSCORE, String cHECKLIST_VALID) {
super();
RNUM = rNUM;
CHECKLIST_ID = cHECKLIST_ID;
CHECKLIST_DISCRIPTION = cHECKLIST_DISCRIPTION;
AUDIT_KIND_ID = aUDIT_KIND_ID;
CHECKLIST_FULLSCORE = cHECKLIST_FULLSCORE;
CHECKLIST_VALID = cHECKLIST_VALID;
}
public CheckListBean(int rNUM, String cHECKLIST_DISCRIPTION, int cHECKLIST_FULLSCORE) {
super();
RNUM = rNUM;
CHECKLIST_DISCRIPTION = cHECKLIST_DISCRIPTION;
CHECKLIST_FULLSCORE = cHECKLIST_FULLSCORE;
}
public String getAUDIT_ID() {
return AUDIT_ID;
}
public void setAUDIT_ID(String aUDIT_ID) {
AUDIT_ID = aUDIT_ID;
}
public int getAUDIT_SCORE() {
return AUDIT_SCORE;
}
public void setAUDIT_SCORE(int aUDIT_SCORE) {
AUDIT_SCORE = aUDIT_SCORE;
}
public int getRNUM() {
return RNUM;
}
public void setRNUM(int rNUM) {
RNUM = rNUM;
}
public String getCHECKLIST_ID() {
return CHECKLIST_ID;
}
public void setCHECKLIST_ID(String cHECKLIST_ID) {
CHECKLIST_ID = cHECKLIST_ID;
}
public String getCHECKLIST_DISCRIPTION() {
return CHECKLIST_DISCRIPTION;
}
public void setCHECKLIST_DISCRIPTION(String cHECKLIST_DISCRIPTION) {
CHECKLIST_DISCRIPTION = cHECKLIST_DISCRIPTION;
}
public String getAUDIT_KIND_ID() {
return AUDIT_KIND_ID;
}
public void setAUDIT_KIND_ID(String aUDIT_KIND_ID) {
AUDIT_KIND_ID = aUDIT_KIND_ID;
}
public int getCHECKLIST_FULLSCORE() {
return CHECKLIST_FULLSCORE;
}
public void setCHECKLIST_FULLSCORE(int cHECKLIST_FULLSCORE) {
CHECKLIST_FULLSCORE = cHECKLIST_FULLSCORE;
}
public String getCHECKLIST_VALID() {
return CHECKLIST_VALID;
}
public void setCHECKLIST_VALID(String cHECKLIST_VALID) {
CHECKLIST_VALID = cHECKLIST_VALID;
}
}
|
JavaScript
|
UTF-8
| 2,103
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
import isLiteralOrUndefined from "./ast/is-literal-or-undefined";
import addStaticHoist from "./hoist-statics";
// Extracts attributes into the appropriate
// attribute array. Static attributes and the key
// are placed into static attributes, and expressions
// are placed into the variadic attributes.
export default function extractOpenArguments(t, path, plugin) {
const attributes = path.get("attributes");
const { scope } = path;
const { hoist } = plugin.opts;
let attrs = [];
let staticAttrs = [];
let key = null;
let keyIndex = -1;
let statics = t.arrayExpression(staticAttrs);
attributes.forEach((attribute) => {
if (attribute.isJSXSpreadAttribute()) {
attrs.push({
name: null,
value: attribute.get("argument").node,
isSpread: true
});
return;
}
const name = t.stringLiteral(attribute.node.name.name);
let value = attribute.get("value");
let node = value.node;
// Attributes without a value are interpreted as `true`.
if (!node) {
value.replaceWith(t.jSXExpressionContainer(t.booleanLiteral(true)));
}
// Get the value inside the expression.
if (value.isJSXExpressionContainer()) {
value = value.get("expression");
node = value.node;
}
let literal = isLiteralOrUndefined(value);
// The key attribute must be passed to the `elementOpen` call.
if (name.value === "key") {
key = node;
// If it's not a literal key, we must assign it in the statics array.
if (hoist && !literal) {
value.replaceWith(t.stringLiteral(""));
node = value.node;
keyIndex = staticAttrs.length + 1;
}
literal = true;
}
if (literal) {
staticAttrs.push(name, node);
} else {
attrs.push({
name,
value: node,
isSpread: false
});
}
});
if (attrs.length === 0) { attrs = null; }
if (staticAttrs.length === 0) {
statics = null;
} else if (hoist) {
statics = addStaticHoist(t, scope, plugin, statics, key, keyIndex);
}
return { key, statics, attrs };
}
|
Java
|
UTF-8
| 433
| 1.929688
| 2
|
[] |
no_license
|
package com.tomyang.domain;
import lombok.Data;
import javax.persistence.Entity;
/**
* Msg
* @author yc
* @date 2018/1/16
*/
@Data
public class Msg {
private String title;
private String content;
private String etraInfo;
public Msg() {
}
public Msg(String title, String content, String etraInfo) {
this.title = title;
this.content = content;
this.etraInfo = etraInfo;
}
}
|
PHP
|
UTF-8
| 625
| 2.59375
| 3
|
[] |
no_license
|
<?php
include("jp_library/jp_lib.php");
$filename = readfile("filename.csv");
$ext=substr($filename,strrpos($filename,"."),(strlen($filename)-strrpos($filename,".")));
//we check,file must be have csv extention
if($ext=="csv"){
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$sql = "INSERT into veeds_dictionary(word) values('$emapData[0]')";
mysqli_query($sql);
}
fclose($file);
echo "CSV File has been successfully Imported.";
}else{
echo "Error: Please Upload only CSV File";
}
?>
|
Java
|
UTF-8
| 460
| 1.9375
| 2
|
[] |
no_license
|
package com.lc.belajar.retrofit.services.service;
import com.lc.belajar.retrofit.entity.ResponseSerializer;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable;
/**
* Created by eby on 07/09/16.
*/
public interface DataService {
@GET("api/tagihan-pln?idp=&thn=&bln=")
Observable<ResponseSerializer> getData(@Query("idp") String idpel, @Query("thn") String tahun, @Query("bln") String bulan);
}
|
C++
|
UTF-8
| 419
| 2.515625
| 3
|
[] |
no_license
|
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include "object.h"
#include "vector.h"
class Object;
class Ray;
class Material;
class Triangle : public Object {
Vector p1,p2,p3;
public:
Triangle(const Material& pmat, const Vector& pp1,
const Vector& pp2, const Vector& pp3);
Object* checkIntersection(Ray& r);
Vector getIntersectionPoint(Ray& r);
Vector getNormalAtPoint(Vector& p);
};
#endif //TRIANGLE_H
|
Python
|
UTF-8
| 795
| 3.375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Created by Ross on 19-1-25
def fist_1(n: int):
position = 0
while n > 0:
if n & 1:
return position
n >>= 1
position += 1
return -1
def is_bit(n: int, index: int):
n >>= index
return n & 1
def solve(array: list):
if not array:
return None
total_dif = 0
for i in array:
total_dif ^= i
pos_1 = fist_1(total_dif)
num1 = 0
num2 = 0
for i in array:
if is_bit(i, pos_1):
num1 ^= i
else:
num2 ^= i
return num1, num2
if __name__ == '__main__':
print(solve([2, 4, 3, 6, 3, 2, 5, 5]))
print(solve([4, 3, 6, 3, 5, 5]))
print(solve([4, 3, 6, 3, 5, 5]))
print(solve([3, 6]))
print(solve([]))
|
Markdown
|
UTF-8
| 29,588
| 2.859375
| 3
|
[] |
no_license
|
# soal-shift-sisop-modul-4-I05-2021
**Rafi Akbar Rafsanjani - 05111942000004**
**Agustinus Aldi Irawan Rahardja - 05111942000010**
**Muhammad Rafi Hayla Arifa - 05111942000014**
Repository for the solution to the module's question :coffee:
```
Notes:
● It is not allowed to use system () and exec * (), unless there are exceptions in the question.
● The work is only done in 1 C program file with the format name SinSeiFS_ [Group] .c.
```
**Built-in Library**
```
#define FUSE_USE_VERSION 28
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <sys/time.h>
#include <wait.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
```
**Global Initialization**
```
static const char *dirPath = "/home/alvancho/Downloads";
char *key = "SISOP";
char *atoz = "AtoZ_";
char *rx = "RX_";
char *aisa = "A_is_a_";
int x = 0;
```
# Question 1
In a department, there was a new lab admin who had nothing to do, his name was Sin.
Sin just became an admin exactly 1 month ago. After a month in that lab he finally met
great people, one of them was Sei. Sei and Sin became good friends. Because in the
past few months there was a lot of buzz about data breach, they decided to make a file
system with a robust encode method technique. The file system is as follows :
```
NOTE:
Every file on the directory must be encoded using menggunakan Atbash cipher(mirror).
For example, for a file named kucinglucu123.jpg on DATA_PENTING directory
“AtoZ_folder/DATA_PENTING/kucinglucu123.jpg” → “AtoZ_folder/WZGZ_KVMGRMT/pfxrmtofxf123.jpg”
Note:
The file system works normally like any linux file system, Mount source (root) of the file system is on /home/[USER]/Downloads directory, when naming a file, ‘/’ is ignored, and extension of a file doesn’t need to be encoded.
Reference:
https://www.dcode.fr/atbash-cipher
```
**a) If a directory starts with ```AtoZ_```, then that directory will be encoded.**
**b). If you rename a directory to have a prefix ```AtoZ_```, then the directory will be
encoded.**
**c) When encoded directory is renamed to not have encoded name, then the
directory will be decoded**
**d) For every encoding of a directory (mkdir or rename) will be recorded in a log file.
The format is : ```/home/[USER]/Downloads/[Directory Name] →
/home/[USER]/Downloads/AtoZ_[Directory Name]```**
**e) Encoding method is also applied to all other directories inside the encoded
directory.(rekursif)**
# Solution 1
Atbash Cipher is a substitution cipher named from the Hebraic alphabet that substitutes the first letter of the alphabet with the last one, the second letter with the second last one, and so on. Basically, when encoded, an ```A``` becomes a ```Z```, ```B``` turns into ```Y```, etc.
Note: The file system works normally like any linux file system, mount source (root) of the file system is on ```/home/[USER]/Downloads``` directory, when naming a file, ```/``` is ignored, and extension of a file doesn't need to be encoded.
For Example:
For a file named ```kucinglucu123.jpg``` on ```DATA_PENTING``` directory
```AtoZ_folder/DATA_PENTING/kucinglucu123.jpg``` → ```AtoZ_folder/WZGZ_KVMGRMT/pfxrmtofxf123.jpg```
Based on the question asked, we have to make a program where all the files in the created directory and/or renamed with the prefix ```AtoZ_```, then the directory and the entire contents of the directory will be encoded. If a directory is created and/or renamed with a prefix other than ```AtoZ_```, the directory and the entire contents of that directory will be decoded. If an encrypted directory is renamed to be unencoded, the contents of that directory will be decoded.
Based on this explanation. Then we can create some support functions to help us determine whether the directory is an encoded or decoded directory. These are the following support functions that we used:
**1) ```split_file_id_return```**
<img width="1000" alt="Screen Shot 2021-06-13 at 00 32 37" src="https://user-images.githubusercontent.com/74056954/121784571-dc0dc400-cbde-11eb-8fef-f4d13d20cdc2.png">
This ```split_file_id_return``` function is to return the index file extension to the file that has been split.
**2) ```file_extension_index_return```**
<img width="1000" alt="Screen Shot 2021-06-13 at 00 36 41" src="https://user-images.githubusercontent.com/74056954/121784675-6d7d3600-cbdf-11eb-8736-318412b4122e.png">
This ```file_extension_index_return``` function is to return the index file extension.
**3) ```slash_id_return```**
<img width="1000" alt="Screen Shot 2021-06-13 at 00 21 18" src="https://user-images.githubusercontent.com/74056954/121784339-b3d19580-cbdd-11eb-84ed-8b6b8ba226c4.png">
Last but not least is the ```slash_id_return``` function. The purpose of this function is to check whether the directory prefix contains ```AtoZ_``` or not. Because as we all know, directory names start after a slash. So by creating this function, we can start checking the prefix of the directory.
To perform the encryption and decryption process using the Atbash Cipher method we also need these 2 functions:
**1) ```encrypt_atbash_cipher_on_atoz```**
<img width="1000" alt="Screen Shot 2021-06-13 at 01 02 07" src="https://user-images.githubusercontent.com/74056954/121785259-fb0e5500-cbe2-11eb-9ff7-1c34b40572b5.png">
**2) ```decrypt_atbash_cipher_on_not_atoz```**
<img width="1000" alt="Screen Shot 2021-06-13 at 01 10 34" src="https://user-images.githubusercontent.com/74056954/121785482-29406480-cbe4-11eb-85d1-4bd5cfce43e0.png">
**Screenshots**
**a.)**


**b.)**



**c.)**


**d.)**

**e.)**

# Question 2
Other than that, Sei proposed to create additional encryption methods to increase the
security of their computer data . The following is the additional encryption method
designed by Sei
a. If a directory is created starting with “RX_[Nama]”, then that directory and its
contents will be encoded with a rename according to problem 1 with an additional
ROT13 algorithm (Atbash + ROT13).
b. If a directory is renamed starting with “RX_[Nama]”, then that directory and its
contents will be encoded with a rename according to problem 1 with an additional
Vigenere Cipher algorithm with “SISOP” as it's key (Case-sensitive, Atbash +
Vigenere).
c. If an encoded directory is renamed (Removing the “RX_”), then that folder will
become unencoded and it's directory contents will be decoded based on it's real
name.
d. Every encoded directory created (mkdir or rename) will be noted to a log file with
it's methods (whether it's mkdir or rename).
e. For this encryption method, files in the original directory will be split into smaller,
1024 byte files. While if accessed via the file system designed by Sin and Sei,
files will become normal. Example, Suatu_File.txt sized 3 kiloBytes in its original
directory will become 3 smaller files::
Suatu_File.txt.0000
Suatu_File.txt.0001
Suatu_File.txt.0002
When accessed via the file system, file will appear as Suatu_File.txt
** **
**Screenshots**
**a.)**


**b.)**


**c.)**



**d.)**

**e.)**

#Solution 2
**The ```RENAME``` utility checks whether the directory is renamed by adding ```RX_``` or removing ```RX_``` with the strstr() function.**
```
static int xmp_rename(const char *from, const char *to)
{
int res;
char frompath[1000], topath[1000];
char *a = strstr(to, atoz);
if (a != NULL) decrypt_atbash_cipher_on_not_atoz(a);
char *b = strstr(from, rx);
if (b != NULL){
//struct stat stats;
//stat(from, &stats);
//if(ctime(&stats.st_ctime) == ctime(&stats.st_mtime))
decrypt_rot13_on_not_rx(b);
decrypt_atbash_cipher_on_not_atoz(b);
//else
//decrypt_vigenere_on_not_rx_rename(b);
}
char *c = strstr(to, rx);
if (c != NULL){
//struct stat stats;
//stat(from, &stats);
//if(ctime(&stats.st_ctime) == ctime(&stats.st_mtime))
decrypt_rot13_on_not_rx(c);
decrypt_atbash_cipher_on_not_atoz(c);
//else
//decrypt_vigenere_on_not_rx_rename(c);
}
sprintf(frompath, "%s%s", directoryPath, from);
sprintf(topath, "%s%s", directoryPath, to);
res = rename(frompath, topath);
if (res == -1) return -errno;
writeLog2("RENAME", frompath, topath);
if (c != NULL){
encryption_utility_function(topath);
writeLog2("ENCRYPT2", from, to);
}
if (b != NULL && c == NULL){
decryption_utility_function(topath);
writeLog2("DECRYPT2", from, to);
}
if (strstr(to, aisa) != NULL){
encrypt_binary_from_difference(topath);
writeLog2("ENCRYPT3", from, to);
}
if (strstr(from, aisa) != NULL && strstr(to, aisa) == NULL){
decrypt_binary_to_normal_from_difference(topath);
writeLog2("DECRYPT3", from, to);
}
return 0;
}
```
**If ```RX_``` is detected in the destination path, it means the directory is renamed by adding ```RX_``` and followed by cracking the file in the encryption function2.**
```
void encryption_utility_function(char *fpath)
{
chdir(fpath);
DIR *dp;
struct dirent *dir;
dp = opendir(".");
if(dp == NULL) return;
struct stat lol;
char directoryPath[1000];
char filePath[1000];
while ((dir = readdir(dp)) != NULL){
printf("dirname %s\n", dir->d_name);
printf("%s/%s\n", fpath, dir->d_name);
if (stat(dir->d_name, &lol) < 0);
else if (S_ISDIR(lol.st_mode)){
if (strcmp(dir->d_name,".") == 0 || strcmp(dir->d_name,"..") == 0){
continue;
}
sprintf(directoryPath,"%s/%s",fpath, dir->d_name);
encryption_utility_function(directoryPath);
printf("directoryPath %s\n", directoryPath);
}
else{
sprintf(filePath,"%s/%s",fpath,dir->d_name);
FILE *input = fopen(filePath, "r");
if (input == NULL){
return;
}
int bytes_read, count = 0;
void *buffer = malloc(1024);
while((bytes_read = fread(buffer, 1, 1024, input)) > 0){
char newFilePath[1000];
sprintf(newFilePath, "%s.%04d", filePath, count);
count++;
FILE *output = fopen(newFilePath, "w+");
if(output == NULL) return;
fwrite(buffer, 1, bytes_read, output);
fclose(output);
memset(buffer, 0, 1024);
}
fclose(input);
printf("filepath %s\n", filePath);
remove(filePath);
}
}
closedir(dp);
}
```
**If ```RX_``` is detected in the origin path and no ```RX_``` is detected in the destination path, it means that the directory is renamed by removing ```RX_``` and continued by merging files in the decryption function2.**
```
void decryption_utility_function(char *dir)
{
chdir(dir);
DIR *dp;
struct dirent *de;
struct stat lol;
dp = opendir(".");
if (dp == NULL) return;
char directoryPath[1000];
char filePath[1000];
while ((de = readdir(dp)) != NULL){
if (stat(de->d_name, &lol) < 0);
else if (S_ISDIR(lol.st_mode)){
if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0){
continue;
}
sprintf(directoryPath, "%s/%s", dir, de->d_name);
decryption_utility_function(directoryPath);
}
else{
sprintf(filePath, "%s/%s", dir, de->d_name);
filePath[strlen(filePath) - 5] = '\0';
FILE *check = fopen(filePath, "r");
if (check != NULL){
return;
}
FILE *file = fopen(filePath, "w");
int count = 0;
char topath[1000];
sprintf(topath, "%s.%04d", filePath, count);
void *buffer = malloc(1024);
while (1){
FILE *op = fopen(topath, "rb");
if (op == NULL){
break;
}
size_t readSize = fread(buffer, 1, 1024, op);
fwrite(buffer, 1, readSize, file);
fclose(op);
remove(topath);
count++;
sprintf(topath, "%s.%04d", filePath, count);
}
free(buffer);
fclose(file);
}
}
closedir(dp);
}
```
**To perform encryption and decryption using the ROT13 cipher, a separate function will be created.**
```
void encrypt_rot13_on_rx(char *path)
{
if (!strcmp(path, ".") || !strcmp(path, "..")){
return;
}
printf("encrypt path ROT13: %s\n", path);
int edge_of_id = split_file_id_return(path);
int starting_point_of_id = slash_id_return(path, 0);
for (int i = starting_point_of_id; i < edge_of_id; i++){
if (path[i] != '/' && isalpha(path[i])){
char temporary = path[i];
if(isupper(path[i])) temporary -= 'A';
else temporary -= 'a';
temporary = (temporary + 13) % 26; //ROT13 cipher
if(isupper(path[i])) temporary += 'A';
else temporary += 'a';
path[i] = temporary;
}
}
}
void decrypt_rot13_on_not_rx(char *path)
{
if (!strcmp(path, ".") || !strcmp(path, "..")){
return;
}
printf("decrypt path ROT13: %s\n", path);
int edge_of_id = split_file_id_return(path);
int starting_point_of_id = slash_id_return(path, edge_of_id);
for (int i = starting_point_of_id; i < edge_of_id; i++){
if (path[i] != '/' && isalpha(path[i])){
char temporary = path[i];
if(isupper(path[i])) temporary -= 'A';
else temporary -= 'a';
temporary = (temporary + 13) % 26; //ROT13 cipher
if(isupper(path[i])) temporary += 'A';
else temporary += 'a';
path[i] = temporary;
}
}
}
```
The decryption function calls are performed on each utility function getattr, mkdir, rename, rmdir, create, and other functions that we think are essential in the FUSE synchronization process and mount folders. The decryption and encryption functions are carried out in the readdir utility function because FUSE will decrypt the mount folder and then encrypt it in FUSE during readdir. The call is done by checking whether the string RX_ is in the string path in each utility function by using the strstr() function. If yes, then the encryption and decryption functions will be called for that string with RX_ as the starting point of the passed string. Logging will be explained in question number 4.
# Question 3
Because Sin still feels exceptionally empty, he finally adds another feature to their file system.
a. If a directory is created with the prefix ```A_is_a_```, it will become a special directory.
b. If a directory is renamed with the prefix ```A_is_a_```, it will become a special directory.
c. If the encrypted directory is renamed by deleting ```A_is_a_``` at the beginning of the folder name, that directory becomes a normal directory.
d. Special directories are directories that return encryption/encoding to the ```AtoZ_``` or ```RX_``` directories but their respective rules still run in the directory within them
(```AtoZ_``` and ```RX_``` recursive properties still run in subdirectories).
e. In the special directory, all filenames (excluding extensions) in the fuse will be changed to lowercase (insensitive) and will be given a new extension in the form
of a decimal value from the binary value that comes from the difference in character between filenames.
For example, if in the original directory the filename is ```FiLe_CoNtoH.txt``` then in the fuse it will be ```file_contoh.txt.1321```. 1321 comes from binary 10100101001.
# Solution 3
**In the ```RENAME``` utility functions, it is checked whether the directory is renamed by adding ```A_is_a_``` or removing ```A_is_a_``` with the strstr() function.**
```
static int xmp_rename(const char *from, const char *to)
{
int res;
char frompath[1000], topath[1000];
...
sprintf(frompath, "%s%s", directoryPath, from);
sprintf(topath, "%s%s", directoryPath, to);
res = rename(frompath, topath);
if (res == -1) return -errno;
writeLog2("RENAME", frompath, topath);
...
if (strstr(to, aisa) != NULL){
encrypt_binary_from_difference(topath);
writeLog2("ENCRYPT3", from, to);
}
if (strstr(from, aisa) != NULL && strstr(to, aisa) == NULL){
decrypt_binary_to_normal_from_difference(topath);
writeLog2("DECRYPT3", from, to);
}
return 0;
}
```
**If A_is_a_ is detected in the destination path, it means the directory was renamed by adding A_is_a_. Then proceed with changing the file name to lowercase and adding the decimal value as a new extension to the encryptBinary function.**
```
void get_binary_from_difference(char *fname, char *bin, char *lowercase){
int edge_of_id = file_extension_index_return(fname);
int starting_point_of_id = slash_id_return(fname, 0);
int i;
for(i=starting_point_of_id; i<edge_of_id; i++){
if(isupper(fname[i])){
bin[i] = '1';
lowercase[i] = fname[i] + 32;
}
else{
bin[i] = '0';
lowercase[i] = fname[i];
}
}
bin[edge_of_id] = '\0';
for(; i<strlen(fname); i++){
lowercase[i] = fname[i];
}
lowercase[i] = '\0';
}
```
```
int binary_to_decimal_converter(char *bin){
int temporary = 1, res = 0;
for(int i=strlen(bin)-1; i>=0; i--){
if(bin[i] == '1') res += temporary;
temporary *= 2;
}
return res;
}
```
```
void encrypt_binary_from_difference(char *fpath)
{
chdir(fpath);
DIR *dp;
struct dirent *dir;
struct stat lol;
dp = opendir(".");
if(dp == NULL) return;
char directoryPath[1000];
char filePath[1000];
char filePathBinary[1000];
while ((dir = readdir(dp)) != NULL){
if (stat(dir->d_name, &lol) < 0);
else if (S_ISDIR(lol.st_mode)){
if (strcmp(dir->d_name,".") == 0 || strcmp(dir->d_name,"..") == 0){
continue;
}
sprintf(directoryPath,"%s/%s",fpath, dir->d_name);
encrypt_binary_from_difference(directoryPath);
}
else{
sprintf(filePath,"%s/%s",fpath, dir->d_name);
char bin[1000], lowercase[1000];
get_binary_from_difference(dir->d_name, bin, lowercase);
int dec = binary_to_decimal_converter(bin);
sprintf(filePathBinary,"%s/%s.%d",fpath,lowercase,dec);
rename(filePath, filePathBinary);
}
}
closedir(dp);
}
```
**If ```A_is_a_ is``` detected in the origin path and ```A_is_a_``` is not detected in the destination path, it means that the directory is renamed by removing ```A_is_a_```. Then proceed with changing the file name to the original with the help of the decimal value in the decryptBinary function.**
```
int convert_decimal(char *ext){
int dec = 0, multiplier = 1;
for(int i=strlen(ext)-1; i>=0; i--){
dec += (ext[i]-'0')*multiplier;
multiplier *= 10;
}
return dec;
}
```
```
void decimal_to_binary_converter(int dec, char *bin, int len){
int idx = 0;
while(dec){
if(dec & 1){
bin[idx] = '1';
}
else{
bin[idx] = '0';
}
idx++;
dec /= 2;
}
while(idx < len){
bin[idx] = '0';
idx++;
}
bin[idx] = '\0';
for(int i=0; i<idx/2; i++){
char temporary = bin[i];
bin[i] = bin[idx-1-i];
bin[idx-1-i] = temporary;
}
}
```
```
void get_decimal(char *fname, char *bin, char *normalcase){
int edge_of_id = file_extension_index_return(fname);
int starting_point_of_id = slash_id_return(fname, 0);
int i;
for(i=starting_point_of_id; i<edge_of_id; i++){
if(bin[i-starting_point_of_id] == '1') normalcase[i-starting_point_of_id] = fname[i] - 32;
else normalcase[i-starting_point_of_id] = fname[i];
}
for(; i<strlen(fname); i++){
normalcase[i-starting_point_of_id] = fname[i];
}
normalcase[i-starting_point_of_id] = '\0';
}
```
```
void decrypt_binary_to_normal_from_difference(char *fpath)
{
chdir(fpath);
DIR *dp;
struct dirent *dir;
struct stat lol;
dp = opendir(".");
if(dp == NULL){
return;
}
char directoryPath[1000];
char filePath[1000];
char filePathDecimal[1000];
while ((dir = readdir(dp)) != NULL){
if (stat(dir->d_name, &lol) < 0);
else if (S_ISDIR(lol.st_mode)){
if (strcmp(dir->d_name,".") == 0 || strcmp(dir->d_name,"..") == 0){
continue;
}
sprintf(directoryPath,"%s/%s",fpath, dir->d_name);
decrypt_binary_to_normal_from_difference(directoryPath);
}
else{
sprintf(filePath,"%s/%s",fpath, dir->d_name);
char fname[1000], bin[1000], normalcase[1000], clearPath[1000];
strcpy(fname, dir->d_name);
char *ext = strrchr(fname, '.');
int dec = convert_decimal(ext+1);
for(int i=0; i<strlen(fname)-strlen(ext); i++){
clearPath[i] = fname[i];
}
char *ext2 = strrchr(clearPath, '.');
decimal_to_binary_converter(dec, bin, strlen(clearPath)-strlen(ext2));
get_decimal(clearPath, bin, normalcase);
sprintf(filePathDecimal,"%s/%s",fpath,normalcase);
rename(filePath, filePathDecimal);
}
}
closedir(dp);
}
```
**Problems**
```
A bit confused by the meaning of the special directory.
A little confused when decrypting because you need to take the decimal value that is at the end of the file name.
Binary uses the array of char data type because of the fear of integer overflow.
This causes the conversion of binary to decimal and vice versa a bit of a problem.
```
**Screenshots**
**a.)**


**b.)**


**c.)**

**d.)**




**e.)**

# Question 4
To make it easier to monitor activities on their filesystem, Sin and Sei created a log system with the following specifications.
a. The system log that will be created is named ```SinSeiFS.log``` in the user's home directory (/home/[user]/SinSeiFS.log).
This system log maintains a list of system call commands that have been executed on the filesystem..
b. Because Sin and Sei like tidiness, the logs that are made will be divided into two levels,INFO and WARNING.
c. For the WARNING level log, it is used to log the rmdir and unlink syscalls.
d. The rest will be recorded at the INFO level.
e. The format for logging is:
```
[Level]::[dd][mm][yyyy]-[HH]:[MM]:[SS]:[CMD]::[DESC :: DESC]
Level : Level logging, dd : 2 digit date, mm : 2 digit month, yyyy : 4 digit year, HH
: 2 digit hour (24 Hour format),MM : 2 digit minute, SS : 2 digit second, CMD :
Called System Call, DESC : additional information and parameters
INFO::28052021-10:00:00:CREATE::/test.txt
INFO::28052021-10:01:00:RENAME::/test.txt::/rename.txt
```
# Solution 4
**For this matter we are asked to create a system log which aims to make it easier to monitor activities on the file system. Here we create two functions in making this system log, namely the ```writeLog``` and ```writeLog2``` functions, the difference is in the DESC (additional information and parameters) that need to be included in the format for logging. In writing the system log according to the existing format we need to find the current time to be included in the system log later. In the ```writeLog``` function we also enter the parameter ```char *name``` which is the System Call and char ```*fpath``` is a description of the existing file.**
```
void writeLog(char *name, char *fpath)
{
time_t originaltime;
struct tm *timeinfo;
time(&originaltime);
timeinfo = localtime(&originaltime);
```
**Next we initialize an array of char or string ```systemCallKeep``` to later save the system call commands that have been executed on the filesystem and record them in the ```SinSeiFS.log``` file. Then we need to open the ```SinSeiFS.log``` file in the user's home directory with mode ```a``` (append) so that a new log can be written later and if the file does not exist, a new file will be created.**
```
char systemCallKeep[1000];
FILE *file;
file = fopen("/home/alvancho/SinSeiFS.log", "a");
```
**Next we can check the syscall in the parameter. If the syscall is ```RMDIR``` or ```UNLINK``` then the log level will be logged ```WARNING```. But if not, then the log level will be recorded ```INFO```. And will also note the current time along with other information.**
```
if (strcmp(name, "RMDIR") == 0 || strcmp(name, "UNLINK") == 0){
sprintf(systemCallKeep, "WARNING::%.2d%.2d%d-%.2d:%.2d:%.2d::%s::%s\n", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, name, fpath);
}
else{
sprintf(systemCallKeep, "INFO::%.2d%.2d%d-%.2d:%.2d:%.2d::%s::%s\n", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, name, fpath);
}
```
**The last step is to write down the existing logs into the ```SinSeiFS.log``` file and close the file.**
```
fputs(systemCallKeep, file);
fclose(file);
return;
}
```
**For the second function, ```writeLog2``` is actually more or less the same as the ```writeLog``` function described earlier, but there are differences in the parameters given and in the recording. For the parameters there is a ```char *name``` which is a syscall, ```const char *from``` is a file description before the system call command is executed by the file system and a ```const char *to``` file description after the system call command is executed by the file system. Then the recording is more or less the same as the previous one but added information according to the parameters given.**
```
void writeLog2(char *name, const char *from, const char *to)
{
time_t originaltime;
struct tm *timeinfo;
time(&originaltime);
timeinfo = localtime(&originaltime);
char systemCallKeep[1000];
FILE *file;
file = fopen("/home/alvancho/SinSeiFS.log", "a");
if (strcmp(name, "RMDIR") == 0 || strcmp(name, "UNLINK") == 0){
sprintf(systemCallKeep, "WARNING::%.2d%.2d%d-%.2d:%.2d:%.2d::%s::%s::%s\n", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, name, from, to);
}
else{
sprintf(systemCallKeep, "INFO::%.2d%.2d%d-%.2d:%.2d:%.2d::%s::%s::%s\n", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, name, from, to);
}
fputs(systemCallKeep, file);
fclose(file);
return;
}
```
**Problems**
```
There was a problem when recording the file because it was different from the given format.
There is difficulty in taking real time and keeping track of it.
Was confused to record the System Call because some have 1 or 2 arguments. Finally we split it into 2 functions for logging.
```
**Screenshots**
**a.), b.), c.), d.), e.)**

|
C#
|
UTF-8
| 3,348
| 3
| 3
|
[] |
no_license
|
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using MonoGameRPG.Gameplay;
#endregion
namespace MonoGameRPG.Physics
{
/// <summary>
/// An axis-aligned bounding box for determining collisions between objects.
/// </summary>
public class BoundingBoxAA : BoundingShape
{
#region Fields
// Minimum and maximum bounds of the bounding box
private Vector2 min, max;
#endregion
#region Properties
/// <summary>
/// Gets the minimum bounds of the bounding box.
/// </summary>
public Vector2 Min
{
get { return min; }
}
/// <summary>
/// Gets the maximum bounds of the bounding box.
/// </summary>
public Vector2 Max
{
get { return max; }
}
#endregion
#region Constructors
/// <summary>
/// Creates a new axis-aligned bounding box from minimum and maximum bounds.
/// </summary>
/// <param name="min">Minimum bounds.</param>
/// <param name="max">Maximum bounds.</param>
public BoundingBoxAA(Vector2 min, Vector2 max)
{
this.min = min;
this.max = max;
}
#endregion
#region Methods
/// <summary>
/// Checks for collisions against another bounding shape.
/// </summary>
/// <param name="shape">Shape to check against.</param>
/// <returns>True if a collision was found.</returns>
public override bool CollidesWith(BoundingShape shape)
{
if (shape is BoundingCircle)
return BoundingShape.CollisionCircleAABox(shape as BoundingCircle, this);
else if (shape is BoundingBoxAA)
return BoundingShape.CollisionAABoxAABox(shape as BoundingBoxAA, this);
throw new Exception("Unknown bounding shape.");
}
/// <summary>
/// Update logic called every game frame.
/// </summary>
/// <param name="gameTime">Snapshot of timing values.</param>
public override void Update(GameTime gameTime)
{
// Check if the bounding box should be moved with an entity
if (attachedEntity != null)
{
Vector2 minMaxVector = getMinMaxVector();
min = attachedEntity.Position + offsetVector;
max = min + minMaxVector;
}
}
/// <summary>
/// Attaches the bounding box to an entity.
/// </summary>
/// <param name="entity">Entity to attach the box to.</param>
public override void AttachToEntity(Entity entity)
{
if (entity != null)
{
offsetVector = min - entity.Position;
}
base.AttachToEntity(entity);
}
#endregion
#region Private Methods
/// <summary>
/// Gets the vector between the minimum bounds and the maximum bounds.
/// </summary>
/// <returns>2-dimensional vector describing the distance between the bounds.</returns>
private Vector2 getMinMaxVector()
{
Vector2 returnVector = max - min;
return returnVector;
}
#endregion
}
}
|
C#
|
UTF-8
| 528
| 2.515625
| 3
|
[
"Unlicense"
] |
permissive
|
namespace Playground.Blazor.Core.Utils
{
using System;
internal sealed class FunctionalDisposable : IDisposable
{
private readonly Action onDispose;
private bool objectDisposed;
public FunctionalDisposable(Action onDispose)
{
this.onDispose = onDispose;
}
public void Dispose()
{
if (!this.objectDisposed)
{
this.onDispose();
this.objectDisposed = true;
}
}
}
}
|
C#
|
UTF-8
| 931
| 3
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using PizzaSharp.Models;
namespace PizzaSharp.Interfaces
{
/// <summary>
/// Representation of allowed actions for a comment.
/// </summary>
public interface ICommentRepository
{
/// <summary>
/// Adds the given Comment to the repository.
/// </summary>
/// <param name="comment"> The comment that should be added. </param>
/// <param name="userId"> The id of the user trying to add the comment. </param>
void Add(Comment comment, Guid userId);
Comment Get(Guid commentId, Guid userId);
/// <summary>
/// Returns a list of all the comments for the given pizza.
/// </summary>
/// <param name="pizzaId">The pizza that we want to get the comments for.</param>
/// <returns>A list of all the comments.</returns>
List<Comment> GetAll(Guid pizzaId);
}
}
|
Java
|
UTF-8
| 3,569
| 2.078125
| 2
|
[] |
no_license
|
/*
* Use twitter4j Library (Apache License 2.0) from
* http://twitter4j.org/ko/
* For twitter api
*
* Main developers: 한주형, 주세현
* Debuggers: 한주형, 주세현
*/
package com.example.twiddy_ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import twitter4j.*;
import twitter4j.auth.RequestToken;
public class TwitLogin extends Activity {
RequestToken requestToken;
Twitter twitter;
Context ctx;
private boolean is_login;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.twit_login);
Intent it_login = getIntent();
is_login = it_login.getExtras().getBoolean("login");
ctx = this;
LoadWebPageASYNC twitasync = new LoadWebPageASYNC();
twitasync.execute("");
}
@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
private class LoadWebPageASYNC extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... urls){
TwitterObj tobj = new TwitterObj();
if(tobj.GetTwitter() == null){
tobj.SetTwitter();
}
twitter = tobj.GetTwitter();
try {
requestToken = twitter.getOAuthRequestToken();
final String urltoload = requestToken.getAuthenticationURL();
TwitLogin.this.runOnUiThread(new Runnable() {
public void run(){
final WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
if(is_login) {
webView.loadUrl(urltoload + "&force_login=true");
}
else {
webView.loadUrl(urltoload);
}
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:window.HTMLOUT.showHTML("
+ "document.getElementsByTagName('code')[0].innerHTML);");
}
});
}
});
} catch (TwitterException te) {
te.printStackTrace();
Log.d("HTML", "Failed to get timeline: " + te.getMessage());
System.exit(-1);
}
return null;
}
class MyJavaScriptInterface
{
@JavascriptInterface
public void showHTML(String pin) throws TwitterException
{
if(pin.length() > 0 ) {
Log.d("PIN", "pin = " + pin);
twitter.getOAuthAccessToken(requestToken, pin);
Intent it_display = new Intent(ctx, DisplayEmotion.class);
it_display.putExtra("twitter", twitter);
startActivity(it_display);
finish();
}
else {
Log.d("HTML", "No pin accept");
}
}
}
}
}
|
Java
|
UTF-8
| 4,330
| 2.484375
| 2
|
[
"CC0-1.0"
] |
permissive
|
package com.hoopawolf.vrm.potion.sin;
import net.minecraft.block.BlockState;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectType;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.tag.FluidTags;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
public class SlothTrialEffect extends StatusEffect
{
private final EntityType[] spawnList = {
EntityType.ENDERMAN
};
public SlothTrialEffect(StatusEffectType typeIn, int liquidColorIn)
{
super(typeIn, liquidColorIn);
}
@Override
public boolean canApplyUpdateEffect(int duration, int amplifier)
{
int k = 380 >> amplifier;
if (k > 0)
{
return duration % k == 0;
} else
{
return true;
}
}
@Override
public void applyUpdateEffect(LivingEntity entityLivingBaseIn, int amplifier)
{
if (!entityLivingBaseIn.world.isClient)
{
teleportRandomly(entityLivingBaseIn);
if (entityLivingBaseIn.world.random.nextInt(100) < 20)
{
int rand = entityLivingBaseIn.world.random.nextInt(1) + 1;
while (rand != 0)
{
double x = entityLivingBaseIn.getX() + (entityLivingBaseIn.world.random.nextDouble() - 0.5D) * 10.0D;
double y = entityLivingBaseIn.getY() + (double) (entityLivingBaseIn.world.random.nextInt(3) - 1);
double z = entityLivingBaseIn.getZ() + (entityLivingBaseIn.world.random.nextDouble() - 0.5D) * 10.0D;
BlockPos.Mutable blockpos$mutable = new BlockPos.Mutable(x, y, z);
while (blockpos$mutable.getY() > 0 && !entityLivingBaseIn.world.getBlockState(blockpos$mutable).getMaterial().blocksMovement())
{
blockpos$mutable.move(Direction.DOWN);
}
BlockState blockstate = entityLivingBaseIn.world.getBlockState(blockpos$mutable);
boolean flag = blockstate.getMaterial().blocksMovement();
boolean flag1 = blockstate.getFluidState().isIn(FluidTags.WATER);
if (flag && !flag1)
{
MobEntity entity = (MobEntity) spawnList[entityLivingBaseIn.world.random.nextInt(spawnList.length)].create(entityLivingBaseIn.world);
entity.refreshPositionAndAngles(blockpos$mutable.getX(), blockpos$mutable.getY() + 1, blockpos$mutable.getZ(), 0.0F, 0.0F);
entity.setTarget(entityLivingBaseIn);
entityLivingBaseIn.world.spawnEntity(entity);
--rand;
}
}
}
}
}
protected boolean teleportRandomly(LivingEntity entityLivingBaseIn)
{
if (entityLivingBaseIn.isAlive())
{
double d0 = entityLivingBaseIn.getX() + (entityLivingBaseIn.world.random.nextDouble() - 0.5D) * 10.0D;
double d1 = entityLivingBaseIn.getY() + (double) (entityLivingBaseIn.world.random.nextInt(3) - 1);
double d2 = entityLivingBaseIn.getZ() + (entityLivingBaseIn.world.random.nextDouble() - 0.5D) * 10.0D;
return this.teleportTo(entityLivingBaseIn, d0, d1, d2);
} else
{
return false;
}
}
private boolean teleportTo(LivingEntity entityLivingBaseIn, double x, double y, double z)
{
BlockPos.Mutable blockpos$mutable = new BlockPos.Mutable(x, y, z);
while (blockpos$mutable.getY() > 0 && !entityLivingBaseIn.world.getBlockState(blockpos$mutable).getMaterial().blocksMovement())
{
blockpos$mutable.move(Direction.DOWN);
}
BlockState blockstate = entityLivingBaseIn.world.getBlockState(blockpos$mutable);
boolean flag = blockstate.getMaterial().blocksMovement();
boolean flag1 = blockstate.getFluidState().isIn(FluidTags.WATER);
if (flag && !flag1)
{
return entityLivingBaseIn.teleport(x, y, z, true);
} else
{
return false;
}
}
}
|
Python
|
UTF-8
| 3,578
| 2.578125
| 3
|
[] |
no_license
|
from config import config
from util import format_seconds
from usagelog import logged_command
from database import Base, dbsession
import math
from datetime import datetime
from sqlalchemy import Column, Integer, BigInteger, String, DateTime
from telegram.ext import CommandHandler
BLSTATUS_ACTIVE = 0
BLSTATUS_DELETED = 1
class UserBlacklist(Base):
__tablename__ = 'blacklistuser'
id = Column(Integer, primary_key=True)
tg_user_id = Column(BigInteger, nullable=False)
status = Column(Integer, default=BLSTATUS_ACTIVE)
tag = Column(String(128), nullable=False)
added = Column(DateTime, default=None, nullable=False)
deleted = Column(DateTime, default=None, nullable=True)
def __init__(self, tg_user, tag):
self.tg_user_id = tg_user.id
self.tag = tag
self.status = BLSTATUS_ACTIVE
self.added = datetime.now()
self.deleted = None
def delete(self):
if self.status != BLSTATUS_DELETED:
self.status = BLSTATUS_DELETED
self.deleted = datetime.now()
@staticmethod
def get_user_blacklist(tg_user):
tags = []
session = dbsession()
# Query
bls = session.query(UserBlacklist)\
.filter(UserBlacklist.tg_user_id == tg_user.id)\
.filter(UserBlacklist.status == BLSTATUS_ACTIVE)\
.all()
for bl in bls:
tags.append(bl.tag)
session.close()
return tags
@logged_command('getbl')
def command_getbl(bot, update, args):
tags = UserBlacklist.get_user_blacklist(update.message.from_user)
if len(tags) > 0:
update.message.reply_text('Your blacklisted tags: {}'.format(
', '.join(tags)
))
else:
update.message.reply_text('You have no blacklisted tags.')
@logged_command('delbl')
def command_delbl(bot, update, args):
if len(args) == 0:
update.message.reply_text('Format: /deleteblacklist <tag>')
return
tag = args[0]
session = dbsession()
# Query
bls = session.query(UserBlacklist)\
.filter(UserBlacklist.tg_user_id == update.message.from_user.id)\
.filter(UserBlacklist.tag == tag)\
.filter(UserBlacklist.status == BLSTATUS_ACTIVE)\
.all()
# Delete
n = 0
for bl in bls:
bl.delete()
session.add(bl)
n += 1
session.commit()
session.close()
if n > 0:
update.message.reply_text('Deleted tag from your blacklist: ' + tag)
else:
update.message.reply_text('You have not blacklisted tag: ' + tag)
@logged_command('addbl')
def command_addbl(bot, update, args):
if len(args) == 0:
update.message.reply_text('Format: /addblacklist <tag>')
return
tag = args[0]
session = dbsession()
# Query for already-existing tag
bl = session.query(UserBlacklist)\
.filter(UserBlacklist.tg_user_id == update.message.from_user.id)\
.filter(UserBlacklist.tag == tag)\
.filter(UserBlacklist.status == BLSTATUS_ACTIVE)\
.first()
if bl:
update.message.reply_text('Tag already blacklisted for you: ' + tag)
else:
bl = UserBlacklist(update.message.from_user, tag)
session.add(bl)
session.commit()
update.message.reply_text('Added tag to your blacklist: ' + tag)
session.close()
def setup_dispatcher(dispatcher):
dispatcher.add_handler(CommandHandler('addbl', command_addbl, pass_args=True))
dispatcher.add_handler(CommandHandler('addblacklist', command_addbl, pass_args=True))
dispatcher.add_handler(CommandHandler('delbl', command_delbl, pass_args=True))
dispatcher.add_handler(CommandHandler('delblacklist', command_delbl, pass_args=True))
dispatcher.add_handler(CommandHandler('getbl', command_getbl, pass_args=True))
dispatcher.add_handler(CommandHandler('mybl', command_getbl, pass_args=True))
dispatcher.add_handler(CommandHandler('myblacklist', command_getbl, pass_args=True))
|
Python
|
UTF-8
| 6,748
| 5.09375
| 5
|
[] |
no_license
|
# Broad but simple description of data types and data structures for mandatory assignment 1
print("Hello Claus! This is my presentation on the first mandatory assignment in Python!\n-----")
# Method to explain strings
def simple_types():
print("\n-----\nSTRINGS:\n-----\n")
string1 = "Hello Claus. "
print(type(string1))
string2 = "I just concatenated two strings!"
string3 = string1 + string2 # Concatenation
print(string3)
print("Here's the length of that string: " + str(len(string3))) # Length checking
print("I can also print out part of a string - like your name: " + string1[6:11]) # String slicing
print("Or I can print the string backwards: " + string3[::-1])
print(".. How about every second letter in 'concatenated'?: " + string2[7:19:3]) # String slicing with stride
print("I can also check if something is in a string - let's check for your name: ", end='')
print("Claus" in string1) # Using the 'in' keyword (boolean return)
print("Let's check for my name: ", end='')
print("Henrik" in string1)
print("We can also play around with f-strings:")
a = 4
b = 5
print(f"{a} times {b} is 20!") # Printing f-strings (Formatted String Literal)
print("You can change strings by overwriting them (because they're mutable), but changing specific chars is hard: ")
print("\"s[3] = 'x'\" would cause an error, but \"s = s[:3] + 'x' + s[4:]\" would work:")
s = "Hello World!"
print(s)
s = s[:3] + 'x' + s[4:]
print(s)
# .count() .upper() .lower() .find() .isalnum() .isalpha() .isdigit() ???
print("\n-----\nBOOLEANS:\n-----\n")
bool1 = True
print(type(bool1))
print("Booleans return either true or false.")
print("Is 2 + 2 = 4: " + str(2 + 2 == 4))
print("Is 2 - 2 = 4: " + str(2 - 2 == 4))
print("Booleans are used to assert results in conditional statements, and execute the relevant code.")
print("\n-----\nNUMBERS:\n-----\n")
num1 = 1
print(type(num1))
print("Integers (whole numbers) are commonly used in programming.")
num2 = 4.2
print(type(num2))
print("Floating point numbers (decimal numbers) have their own data type (float).", end='')
num2 = 4.2e7
print("They can also be defined with scientific notation (4.2e7): ", end='')
print(num2)
num3 = 2+3j
print(type(num3))
print("Complex numbers (like 2+3j) are specified as (real number)+(imaginary number)")
print("\n-----\nARITHMETIC OPERATORS:\n-----\n")
a = 8
b = 5
print("Examples of the primary arithmetic operators:")
print("8 + 5 = " + str(a + b))
print("8 - 5 = " + str(a - b))
print("8 * 5 = " + str(a * b))
print("8 / 5 = " + str(a / b))
print("8 % 5 = " + str(a % b))
# Method to explain lists
def lists():
print("\n-----\nLISTS:\n-----\n")
print("Lists can contain elements of any type, and is not restricted to containing elements of a single type:")
list1 = [1, 2, "345", True, (1, 2, 3)]
print(list1)
print("Lists are ordered, and elements can therefore be accessed by their index - let's get the third element:")
print(list1[2]) # Zero-based, obviously
print("Lists can also be nested - yes, even lists in lists:")
list2 = [1, 2, 3, [4, 5, 6], 7, 8, 9]
print(list2)
print("We can also change an element in our list, because lists as a type is mutable:")
list2[2] = "Hej Claus!"
print(list2)
print(".. Or even change multiple elements in the list at once:")
list2[3][0:2] = ["Let's", "try", "this"]
print(list2)
print("Because lists are dynamic, we can also just remove elements, and the list remains:")
del list2[0]
print(list2)
list2[3:5] = []
print(list2)
# Method to explain tuples
def tuples():
print("\n-----\nTUPLES:\n-----\n")
print("Tuples are much like lists, and can contain elements of multiple types")
tuple1 = (1, 2, 3, "Hej", "med", "dig", True, None, ["Og", "en", "liste"])
print(tuple1)
print("However, a tuple can not be modified in any way - it is immutable")
print("tuple1[0] = \"Test\" would cause a TypeError")
# Method to explain sets
def sets():
print("\n-----\nSETS:\n-----\n")
print("Sets can only contain unique elements, and are unordered")
set1 = {1, 2, 3, "4", "5", "6", 6, 7, 8, 8}
print(set1)
print("The set itself is mutable, but the elements are immutable:")
set1.update([9, ("Hello", "World!")])
print(set1)
set1.add("Woohoo!")
print(set1)
print("set1.update([[1, 2]]) returns a TypeError - lists and dicts can not be added to sets are they are mutable!")
print("We can also perform certain methods on multiple sets, e.g. to see what they have in common: ")
set2 = {1, 2, 3, 10, 11, 12}
print(set1 & set2)
print(".. Or their union (all unique elements from both sets put together: ")
print(set1 | set2)
print(".. Or subtract elements from one set from another!")
print(set1 - set2)
print("Or their symmetric difference - meaning all elements that is present in only one of the sets but not both:")
print(set1 ^ set2)
# pop() remove() discard() clear()
# Frozen sets immutable (only non-modifying methods)
# Method to explain dicts
def dicts():
print("\n-----\nDICTS:\n-----\n")
# Mutable
# Dynamic
# Nested
# Dictionaries are accessed via keys, not indexing by position
print("Dictionaries is a data structure that contains key-value pairs:")
dict1 = {
1: "Hello ",
2: "World! ",
3: "This ",
4: "is ",
5: "a ",
6: "dictionary!"
}
print(dict1)
print("To access the value in a dict, you specify the key - whereas in lists you reference the position (indexing)")
print(dict1[1])
print("Dictionaries cannot return a slice value, so \"dict1[1:2]\" would return a TypeError!")
print("We can also add to our dict (e.g. \"dict1[7] = \"Test\"): ")
dict1[7] = "Test"
print(dict1)
print(dict1[7])
print("There are few restrictions on dicts - keys have to be unique (but new values can be assigned to a key):")
dict1[7] = "New value here!"
print(dict1)
print("Furthermore, a dict key has to be immutable - numbers, strings, booleans, or even tuples can be used as key")
print("Lists or another dictionary can not be used, as they are mutable")
# clear() (empties dict), get() (retrieves value for a given key), items() (returns a list of key-value pairs)
# keys() (returns a list of keys), values() (returns a list of values), pop() (removes a key and returns its value)
# Did not include special types / JSON as of yet
# Run methods
simple_types()
lists()
tuples()
sets()
dicts()
|
JavaScript
|
UTF-8
| 46
| 2.859375
| 3
|
[] |
no_license
|
var num = 4;
alert("my number is: " + num);
|
Java
|
UTF-8
| 4,571
| 2.3125
| 2
|
[] |
no_license
|
package com.yuntu.servlet;
import com.yuntu.biz.ScenicspotBiz;
import com.yuntu.pojo.Scenicspot;
import com.yuntu.util.PageUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
@WebServlet(name = "ScenServlet",value = "/ScenServlet")
public class ScenServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ScenicspotBiz biz = (ScenicspotBiz) context.getBean("ScenicspotBiz");
String type = request.getParameter("type");
if("pageUtil".equals(type)){
String strindex = request.getParameter("pageindex");
if(strindex==null){
strindex="1";
}
int pageindex = Integer.parseInt(strindex);
if (pageindex<1){
pageindex=1;
}
PageUtil<Scenicspot> pageUtil = new PageUtil<>();
pageUtil.setPageindex(pageindex);
pageUtil.setPagesize(2);
biz.getPageAll(pageUtil);
request.setAttribute("pageUtil",pageUtil);
request.getRequestDispatcher("index.jsp").forward(request,response);
}else if("add".equals(type)){
String sname = request.getParameter("sname");
String describe = request.getParameter("describe");
String city = request.getParameter("city");
Double price = Double.parseDouble(request.getParameter("price"));
Date createDate = new Date();
Scenicspot scenicspot = new Scenicspot(sname,describe,city,price,createDate);
int num = biz.addSce(scenicspot);
if(num!=0){
out.print("<script type='text/javascript'>alert('添加成功!');open('index.jsp','_self');</script>");
}else{
out.print("<script type='text/javascript'>alert('添加失败!');open('index.jsp','_self');</script>");
}
}else if("del".equals(type)){
int id = Integer.parseInt(request.getParameter("id"));
int num = biz.delSce(id);
if(num!=0){
out.print("<script type='text/javascript'>alert('删除成功,返回首页!');open('index.jsp','_self');</script>");
}else {
out.print("<script type='text/javascript'>alert('删除失败,返回首页!');open('index.jsp','_self');</script>");
}
}else if("selOne".equals(type)){
int id =Integer.parseInt(request.getParameter("id"));
Scenicspot scenicspot = biz.selOneS(id);
request.setAttribute("scenicspot", scenicspot);
request.getRequestDispatcher("selOne.jsp").forward(request, response);
}else if("upd".equals(type)){
int sid =Integer.parseInt(request.getParameter("id"));
String sname = request.getParameter("sname");
String describe = request.getParameter("describe");
String city = request.getParameter("city");
Double price = Double.parseDouble(request.getParameter("price"));
Date createDate = new Date();
Scenicspot scenicspot = new Scenicspot(sid,sname,describe,city,price,createDate);
int num = biz.updSce(scenicspot);
if(num!=0){
out.print("<script type='text/javascript'>alert('修改成功!');open('index.jsp','_self');</script>");
}else{
out.print("<script type='text/javascript'>alert('修改失败!');open('index.jsp','_self');</script>");
}
}else{
out.print("<script type='text/javascript'>alert('加载失败,返回首页!');open('index.jsp','_self');</script>");
}
}
}
|
Python
|
UTF-8
| 2,211
| 2.53125
| 3
|
[] |
no_license
|
from IPython import embed
def prepare_folds(args):
ndays = args.ndays
nfolds = args.nfolds
t_size=args.ntrain
step=args.ntest
v_size = args.nval
set_fold = [];
for i in range(nfolds):
total = i * step + t_size;
training = range(total - v_size)
test = range(step);
validation = range(v_size);
j = 0;
traini = 0;
tt = round(total/2.)-1;
while j < tt - v_size/2:
training[traini] = j;
j+=1
traini+=1
k=0
while k < len(validation):
validation[k] = j;
k+=1
j+=1
while j < total:
training[traini] = j;
j+=1
traini+=1
k=0
while k < len(test):
test[k] = j;
k+=1
j+=1
foldi = {
"training":training,
"test": test,
"validation":validation
}
set_fold += [foldi]
return set_fold;
def prepare_folds_windowed(args):
ndays = args.ndays
nfolds = args.nfolds
training_window=args.train_win
test_window=args.test_win
set_fold = []
for i in range(nfolds):
validation = []
train_start = i * test_window
train_end = train_start + training_window
training = [x for x in range(train_start, train_end)]
test = [x for x in range(train_end, train_end + test_window)]
set_fold += [{
"training":training,
"test": test,
"validation": validation
}]
return set_fold
import experimentinputmode as eim
def prepare_fold_args(parser):
subparsers = parser.add_subparsers()
parser_windowed = subparsers.add_parser('windowed')
parser_windowed.add_argument('--train-win', type=int, default=48)
parser_windowed.add_argument('--test-win', type=int, default=5)
parser_windowed.set_defaults(folds=prepare_folds_windowed)
eim.prepare_input_mode(parser_windowed)
parser_growing = subparsers.add_parser('growing')
parser_growing.add_argument("--n-training", dest="ntrain",default=48,
help="Number of training instances in the first fold")
parser_growing.add_argument("--n-validation", dest="nval",default=8,
help="Number of training instances in the first fold to be used as validation")
parser_growing.add_argument("--n-test", dest="ntest",default=5,
help="Number of test instances and the increment per fold")
parser_growing.set_defaults(folds=prepare_folds)
eim.prepare_input_mode(parser_growing)
|
Java
|
UTF-8
| 2,387
| 2.484375
| 2
|
[] |
no_license
|
package cn.tedu.ttms.product.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import cn.tedu.ttms.common.dao.BaseDao;
import cn.tedu.ttms.common.vo.IdName;
import cn.tedu.ttms.product.entity.Project;
/**
* 项目模块的数据访问对象 1)负责数据的持久化 2)负责数据的查询然后执行映射操作
*/
public interface ProjectDao extends BaseDao<Project> {
/**
* 定义此方法用于实现分页查询操作 1)第一步先查询所有数据 2)第二步重构方法实现分页查询 3)第三步重构方法实现条件查询
*
* @param startIndex
* 从startIndex+1的位置开始取记录
* @Param pageSize 每页显示多少条记录 当一个方法中有多个参数时,请使用
* @Param 注解进行声明,在mapper文件中 使用参数时需要与@Param注解定义的名字 保持一致.
*/
List<Project> findPageObjects(@Param("name") String name, @Param("valid") Integer valid,
@Param("startIndex") Integer startIndex, @Param("pageSize") Integer pageSize);
// .....
/** 通过此方法获得记录总数,根据条件进行统计 */
int getRowCount(@Param("name") String name, @Param("valid") Integer valid);
/**
* 通过此方法实现禁用启用操作
*
* @param ids
* 表示要禁用的对象的id
* @param valid
* 表示状态(1,0)
*/
int validById(@Param("ids") String[] ids, @Param("valid") Integer valid);
/**
* 通过此方法实现数据的插入操作
*
* @param entity
* 通过此对象封装了要 写入的数据
* @return 表示写入数据的行数
*/
// int insertObject(Project entity);
/**
* 根据ID获得project对象
*
* @param id
* 对象的唯一标识
*/
Project findObjectById(Integer id);
/** 用于更新项目信息 */
int updateObject(Project entity);
/** 获得项目的id和name */
List<IdName> findIdAndNames();
}
/**
* 知识点回顾? 1.SSM架构中这个DAO对象的实现方式有哪些形式? 1)自己实现此DAO实现类 2)在配置文件中通过配置由底层自动创建dao的 实现类。
* 例如借助MapperScannerConfigurer对象扫描对应包 中的实现类? 2.SSM架构中这个DAO对象与具体mapper是如何 绑定的?
* 1)命名空间的绑定 2)方法与元素id的绑定 3)方法参数与具体SQL的绑定 4)方法返回值的匹配
*/
|
Java
|
UTF-8
| 11,161
| 1.601563
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2015-2023 AsyncHttpClient Project. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.asynchttpclient;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.ssl.SslContext;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import org.asynchttpclient.channel.ChannelPool;
import org.asynchttpclient.channel.KeepAliveStrategy;
import org.asynchttpclient.cookie.CookieStore;
import org.asynchttpclient.filter.IOExceptionFilter;
import org.asynchttpclient.filter.RequestFilter;
import org.asynchttpclient.filter.ResponseFilter;
import org.asynchttpclient.netty.EagerResponseBodyPart;
import org.asynchttpclient.netty.LazyResponseBodyPart;
import org.asynchttpclient.netty.channel.ConnectionSemaphoreFactory;
import org.asynchttpclient.proxy.ProxyServer;
import org.asynchttpclient.proxy.ProxyServerSelector;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.function.Consumer;
public interface AsyncHttpClientConfig {
/**
* @return the version of AHC
*/
String getAhcVersion();
/**
* Return the name of {@link AsyncHttpClient}, which is used for thread naming and debugging.
*
* @return the name.
*/
String getThreadPoolName();
/**
* Return the maximum number of connections an {@link AsyncHttpClient} can handle.
*
* @return the maximum number of connections an {@link AsyncHttpClient} can handle.
*/
int getMaxConnections();
/**
* Return the maximum number of connections per hosts an {@link AsyncHttpClient} can handle.
*
* @return the maximum number of connections per host an {@link AsyncHttpClient} can handle.
*/
int getMaxConnectionsPerHost();
/**
* Return the maximum duration in milliseconds an {@link AsyncHttpClient} can wait to acquire a free channel
*
* @return Return the maximum duration in milliseconds an {@link AsyncHttpClient} can wait to acquire a free channel
*/
int getAcquireFreeChannelTimeout();
/**
* Return the maximum time an {@link AsyncHttpClient} can wait when connecting to a remote host
*
* @return the maximum time an {@link AsyncHttpClient} can wait when connecting to a remote host
*/
Duration getConnectTimeout();
/**
* Return the maximum time an {@link AsyncHttpClient} can stay idle.
*
* @return the maximum time an {@link AsyncHttpClient} can stay idle.
*/
Duration getReadTimeout();
/**
* Return the maximum time an {@link AsyncHttpClient} will keep connection in pool.
*
* @return the maximum time an {@link AsyncHttpClient} will keep connection in pool.
*/
Duration getPooledConnectionIdleTimeout();
/**
* @return the period to clean the pool of dead and idle connections.
*/
Duration getConnectionPoolCleanerPeriod();
/**
* Return the maximum time an {@link AsyncHttpClient} waits until the response is completed.
*
* @return the maximum time an {@link AsyncHttpClient} waits until the response is completed.
*/
Duration getRequestTimeout();
/**
* Is HTTP redirect enabled
*
* @return true if enabled.
*/
boolean isFollowRedirect();
/**
* Get the maximum number of HTTP redirect
*
* @return the maximum number of HTTP redirect
*/
int getMaxRedirects();
/**
* Is the {@link ChannelPool} support enabled.
*
* @return true if keep-alive is enabled
*/
boolean isKeepAlive();
/**
* Return the USER_AGENT header value
*
* @return the USER_AGENT header value
*/
String getUserAgent();
/**
* Is HTTP compression enforced.
*
* @return true if compression is enforced
*/
boolean isCompressionEnforced();
/**
* If automatic content decompression is enabled.
*
* @return true if content decompression is enabled
*/
boolean isEnableAutomaticDecompression();
/**
* Return the {@link ThreadFactory} an {@link AsyncHttpClient} use for handling asynchronous response.
*
* @return the {@link ThreadFactory} an {@link AsyncHttpClient} use for handling asynchronous response. If no {@link ThreadFactory} has been explicitly
* provided, this method will return {@code null}
*/
@Nullable ThreadFactory getThreadFactory();
/**
* An instance of {@link ProxyServer} used by an {@link AsyncHttpClient}
*
* @return instance of {@link ProxyServer}
*/
ProxyServerSelector getProxyServerSelector();
/**
* Return an instance of {@link SslContext} used for SSL connection.
*
* @return an instance of {@link SslContext} used for SSL connection.
*/
@Nullable SslContext getSslContext();
/**
* Return the current {@link Realm}
*
* @return the current {@link Realm}
*/
@Nullable Realm getRealm();
/**
* Return the list of {@link RequestFilter}
*
* @return Unmodifiable list of {@link RequestFilter}
*/
List<RequestFilter> getRequestFilters();
/**
* Return the list of {@link ResponseFilter}
*
* @return Unmodifiable list of {@link ResponseFilter}
*/
List<ResponseFilter> getResponseFilters();
/**
* Return the list of {@link IOException}
*
* @return Unmodifiable list of {@link IOException}
*/
List<IOExceptionFilter> getIoExceptionFilters();
/**
* Return cookie store that is used to store and retrieve cookies
*
* @return {@link CookieStore} object
*/
CookieStore getCookieStore();
/**
* Return the delay in milliseconds to evict expired cookies from {@linkplain CookieStore}
*
* @return the delay in milliseconds to evict expired cookies from {@linkplain CookieStore}
*/
int expiredCookieEvictionDelay();
/**
* Return the number of time the library will retry when an {@link IOException} is throw by the remote server
*
* @return the number of time the library will retry when an {@link IOException} is throw by the remote server
*/
int getMaxRequestRetry();
/**
* @return the disableUrlEncodingForBoundRequests
*/
boolean isDisableUrlEncodingForBoundRequests();
/**
* @return true if AHC is to use a LAX cookie encoder, eg accept illegal chars in cookie value
*/
boolean isUseLaxCookieEncoder();
/**
* In the case of a POST/Redirect/Get scenario where the server uses a 302 for the redirect, should AHC respond to the redirect with a GET or whatever the original method was.
* Unless configured otherwise, for a 302, AHC, will use a GET for this case.
*
* @return {@code true} if strict 302 handling is to be used, otherwise {@code false}.
*/
boolean isStrict302Handling();
/**
* @return the maximum time an {@link AsyncHttpClient} will keep connection in the pool, or negative value to keep connection while possible.
*/
Duration getConnectionTtl();
boolean isUseOpenSsl();
boolean isUseInsecureTrustManager();
/**
* @return true to disable all HTTPS behaviors AT ONCE, such as hostname verification and SNI
*/
boolean isDisableHttpsEndpointIdentificationAlgorithm();
/**
* @return the array of enabled protocols
*/
@Nullable String[] getEnabledProtocols();
/**
* @return the array of enabled cipher suites
*/
@Nullable String[] getEnabledCipherSuites();
/**
* @return if insecure cipher suites must be filtered out (only used when not explicitly passing enabled cipher suites)
*/
boolean isFilterInsecureCipherSuites();
/**
* @return the size of the SSL session cache, 0 means using the default value
*/
int getSslSessionCacheSize();
/**
* @return the SSL session timeout in seconds, 0 means using the default value
*/
int getSslSessionTimeout();
int getHttpClientCodecMaxInitialLineLength();
int getHttpClientCodecMaxHeaderSize();
int getHttpClientCodecMaxChunkSize();
int getHttpClientCodecInitialBufferSize();
boolean isDisableZeroCopy();
int getHandshakeTimeout();
@Nullable SslEngineFactory getSslEngineFactory();
int getChunkedFileChunkSize();
int getWebSocketMaxBufferSize();
int getWebSocketMaxFrameSize();
boolean isKeepEncodingHeader();
Duration getShutdownQuietPeriod();
Duration getShutdownTimeout();
Map<ChannelOption<Object>, Object> getChannelOptions();
@Nullable EventLoopGroup getEventLoopGroup();
boolean isUseNativeTransport();
boolean isUseOnlyEpollNativeTransport();
@Nullable Consumer<Channel> getHttpAdditionalChannelInitializer();
@Nullable Consumer<Channel> getWsAdditionalChannelInitializer();
ResponseBodyPartFactory getResponseBodyPartFactory();
@Nullable ChannelPool getChannelPool();
@Nullable ConnectionSemaphoreFactory getConnectionSemaphoreFactory();
@Nullable Timer getNettyTimer();
/**
* @return the duration between tick of {@link HashedWheelTimer}
*/
long getHashedWheelTimerTickDuration();
/**
* @return the size of the hashed wheel {@link HashedWheelTimer}
*/
int getHashedWheelTimerSize();
KeepAliveStrategy getKeepAliveStrategy();
boolean isValidateResponseHeaders();
boolean isAggregateWebSocketFrameFragments();
boolean isEnableWebSocketCompression();
boolean isTcpNoDelay();
boolean isSoReuseAddress();
boolean isSoKeepAlive();
int getSoLinger();
int getSoSndBuf();
int getSoRcvBuf();
@Nullable ByteBufAllocator getAllocator();
int getIoThreadsCount();
enum ResponseBodyPartFactory {
EAGER {
@Override
public HttpResponseBodyPart newResponseBodyPart(ByteBuf buf, boolean last) {
return new EagerResponseBodyPart(buf, last);
}
},
LAZY {
@Override
public HttpResponseBodyPart newResponseBodyPart(ByteBuf buf, boolean last) {
return new LazyResponseBodyPart(buf, last);
}
};
public abstract HttpResponseBodyPart newResponseBodyPart(ByteBuf buf, boolean last);
}
}
|
Java
|
UTF-8
| 888
| 3.96875
| 4
|
[] |
no_license
|
package eos.java.practice.ppt;
/**
* 汉诺塔:始终保证小圆盘上不能放大圆盘,一次只能移动一个圆盘
*/
public class Hanoi {
private static int count = 1 ;
//有 A B C三个容器 A上放入N个圆盘
//目标是借助B容器,将A容器上的所有圆盘移动到C容器上
//每次取A中最大的圆盘,移到C中
public static void moveDisc(int n, char a, char b, char c) {
if( n == 1) {
System.out.println("第" + (count++) + "步 :" + "将 盘子 1 从 " + a + " 移动到 " + c);
} else {
moveDisc(n - 1, a, c, b);
System.out.println("第" + (count++) + "步 :" + "将 盘子 "+ n + " 从 " + a + " 移动到 " + c);
moveDisc(n - 1, b, a, c);
}
}
public static void main(String args[]) {
Hanoi.moveDisc(4, 'A', 'B', 'C');
}
}
|
Python
|
UTF-8
| 9,861
| 2.515625
| 3
|
[] |
no_license
|
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow_probability import distributions
from configuration.Hyperparameter import Hyperparameters
##
# Implementation based on: https://bit.ly/3oRMiQz
##
class Sampling(layers.Layer):
def call(self, inputs, **kwargs):
z_mean, z_log_var = inputs
batch = tf.shape(z_mean)[0]
dim = tf.shape(z_mean)[1]
epsilon = tf.keras.backend.random_normal(shape=(batch, dim))
return z_mean + tf.exp(0.5 * z_log_var) * epsilon
class Encoder(layers.Layer):
def __init__(self, latent_dim, intermediate_dim, name="vae_encoder", **kwargs):
super(Encoder, self).__init__(name=name, **kwargs)
self.dense_proj = layers.Dense(intermediate_dim, activation="relu")
self.dense_mean = layers.Dense(latent_dim)
self.dense_log_var = layers.Dense(latent_dim)
def call(self, inputs, **kwargs):
x = self.dense_proj(inputs)
z_mean = self.dense_mean(x)
z_log_var = self.dense_log_var(x)
return z_mean, z_log_var
class Decoder(layers.Layer):
def __init__(self, original_dim, intermediate_dim, name="vae_decoder", **kwargs):
super(Decoder, self).__init__(name=name, **kwargs)
self.dense_proj = layers.Dense(intermediate_dim, activation="relu")
self.dense_mean = layers.Dense(original_dim)
self.dense_log_var = layers.Dense(original_dim)
def call(self, inputs, **kwargs):
"""
This variant of a VAE decoder returns the mean and variance with which X hat can be sampled.
Necessary for the reconstruction probability calculation.
"""
inter = self.dense_proj(inputs)
x_mean = self.dense_mean(inter)
x_log_var = self.dense_log_var(inter)
return x_mean, x_log_var
class VAE(layers.Layer):
def __init__(self, hyper: Hyperparameters, name="VAE", **kwargs):
super(VAE, self).__init__(name=name, **kwargs)
self.hyper = hyper
self.latent_dim = self.hyper.d3_vae_latent_dim
self.intermediate_dim = self.hyper.d3_vae_inter_dim
# If the variant is used, where the gru output is reconstructed, the output size of the gru layer is fixed
# to the time series depth, so we use this value instead of the value configured in d1_gru_units
# which could be different
if 'reconstruct_gru' in self.hyper.variants:
target_feature_dim = self.hyper.time_series_depth
else:
target_feature_dim = self.hyper.d1_gru_units[-1]
self.gru_output_dim = (self.hyper.time_series_length, target_feature_dim)
self.gru_output_dim_flat = self.hyper.time_series_length * target_feature_dim
self.rec_target_dim = (self.hyper.time_series_length, self.hyper.time_series_depth)
self.rec_target_dim_flat = self.hyper.time_series_length * self.hyper.time_series_depth
self.flatten_gru_output = tf.keras.layers.Reshape(target_shape=(self.gru_output_dim_flat,))
self.flatten_rec_target = tf.keras.layers.Reshape(target_shape=(self.rec_target_dim_flat,))
self.rebuild_rec_target_shape = tf.keras.layers.Reshape(target_shape=self.rec_target_dim)
self.encoder = Encoder(latent_dim=self.latent_dim, intermediate_dim=self.intermediate_dim)
self.decoder = Decoder(original_dim=self.rec_target_dim_flat, intermediate_dim=self.intermediate_dim)
self.sampling = Sampling()
print('Adding VAE as reconstruction model with dimensions {} & {} and ...'.format(self.intermediate_dim,
self.latent_dim))
def call(self, inputs, **kwargs):
inputs = self.flatten_gru_output(inputs)
z_mean, z_log_var = self.encoder(inputs)
z = self.sampling([z_mean, z_log_var])
x_mean, x_log_var = self.decoder(z)
x_reconstructed = self.sampling([x_mean, x_log_var])
x_reconstructed = self.rebuild_rec_target_shape(x_reconstructed)
# Add KL divergence regularization loss.
kl_loss = -0.5 * tf.reduce_mean(z_log_var - tf.square(z_mean) - tf.exp(z_log_var) + 1)
self.add_loss(kl_loss)
return x_reconstructed
@tf.function
def reconstruction_probability(self, gru_output, reconstruction_target, L=None):
reconstruction_target = self.flatten_rec_target(reconstruction_target)
gru_output = self.flatten_gru_output(gru_output)
z_means, z_log_vars = self.encoder(gru_output)
# Sample size is set to the batch size if no specific value is passed
L = gru_output.shape[0] if L is None else L
L = tf.constant(L)
sample_index = tf.constant(0)
sampling_results = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True)
# Track the sampling process
def while_condition(sample_index, L, _):
return tf.less(sample_index, L)
# Note to self: all parameters of body must be returned in the same order
# Write the result of a single sample calculation to the result array
def while_body(sample_index, L, results):
single_result = single_sample_calculation()
results = results.write(sample_index, single_result)
return sample_index + 1, L, results
def single_sample_calculation():
"""
One call calculates one of L Samples for each example in the batch
Based on An and Chao http://dm.snu.ac.kr/static/docs/TR/SNUDM-TR-2015-03.pdf,
but applied to a single cell (time step, feature)
:return:
"""
# Sample x' distribution for this sample
z = self.sampling([z_means, z_log_vars])
x_mean, x_log_var = self.decoder(z)
# Convert log. variance to standard deviation
x_sigma = tf.sqrt(tf.exp(x_log_var) + 1e-5)
# Split the calculation for this sample for each example in the batch
reconstruction_probs = tf.vectorized_map(self.each_example, [reconstruction_target, x_mean, x_sigma])
return reconstruction_probs
# Execute a loop the calculate the results for L samples
# Note to self: return values correspond to the loop vars
_, _, sampling_results = tf.while_loop(cond=while_condition, body=while_body,
loop_vars=[sample_index, L, sampling_results])
# Combine the sample results into a tensor and calculate the mean of each cell over the L samples
# sampling_results = sampling_results.stack()
sampling_results = sampling_results.gather(range(0, L))
sampling_results = tf.stack(sampling_results, axis=0)
sampling_results = tf.reduce_mean(sampling_results, axis=0)
# Reshape from 1 dimensional vector the time series dimensions (time series length x time series depth)
sampling_results = self.rebuild_rec_target_shape(sampling_results)
return sampling_results
def each_example(self, args):
x, means, sigmas = args
# Split the calculation from each example in the batch into a cell based calculation
reconstruction_prob = tf.vectorized_map(self.each_cell, [x, means, sigmas], fallback_to_while_loop=True)
return reconstruction_prob
@tf.function
def each_cell(self, args):
reconstructed_cell, mean_sample, sigma_sample = args
# Calculate the probability of the cell value being reconstructed from a normal distribution defined by
# the passed mean and standard deviation
normal = distributions.Normal(mean_sample, sigma_sample, validate_args=False, allow_nan_stats=False)
# Changed from probability density to cumulative density function in order to return a probability in [0,1]
reconstruction_prob_for_cell = normal.cdf(reconstructed_cell)
return reconstruction_prob_for_cell
class GRU_AE(layers.Layer):
def __init__(self, hyper: Hyperparameters, name="GRU_AE", **kwargs):
super(GRU_AE, self).__init__(name=name, **kwargs)
self.hyper = hyper
self.inter_dim = self.hyper.d3_vae_inter_dim
self.latent_dim = self.hyper.d3_vae_latent_dim
self.output_dim = self.hyper.time_series_depth
# If the variant is used, where the gru output is reconstructed, the output size of the gru layer is fixed
# to the time series depth, so we use this value instead of the value configured in d1_gru_units
# which could be different
if 'reconstruct_gru' in self.hyper.variants:
self.input_dim = self.hyper.time_series_depth
else:
self.input_dim = self.hyper.d1_gru_units[-1]
self.encoder = tf.keras.models.Sequential()
self.encoder.add(layers.Input(shape=(self.hyper.time_series_length, self.input_dim)))
if self.inter_dim is not None:
self.encoder.add(layers.GRU(units=self.inter_dim, return_sequences=True))
self.encoder.add(layers.GRU(units=self.latent_dim, return_sequences=True))
self.decoder = tf.keras.models.Sequential()
self.decoder.add(layers.Input(shape=(self.hyper.time_series_length, self.latent_dim)))
if self.inter_dim is not None:
self.decoder.add(layers.GRU(self.inter_dim, return_sequences=True))
self.decoder.add(layers.GRU(self.output_dim, return_sequences=True))
print('Adding GRU AE as reconstruction model with dimensions {} & {} and ...'.format(self.inter_dim,
self.latent_dim))
def call(self, inputs, **kwargs):
z = self.encoder(inputs)
inputs_reconstructed = self.decoder(z)
return inputs_reconstructed
|
C++
|
UTF-8
| 1,130
| 3.125
| 3
|
[] |
no_license
|
#include <iostream>
#include <time.h>
#include <sys/time.h>
#include <vector>
using namespace std;
#define FLT_MAX 3.402823466e+38F
int main() {
time_t t = time(NULL);
cout << t << endl;
cout << time(NULL) << endl;
cout << system("time") << endl;
struct timeval tv;
gettimeofday(&tv, NULL);
double mm = (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
printf("%lf\n", mm);
cout << "----------------------------" << endl;
vector<int> vec1;
vec1.push_back(1);
vec1.push_back(2);
vector<int> vec2;
vec2.push_back(5);
vec2.push_back(6);
vec1.insert(vec1.end(), vec2.begin(), vec2.end());
vec1.assign(vec2.begin(), vec2.end());
for (int i = 0; i < vec1.size(); ++i) {
cout << vec1[i] << endl;
}
cout << "----------------------------" << endl;
float a = FLT_MAX;
float b = FLT_MAX;
float c = a;
if (c < b) {
printf("less %f\n", b - c );
}
cout << a - c << endl;
printf("%f\n", a - c );
cout << "----------------------------" << endl;
int* arr = new int(5);
return 0;
}
|
PHP
|
UTF-8
| 883
| 2.671875
| 3
|
[] |
no_license
|
<?php
$num=$_POST['num'];
$titre=$_POST['titre'];
$duree=$_POST['duree'];
$res=$_POST['res'];
$dossier="../pochettes/";
$nomPochette=sha1($titre.time());
$pochette="avatar.jpg";
if(!$fic=fopen("../donnees/films.txt","a")){
echo "ERREUR: probleme avec le fichier";
exit;
}
if($_FILES['pochette']['tmp_name']!==""){
//Upload de la photo
$tmp = $_FILES['pochette']['tmp_name'];
$fichier= $_FILES['pochette']['name'];
$extension=strrchr($fichier,'.');
@move_uploaded_file($tmp,$dossier.$nomPochette.$extension);
// Enlever le fichier temporaire chargé
@unlink($tmp); //effacer le fichier temporaire
$pochette=$nomPochette.$extension;
}
$ligne=$num.";".$titre.";".$duree.";".$res.";".$pochette."\n";
fputs($fic,$ligne);
fclose($fic);
echo "<br><b>AJOUT DU FILM NUMERO : ".$num."</b>";
?>
<br><br>
<a href="../films.html">Retour à la page d'accueil</a>
|
C++
|
UTF-8
| 2,255
| 2.671875
| 3
|
[] |
no_license
|
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <CTP7AlgoClient.hh>
#include <stdexcept>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <pthread.h>
#include <limits.h>
#include <errno.h>
#include <sys/stat.h>
#include <map>
const std::string data_path = "data";
typedef struct
{
std::vector<uint32_t> data;
} input_data_t;
std::map<int, input_data_t> load_file(std::string path)
{
std::ifstream infile(path.c_str(), std::fstream::in);
if (!infile.is_open())
throw std::runtime_error(std::string("Unable to open input file: ") + path);
// std map container to store complete LUT info read from the file
// 28x8182 uint32_t for 2nd Stage LUTs (iEta=[1-28])
std::map<int, input_data_t> input_data;
uint64_t value64;
uint64_t value32;
std::string dummyLine;
// skip header lines
getline(infile, dummyLine);
getline(infile, dummyLine);
getline(infile, dummyLine);
// Read input data from the file
for (int idx = 0; idx < 512; idx++)
{
infile >> std::hex >> value64;
for (int i = 0; i < 48; i++)
{
infile >> std::hex >> value64;
value32 = uint32_t(value64 & 0xFFFFFFFF);
input_data[i].data.push_back(value32);
value32 = (value64 >> 32);
input_data[i].data.push_back(value32);
}
}
return input_data;
}
int main(int argc, char *argv[]) {
bool rc; // RPC return code
std::vector<CTP7AlgoClient*> cards;
int phi = atoi(argv[1]);
CTP7AlgoClient * card;
try
{
card = new CTP7AlgoClient(phi, "CTP7Map.xml");
}
catch (std::runtime_error &e)
{
std::cout << "Couldnt connect to phi: " << phi << e.what() << std::endl;
return -1;
}
std::map<int, input_data_t> input_data;
try
{
input_data = load_file( (data_path + "/" + argv[2]).c_str() );
}
catch (std::runtime_error &e)
{
std::cout << "Error loading link data for phi " << phi << e.what() << std::endl;
return -1 ;
}
for (int link = 0; link < 48; link++)
{
rc = card->setOutputLinkBuffer(link, input_data[link].data);
if (rc == false) {
std::cout << "setOutputLinkBuffer fails for link " << link << std::endl;
return -1;
}
}
return 0;
}
|
JavaScript
|
UTF-8
| 2,333
| 2.921875
| 3
|
[] |
no_license
|
class TeamMembers{
name;
address;
constructor(name , address){
this.name = name;
this.address = address;
}
}
class Support extends TeamMembers{
designation;
constructor( name, address, designation){
super(name, address);
this.designation = designation;
}
startSession(){
console.log(this.name,'Say, Yess This is Session Time');
}
}
class StudentCare extends TeamMembers{
designation = "Care Of Our Student";
constructor( name, address){
super(name, address);
}
builARoutin(student){
console.log(this.name , "please Make a Routin for the", student)
}
}
class NeptuneDev extends TeamMembers{
designation = "Maintain Neptune App";
constructor( name, address){
super(name,address);
}
reliseApp(version){
console.log( this.name , "please Make a Routin for the", version )
}
}
const firstPerson = new Support("maruf","mirpur", "Support Member");
// console.log(firstPerson)
// const secondPerson = new NeptuneDev( "Rocky", "Dhaka BD");
// console.log(secondPerson)
// const thirdPerson = new StudentCare('Mukit', "Kalsi");
// thirdPerson.builARoutin('rocky')
// console.log(thirdPerson)
class GlobalProductss{
nameOfProduct;
productQuentity;
productDiscount;
productSlNum;
constructor( nameOfProduct, productQuentity, productDiscount, productSlNum ){
this.nameOfProduct = nameOfProduct;
this.productQuentity = productQuentity;
this.productDiscount = productDiscount;
this.productSlNum = productSlNum;
}
}
class productOfTshirt extends GlobalProductss{
prodcutLocation;
constructor( nameOfProduct, productQuentity, productDiscount, productSlNum, prodcutLocation){
super(nameOfProduct, productQuentity, productDiscount, productSlNum);
this.prodcutLocation = prodcutLocation;
}
}
const resultOfProduct = new productOfTshirt( 'Samsung Phone', '15 pcs', '30% off', 'Sl num : 5',"Dhaka" );
const secondProduct = new productOfTshirt( 'Shawni Phone', '50 pcs', '30% off', 'Sl num : 8',"Dhaka" );
const thirdProduct = new productOfTshirt( 'iphone Phone', '10 pcs', '30% off', 'Sl num : 1',"Dhaka" );
// console.log(resultOfProduct)
// console.log(secondProduct)
// console.log(thirdProduct)
|
Markdown
|
UTF-8
| 5,741
| 3.609375
| 4
|
[] |
no_license
|
#初识redis
##数据结构简介
结构类型|结构存储的值|结构的读写能力
-------|------------|------------
STRING|可以是字符串、整数或则浮点数|对整个字符串或者字符串的其中一部分执行操作;对整数和浮点数执行自增或则自减操作
LIST|一个链表,链表上的每个节点都包含了一个字符串|从链表的两端推入或则弹出元素,根据偏移量对链表进行修剪;读取单个或则多个元素;根据值查找或则移除元素
SET|包含字符串的无序收集器,并且包含的每个字符串都是独一无二的、各不相同的|添加、获取、移除单个元素;检查一个元素是否存在于集合中;计算交集、并级、差集;从集合里面随机获取元素
HASH|包含键值对的无序列表|添加、获取、移除单个键值对;获取所有键值对
ZSET(有序集合)|字符串成员(member)与浮点数分值(score)之间的有序映射,元素的排列顺序由分值大小决定|添加、获取、删除单个元素;根据分值范围(range)或则成员来获取元素
### 字符串
>命令:get、set、del;还提供对存储的数值进行自增或则自减操作
```shell
127.0.0.1:6379> set name xq
OK
127.0.0.1:6379> set name xl
OK
127.0.0.1:6379> get name
"xl"
127.0.0.1:6379> del name
(integer) 1
127.0.0.1:6379> get name
(nil)
```
### 列表
链表(linked-list): list-key --> list
1. key --> list;比如:RPUSH name xq;RPUSH name xl; xq和小丽都属于name这个key中
2. 值有序,可重复
命令|行为
-|-
RPUSH|将给定值推入列表的右端
LRANGE|获取列表在给定范围上的所有值
LINDEX|获取列表在给定位置上的单个元素
LPOP|从列表的左端弹出一个值,并返回被弹出的值
```shell
127.0.0.1:6379> rpush names xq
(integer) 1
127.0.0.1:6379> rpush names xl
(integer) 2
127.0.0.1:6379> rpush names xl2
(integer) 3
127.0.0.1:6379> rpush names xl1
(integer) 4
127.0.0.1:6379> lrange names
(error) ERR wrong number of arguments for 'lrange' command
127.0.0.1:6379> lrange names 0 -1
1) "xq"
2) "xl"
3) "xl2"
4) "xl1"
127.0.0.1:6379> lpop names
"xq"
127.0.0.1:6379> lrange names 0 -1
1) "xl"
2) "xl2"
3) "xl1"
127.0.0.1:6379> lindex names 2
"xl1"
127.0.0.1:6379> lrange names 0 -1
1) "xl"
2) "xl2"
3) "xl1"
```
###集合
set-key --> set
1. 与列表差不多的数据结构,都是 key ---> set 方式;
2. 无序,set中的值不可重复
命令|行为
-|-
SADD|将给定元素添加到集合
SMEMBERS|返回集合包含的所有元素
SISMEMBER|检查给定元素是否存在于集合中
SREM|如果给定的元素存在于集合中,那么移除这个元素
```shell
增加几个名字到key=names1 的集合中
127.0.0.1:6379> sadd names1 xq
(integer) 1
127.0.0.1:6379> sadd names1 xl
(integer) 1
127.0.0.1:6379> sadd names1 xl
(integer) 0
返回所有元素
127.0.0.1:6379> smembers names1
1) "xq"
2) "xl"
是否存在xq这个元素
127.0.0.1:6379> sismember names1 xq
(integer) 1
127.0.0.1:6379> sismember names1 xq1
(integer) 0
存在xq这个元素就删除它
127.0.0.1:6379> srem names1 xq
(integer) 1
127.0.0.1:6379> smembers names1
1) "xl"
```
###散列
hash-key --> hash
1. 和字符串一样,可以存储字符串和数字,支持自增和自减操作
2. 键key,无序
命令|行为
-|-
HSET|在散列里面关联起给定的键值对
HGET|获取指定散列的值
HGETALL|获取散列包含的所有键值对
HDEL|如果给定键存在于散列里面,那么移除这个键
```Shell
往散列中存入 KEY=class,key=c1,val=xq 的数据
127.0.0.1:6379> hset class c1 xq
(integer) 1
这里其实是对上一条数据的更新,因为key是hash的,唯一的
127.0.0.1:6379> hset class c1 xl
(integer) 0
127.0.0.1:6379> hset class c2 xq
(integer) 1
127.0.0.1:6379> hset class c2 lp
(integer) 0
上面4条语句,其实只插入了两条数据。有两条命令是对上一条的更新
下面的获取所有的数据,在命令行中,显示有4条,其实奇数行是key,偶数行是val
127.0.0.1:6379> hgetall class
1) "c1"
2) "xl"
3) "c2"
4) "lp"
127.0.0.1:6379> hget class c1
"xl"
这里可以证明上面的4行数据,是key和val组成的
127.0.0.1:6379> hget class xl
(nil)
删除
127.0.0.1:6379> hdel class c1
(integer) 1
127.0.0.1:6379> hgetall class
1) "c2"
2) "lp"
```
###有序集合
zset-key --> zset
1. 键称为成员(member)
2. 值称为分值(score)
3. 有序集合是redis中唯一一个既可以根据成员访问元素,又可以根据分值以及分值的排列顺序来访问元素的结构
命令|行为
-|-
ZADD|将一个带有给定分值的成员添加到有序集合里面
ZRANGE|根据元素在有序排列中所处的位置,从有序集合里面获取多个元素
ZRANGEBYSCORE|获取有序集合在给定分值范围内的所有元素
ZREM|如果给定成员存在于有序集合,那么移除这个成员
```bash
往 KEY=znames,分值=整数浮点数如728,成员=m1 的有序集合插入一条数据
127.0.0.1:6379> zadd znames 728 m1
(integer) 1
127.0.0.1:6379> zadd znames 600 m2
(integer) 1
127.0.0.1:6379> zadd znames 900 m0
(integer) 1
获取所有的成员
127.0.0.1:6379> zrange znames 0 -1
1) "m2"
2) "m1"
3) "m0"
获取所有的成员,显示分值
127.0.0.1:6379> zrange znames 0 -1 withscores
1) "m2"
2) "600"
3) "m1"
4) "728"
5) "m0"
6) "900"
语法一定要对,不然就提示无效的哦
127.0.0.1:6379> zadd znames m3 800
(error) ERR value is not a valid float
指定获取分值为600 - 800 的成员
127.0.0.1:6379> zrangebyscore znames 600 800
1) "m2"
2) "m1"
删除成员m0
127.0.0.1:6379> zrem znames m0
(integer) 1
127.0.0.1:6379> zrange znames 0 -1 withscores
1) "m2"
2) "600"
3) "m1"
4) "728"
```
|
Python
|
UTF-8
| 471
| 3.375
| 3
|
[
"MIT"
] |
permissive
|
def BinarySearch(Arr,l,h,key):
n = len(Arr)
# l = 0
# h = n
mid = (l+h)//2
if n == 0:
return False
elif l >= h:
if Arr[0] == key:
return True
else:
if Arr[mid] == key:
return True
elif key < Arr[mid]:
return BinarySearch(Arr, l, mid, key)
else:
return BinarySearch(Arr, (mid+1), h, key)
Arr = [1,2,4,5,9,13,14]
l = 0
h = len(Arr)
key = 15
Ans = BinarySearch(Arr,l,h,key)
print Ans
if Ans == True:
print("found")
else:
print("not found")
|
Shell
|
UTF-8
| 2,407
| 2.796875
| 3
|
[] |
no_license
|
#!/bin/bash
github_black="#24292e"
github_yellow="#df5f11"
github_white="#feffff"
github_green="#22863a"
github_visual_grey="#41484f"
github_light_grey="#eceef1"
github_light_blue="#aedaf7"
time_format="%R"
date_format="%Y-%m-%d"
tmux set-option -gq status "on"
tmux set-option -gq status-justify "left"
tmux set-option -gq status-left-length "100"
tmux set-option -gq status-right-length "100"
tmux set-option -gq status-right-attr "none"
tmux set-option -gq message-style "bg=$github_light_grey,fg=$github_black"
tmux set-option -gq message-command-style "bg=$github_white,fg=$github_black"
tmux set-option -gq status-attr "none"
tmux set-option -gq status-left-attr "none"
tmux set-option -gq status-style "bg=$github_light_grey,fg=$github_black"
tmux set-option -gq pane-border-style "fg=$github_light_grey"
tmux set-option -gq pane-active-border-style "fg=$github_black"
tmux set-window-option -gq mode-style "bg=$github_light_blue"
tmux set-window-option -gq window-status-fg $github_black
tmux set-window-option -gq window-status-bg $github_light_grey
tmux set-window-option -gq window-status-attr "none"
tmux set-window-option -gq window-status-activity-bg $github_black
tmux set-window-option -gq window-status-activity-fg $github_white
tmux set-window-option -gq window-status-activity-attr "none"
tmux set-window-option -gq window-status-separator ""
tmux set-option -gq @prefix_highlight_fg "$github_white"
tmux set-option -gq @prefix_highlight_bg "$github_yellow"
tmux set-option -gq @prefix_highlight_copy_mode_attr "bg=$github_yellow,fg=$github_visual_grey"
tmux set-option -gq @prefix_highlight_output_prefix "« "
tmux set-option -gq @prefix_highlight_output_suffix " "
tmux set-option -gq status-right "#{prefix_highlight}#[fg=$github_visual_grey,bg=$github_light_grey]«#[fg=$github_light_grey,bg=$github_visual_grey] ${date_format} ${time_format} #[fg=$github_black,bg=$github_visual_grey]«#[fg=$github_light_grey,bg=$github_black] #h "
tmux set-option -gq status-left "#[fg=$github_light_grey,bg=$github_yellow] #S #[fg=$github_visual_grey,bg=$github_light_grey]»"
tmux set-option -gq window-status-format "#[fg=$github_light_grey,bg=$github_visual_grey] #I » #W #[fg=$github_visual_grey,bg=$github_light_grey]»"
tmux set-option -gq window-status-current-format "#[fg=$github_light_grey,bg=$github_green,bold] #I » #W #[fg=$github_visual_grey,bg=$github_light_grey]»"
|
Shell
|
UTF-8
| 1,405
| 4.1875
| 4
|
[] |
no_license
|
#!/bin/bash
###############################################################################
# Name : DeployToPCFDev.sh
# Author : Swarada Kalekar
# Created on : Jan 2017
# Description : Script is written to deploy the application
# on PCF Dev Environment. Script will accept
# User Details, Organization, Space, Application details
###############################################################################
if [ ${#} -ne 6 ]; then
echo "Usage: DeployToPCFDev.sh <HostURL> <UserId> <Password> <Org> <Space> <ApplicationName>"
else
export hostURL=$1
export userId=$2
export password=$3
export org=$4
export space=$5
export appName=$6
rm -rf logs
mkdir logs
cf login -a ${hostURL} --skip-ssl-validation -u ${userId} -p ${password} -o ${org} -s ${space}
cnt=1
while [ $cnt -lt 4 ]
do
echo "" >> logs/deployLogs.log
echo "***************Deploy attempt $cnt******************" >> logs/deployLogs.log
echo "" >> logs/deployLogs.log
cf push --hostname ${appName} >> logs/deployLogs.log 2>&1
if [ 1 -ge `cat logs/deployLogs.log | grep 'App started' | wc -l` ]; then
cf logs ${appName} --recent > logs/appRecentLogs.log 2>&1
echo "App deployed and started successfully"
echo "Check logs/deployLogs.log and logs/appRecentLogs.log files for more details"
echo "Exit 1 with Success"
exit 1
fi
cnt=`expr $cnt + 1`
done
echo "Exit 2 with error"
exit 2
fi
|
Python
|
UTF-8
| 22,651
| 2.546875
| 3
|
[] |
no_license
|
'''
Encapsulate the input, output variables, as well as some default configurations
'''
from dataclasses import dataclass
from typing import List, Dict
import json
import numpy as np
@dataclass
class Default:
'''some default configurations
'''
alpha = 3.5 # the slope of wireless signal depreciation
std = 1 # the standard deviation of the zero mean shadowing
data_source = 'log-distance'
methods = ['dl']
sen_density = 600
num_intruder = 5
grid_length = 100
cell_length = 10
random_seed = 0
noise_floor = -80
power = 10
cell_percentage = 1
sample_per_label = 10
root_dir = 'data/images-1' # the root directory of the data
num_tx = 1
error_threshold = 0.2
min_dist = 1
max_dist = None
edge = 2
methods = ['deepmtl', 'deepmtl-simple', 'deepmtl-yolo', 'map', 'splot', 'dtxf']
server_ip = '0.0.0.0'
authorized = 0 # number of authorized users
@dataclass
class Input:
'''encapsulate the input variables
'''
methods: List[str]
experiment_num: int = -1
num_intruder: int = Default.num_intruder
data_source: str = Default.data_source
sensor_density: int = Default.sen_density
image_index: int = -1 # client send an index, and the server read the data locally according the index (client and server are on the same machine)
def to_json_str(self):
'''return json formated string
Return:
str
'''
inputdict = {
'experiment_num':self.experiment_num,
'num_intruder':self.num_intruder,
'image_index':self.image_index,
'methods':self.methods,
'data_source':self.data_source,
'sensor_density':self.sensor_density
}
return json.dumps(inputdict)
@classmethod
def from_json_str(cls, json_str):
'''Init an Input object from json string
Args:
json_str -- str
Return:
Input
'''
inputdict = json.loads(json_str)
return cls.from_json_dict(inputdict)
@classmethod
def from_json_dict(cls, json_dict):
'''Init an Input object from json dictionary
Args:
json_dict -- dict
Return:
Input
'''
myinput = cls([])
myinput.experiment_num = json_dict['experiment_num']
myinput.num_intruder = json_dict['num_intruder']
myinput.image_index = json_dict['image_index']
myinput.methods = json_dict['methods']
myinput.data_source = json_dict['data_source']
myinput.sensor_density = json_dict['sensor_density']
return myinput
def log(self):
'''log'''
return self.to_json_str()
@dataclass
class IpsnInput:
'''input data of IPSN20 localization method
'''
ground_truth: Dict
sensor_data: Dict
authorized: List = None
def to_json_str(self):
'''return json formated string
Return:
str
'''
inputdict = {
"ground_truth": self.ground_truth,
"sensor_data": self.sensor_data,
"authorized": self.authorized
}
return json.dumps(inputdict)
@classmethod
def from_file(cls, file):
'''init from a file
'''
with open(file, 'r') as f:
line = f.readline()
json_dict = json.loads(line)
return cls(json_dict['ground_truth'], json_dict['sensor_data'], json_dict['authorized'])
@dataclass
class Output:
'''encapsulate the output variables
'''
method: List[str]
error: List[float] # error of the detected TX
false_alarm: int
miss: int
preds: List
time: float
power_error: List[float]
def get_metric(self, metric):
'''get the evaluation metrics'''
if metric == 'error':
return round(np.mean(self.error), 3)
elif metric == 'miss':
return self.miss
elif metric == 'false_alarm':
return self.false_alarm
elif metric == 'time':
return self.time
elif metric == 'power_error':
return round(np.mean(np.abs(self.power_error)), 3)
else:
raise Exception('unknown metrics')
def get_pred_len(self):
'''Get the number of predicted TX
'''
size = len(self.preds)
return size if size != 0 else 1 # if len(self.preds) equals 0, then the false alarm rate will be zero anyway because the false alarm (numerator is 0)
def to_json_str(self):
'''return json formated string
Return:
str
'''
self.preds = [(round(x, 2), round(y, 2)) for x, y in self.preds]
self.power_error = [round(x, 4) for x in self.power_error]
self.time = round(self.time, 5)
outputdict = {
"method":self.method,
"error":self.error,
"false_alarm":self.false_alarm,
"miss":self.miss,
"preds":self.preds,
"time":self.time,
"power_error":self.power_error
}
return json.dumps(outputdict)
@classmethod
def from_json_str(cls, json_str):
'''Init an Output object from json
Args:
json_str -- str
Return:
Output
'''
outputdict = json.loads(json_str)
return cls.from_json_dict(outputdict)
@classmethod
def from_json_dict(cls, json_dict):
'''Init an Output object from json dictionary
Args:
json_dict -- dict
Return:
Output
'''
method = json_dict['method']
error = json_dict['error']
false_alarm = json_dict['false_alarm']
miss = json_dict['miss']
preds = json_dict['preds']
time = json_dict['time']
power_error = json_dict['power_error']
return cls(method, error, false_alarm, miss, preds, time, power_error)
def log(self):
return self.to_json_str()
@dataclass
class DataInfo:
'''the data set used for training and testing
'''
max_ntx: int
test_data: str
train_data: str
ipsn_cov_list: List # there are five ipsn dataset for five differnent set of sensors
ipsn_sensors_list: List
ipsn_hypothesis_list: List
translate_net: str # image translation
yolocust_def: str # our yolo cust model definition
yolocust_weights: str # our yolo cust model weights
yolo_def: str # yolo model definition
yolo_weights: str # yolo model weights
dtxf_cnn1: str
dtxf_cnn2_template: str
predpower_net: str = None
power_corrector: str = None
subtract_net: str = None
@classmethod
def naive_factory(cls, data_source):
'''factory'''
if data_source == 'data/205test': # the log-distancec based model
max_ntx = 10
test_data = 'data/205test'
train_data = 'data/205train'
ipsn_cov_list = ['data/200test-ipsn/cov', 'data/201test-ipsn/cov', 'data/202test-ipsn/cov', 'data/203test-ipsn/cov', 'data/204test-ipsn/cov']
ipsn_sen_list = ['data/200test-ipsn/sensors', 'data/201test-ipsn/sensors', 'data/202test-ipsn/sensors', 'data/203test-ipsn/sensors', 'data/204test-ipsn/sensors']
ipsn_hypo_list = ['data/200test-ipsn/hypothesis', 'data/201test-ipsn/hypothesis', 'data/202test-ipsn/hypothesis', 'data/203test-ipsn/hypothesis', 'data/204test-ipsn/hypothesis']
translate_net = 'model/model1-12.8-net5-norm-32.pt'
yolocust_def = '../PyTorch-YOLOv3/config/yolov3-custom.cfg'
yolocust_weights = '../PyTorch-YOLOv3/checkpoints_logdistance/yolov3_ckpt_5.pth'
yolo_def = '../PyTorch-YOLOv3/config/yolov3-custom-class.cfg'
yolo_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_class/yolov3_ckpt_5.pth'
dtxf_cnn1 = 'model_dtxf/12.12-cnn1-logdist.pt'
dtxf_cnn2_template = 'model_dtxf/12.12-cnn2-logdist_{}.pt'
return cls(max_ntx, test_data, train_data, ipsn_cov_list, ipsn_sen_list, ipsn_hypo_list, \
translate_net, yolocust_def, yolocust_weights, yolo_def, yolo_weights, dtxf_cnn1, dtxf_cnn2_template)
if data_source == 'data/305test': # the splat model
max_ntx = 10
test_data = 'data/305test'
train_data = 'data/305train'
ipsn_cov_list = ['data/300test-ipsn/cov', 'data/301test-ipsn/cov', 'data/302test-ipsn/cov', 'data/303test-ipsn/cov', 'data/304test-ipsn/cov']
ipsn_sen_list = ['data/300test-ipsn/sensors', 'data/301test-ipsn/sensors', 'data/302test-ipsn/sensors', 'data/303test-ipsn/sensors', 'data/304test-ipsn/sensors']
ipsn_hypo_list = ['data/300test-ipsn/hypothesis', 'data/301test-ipsn/hypothesis', 'data/302test-ipsn/hypothesis', 'data/303test-ipsn/hypothesis', 'data/304test-ipsn/hypothesis']
translate_net = 'model/model1-12.13-net5-norm-32-splat.pt'
yolocust_def = '../PyTorch-YOLOv3/config/yolov3-custom.cfg'
yolocust_weights = '../PyTorch-YOLOv3/checkpoints_splat/yolov3_ckpt_5.pth'
yolo_def = '../PyTorch-YOLOv3/config/yolov3-custom-class.cfg'
yolo_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_class/yolov3_ckpt_5.pth'
dtxf_cnn1 = 'model_dtxf/12.13-cnn1-splat.pt'
dtxf_cnn2_template = 'model_dtxf/12.13-cnn2-splat_{}.pt'
return cls(max_ntx, test_data, train_data, ipsn_cov_list, ipsn_sen_list, ipsn_hypo_list, \
translate_net, yolocust_def, yolocust_weights, yolo_def, yolo_weights, dtxf_cnn1, dtxf_cnn2_template)
# don't need to retrain the second part (YOLO): first part log-distance, second part splat
if data_source == 'data/205test_plus': # the log-distancec based model
max_ntx = 10
translate_net = 'model/model1-12.8-net5-norm-32.pt'
yolocust_def = '../PyTorch-YOLOv3/config/yolov3-custom.cfg'
yolocust_weights = '../PyTorch-YOLOv3/checkpoints/yolov3_ckpt_5.pth'
# below are useless
test_data = 'data/205test'
train_data = 'data/205train'
ipsn_cov_list = ['data/200test-ipsn/cov', 'data/201test-ipsn/cov', 'data/202test-ipsn/cov', 'data/203test-ipsn/cov', 'data/204test-ipsn/cov']
ipsn_sen_list = ['data/200test-ipsn/sensors', 'data/201test-ipsn/sensors', 'data/202test-ipsn/sensors', 'data/203test-ipsn/sensors', 'data/204test-ipsn/sensors']
ipsn_hypo_list = ['data/200test-ipsn/hypothesis', 'data/201test-ipsn/hypothesis', 'data/202test-ipsn/hypothesis', 'data/203test-ipsn/hypothesis', 'data/204test-ipsn/hypothesis']
yolo_def = '../PyTorch-YOLOv3/config/yolov3-custom-class.cfg'
yolo_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_class/yolov3_ckpt_5.pth'
dtxf_cnn1 = 'model_dtxf/12.12-cnn1-logdist.pt'
dtxf_cnn2_template = 'model_dtxf/12.12-cnn2-logdist_{}.pt'
return cls(max_ntx, test_data, train_data, ipsn_cov_list, ipsn_sen_list, ipsn_hypo_list, \
translate_net, yolocust_def, yolocust_weights, yolo_def, yolo_weights, dtxf_cnn1, dtxf_cnn2_template)
# don't need to retrain the second part (YOLO): first part splat, second part log-distance
if data_source == 'data/305test_plus': # the splat model
translate_net = 'model/model1-12.13-net5-norm-32-splat.pt'
yolocust_def = '../PyTorch-YOLOv3/config/yolov3-custom.cfg'
yolocust_weights = '../PyTorch-YOLOv3/checkpoints_logdistance/yolov3_ckpt_5.pth'
# below are useless
max_ntx = 10
test_data = 'data/305test'
train_data = 'data/305train'
ipsn_cov_list = ['data/300test-ipsn/cov', 'data/301test-ipsn/cov', 'data/302test-ipsn/cov', 'data/303test-ipsn/cov', 'data/304test-ipsn/cov']
ipsn_sen_list = ['data/300test-ipsn/sensors', 'data/301test-ipsn/sensors', 'data/302test-ipsn/sensors', 'data/303test-ipsn/sensors', 'data/304test-ipsn/sensors']
ipsn_hypo_list = ['data/300test-ipsn/hypothesis', 'data/301test-ipsn/hypothesis', 'data/302test-ipsn/hypothesis', 'data/303test-ipsn/hypothesis', 'data/304test-ipsn/hypothesis']
yolo_def = '../PyTorch-YOLOv3/config/yolov3-custom-class.cfg'
yolo_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_class/yolov3_ckpt_5.pth'
dtxf_cnn1 = 'model_dtxf/12.13-cnn1-splat.pt'
dtxf_cnn2_template = 'model_dtxf/12.13-cnn2-splat_{}.pt'
return cls(max_ntx, test_data, train_data, ipsn_cov_list, ipsn_sen_list, ipsn_hypo_list, \
translate_net, yolocust_def, yolocust_weights, yolo_def, yolo_weights, dtxf_cnn1, dtxf_cnn2_template)
if data_source == 'data/605test': # the logdistance model, 1 TX only
test_data = 'data/605test'
train_data = 'data/605train'
ipsn_cov_list = ['data/600test-ipsn/cov', 'data/601test-ipsn/cov', 'data/602test-ipsn/cov', 'data/603test-ipsn/cov', 'data/604test-ipsn/cov']
ipsn_sen_list = ['data/600test-ipsn/sensors', 'data/601test-ipsn/sensors', 'data/602test-ipsn/sensors', 'data/603test-ipsn/sensors', 'data/604test-ipsn/sensors']
ipsn_hypo_list = ['data/600test-ipsn/hypothesis', 'data/601test-ipsn/hypothesis', 'data/602test-ipsn/hypothesis', 'data/603test-ipsn/hypothesis', 'data/604test-ipsn/hypothesis']
yolocust_def = '../PyTorch-YOLOv3/config/yolov3-custom.cfg'
yolocust_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_predpower/yolov3_ckpt_5.pth'
translate_net = 'model/model1.9.26.0.02487.pt'
# below are useless
max_ntx = 10
yolo_def = '../PyTorch-YOLOv3/config/yolov3-custom-class.cfg'
yolo_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_class/yolov3_ckpt_5.pth'
dtxf_cnn1 = 'model_dtxf/12.13-cnn1-splat.pt'
dtxf_cnn2_template = 'model_dtxf/12.13-cnn2-splat_{}.pt'
return cls(max_ntx, test_data, train_data, ipsn_cov_list, ipsn_sen_list, ipsn_hypo_list, \
translate_net, yolocust_def, yolocust_weights, yolo_def, yolo_weights, dtxf_cnn1, dtxf_cnn2_template)
if data_source == 'data/705test': # the splat model, 1 TX only
test_data = 'data/705test'
train_data = 'data/705train'
ipsn_cov_list = ['data/700test-ipsn/cov', 'data/701test-ipsn/cov', 'data/702test-ipsn/cov', 'data/703test-ipsn/cov', 'data/704test-ipsn/cov']
ipsn_sen_list = ['data/700test-ipsn/sensors', 'data/701test-ipsn/sensors', 'data/702test-ipsn/sensors', 'data/703test-ipsn/sensors', 'data/704test-ipsn/sensors']
ipsn_hypo_list = ['data/700test-ipsn/hypothesis', 'data/701test-ipsn/hypothesis', 'data/702test-ipsn/hypothesis', 'data/703test-ipsn/hypothesis', 'data/704test-ipsn/hypothesis']
yolocust_def = '../PyTorch-YOLOv3/config/yolov3-custom.cfg'
yolocust_weights = '../PyTorch-YOLOv3/checkpoints_splat_predpower/yolov3_ckpt_5.pth'
translate_net = 'model/model1.9.27.splat.0.0520.pt'
# below are useless
max_ntx = 10
yolo_def = '../PyTorch-YOLOv3/config/yolov3-custom-class.cfg'
yolo_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_class/yolov3_ckpt_5.pth'
dtxf_cnn1 = 'model_dtxf/12.13-cnn1-splat.pt'
dtxf_cnn2_template = 'model_dtxf/12.13-cnn2-splat_{}.pt'
return cls(max_ntx, test_data, train_data, ipsn_cov_list, ipsn_sen_list, ipsn_hypo_list, \
translate_net, yolocust_def, yolocust_weights, yolo_def, yolo_weights, dtxf_cnn1, dtxf_cnn2_template)
if data_source == 'data/805test': # the logdistance model, up to 10 TX, the ipsn dataset keeps the same comparing to 600 series
test_data = 'data/805test'
train_data = 'data/805train'
ipsn_cov_list = ['data/600test-ipsn/cov', 'data/601test-ipsn/cov', 'data/602test-ipsn/cov', 'data/603test-ipsn/cov', 'data/604test-ipsn/cov']
ipsn_sen_list = ['data/600test-ipsn/sensors', 'data/601test-ipsn/sensors', 'data/602test-ipsn/sensors', 'data/603test-ipsn/sensors', 'data/604test-ipsn/sensors']
ipsn_hypo_list = ['data/600test-ipsn/hypothesis', 'data/601test-ipsn/hypothesis', 'data/602test-ipsn/hypothesis', 'data/603test-ipsn/hypothesis', 'data/604test-ipsn/hypothesis']
yolocust_def = '../PyTorch-YOLOv3/config/yolov3-custom.cfg'
yolocust_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_predpower/yolov3_ckpt_5.pth'
translate_net = 'model/model1.9.26.0.02487.pt'
predpower_net = 'model/predictor5-9.24-0.2366.pt'
power_corrector = 'model/ridgereg_logdist.sav'
# below are useless
max_ntx = 10
yolo_def = '../PyTorch-YOLOv3/config/yolov3-custom-class.cfg'
yolo_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_class/yolov3_ckpt_5.pth'
dtxf_cnn1 = 'model_dtxf/12.13-cnn1-splat.pt'
dtxf_cnn2_template = 'model_dtxf/12.13-cnn2-splat_{}.pt'
return cls(max_ntx, test_data, train_data, ipsn_cov_list, ipsn_sen_list, ipsn_hypo_list, \
translate_net, yolocust_def, yolocust_weights, yolo_def, yolo_weights, dtxf_cnn1, dtxf_cnn2_template, predpower_net, power_corrector)
if data_source == 'data/905test': # the splat model, up to 10 TX, the ipsn dataset keeps the same comparing to 700 series
test_data = 'data/905test'
train_data = 'data/905train'
ipsn_cov_list = ['data/700test-ipsn/cov', 'data/701test-ipsn/cov', 'data/702test-ipsn/cov', 'data/703test-ipsn/cov', 'data/704test-ipsn/cov']
ipsn_sen_list = ['data/700test-ipsn/sensors', 'data/701test-ipsn/sensors', 'data/702test-ipsn/sensors', 'data/703test-ipsn/sensors', 'data/704test-ipsn/sensors']
ipsn_hypo_list = ['data/700test-ipsn/hypothesis', 'data/701test-ipsn/hypothesis', 'data/702test-ipsn/hypothesis', 'data/703test-ipsn/hypothesis', 'data/704test-ipsn/hypothesis']
yolocust_def = '../PyTorch-YOLOv3/config/yolov3-custom.cfg'
yolocust_weights = '../PyTorch-YOLOv3/checkpoints_splat_predpower/yolov3_ckpt_5.pth'
translate_net = 'model/model1.9.27.splat.0.0520.pt'
predpower_net = 'model/predictor5-9.25-splat-0.1562.pt'
power_corrector = 'model/ridgereg_splat.sav'
# below are useless
max_ntx = 10
yolo_def = '../PyTorch-YOLOv3/config/yolov3-custom-class.cfg'
yolo_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_class/yolov3_ckpt_5.pth'
dtxf_cnn1 = 'model_dtxf/12.13-cnn1-splat.pt'
dtxf_cnn2_template = 'model_dtxf/12.13-cnn2-splat_{}.pt'
return cls(max_ntx, test_data, train_data, ipsn_cov_list, ipsn_sen_list, ipsn_hypo_list, \
translate_net, yolocust_def, yolocust_weights, yolo_def, yolo_weights, dtxf_cnn1, dtxf_cnn2_template, predpower_net, power_corrector)
if data_source == 'data/1005test': # the splat model, using the same parameters comparing to 305test, except for adding 5 authorized users
max_ntx = 10
test_data = 'data/1005test'
train_data = 'data/1005train'
ipsn_cov_list = ['data/300test-ipsn/cov', 'data/301test-ipsn/cov', 'data/302test-ipsn/cov', 'data/303test-ipsn/cov', 'data/304test-ipsn/cov']
ipsn_sen_list = ['data/300test-ipsn/sensors', 'data/301test-ipsn/sensors', 'data/302test-ipsn/sensors', 'data/303test-ipsn/sensors', 'data/304test-ipsn/sensors']
ipsn_hypo_list = ['data/300test-ipsn/hypothesis', 'data/301test-ipsn/hypothesis', 'data/302test-ipsn/hypothesis', 'data/303test-ipsn/hypothesis', 'data/304test-ipsn/hypothesis']
translate_net = 'model/model1-12.13-net5-norm-32-splat.pt'
yolocust_def = '../PyTorch-YOLOv3/config/yolov3-custom.cfg'
yolocust_weights = '../PyTorch-YOLOv3/checkpoints_splat/yolov3_ckpt_5.pth'
subtract_net = 'model/subtractnet3-10.7-pu_guassian.pt'
# below are useless
yolo_def = '../PyTorch-YOLOv3/config/yolov3-custom-class.cfg'
yolo_weights = '../PyTorch-YOLOv3/checkpoints_logdistance_class/yolov3_ckpt_5.pth'
dtxf_cnn1 = 'model_dtxf/12.13-cnn1-splat.pt'
dtxf_cnn2_template = 'model_dtxf/12.13-cnn2-splat_{}.pt'
return cls(max_ntx, test_data, train_data, ipsn_cov_list, ipsn_sen_list, ipsn_hypo_list, \
translate_net, yolocust_def, yolocust_weights, yolo_def, yolo_weights, dtxf_cnn1, dtxf_cnn2_template, None, None, subtract_net)
class IOUtility:
'''input/output utility'''
@staticmethod
def read_logs(logs):
'''reading logs
Args:
logs -- list<str> -- a list of filenames
Return:
data -- list<(Input, dic{str:Output}>
'''
data = []
for log in logs:
f = open(log, 'r')
while True:
line = f.readline()
if line == '':
break
myinput = Input.from_json_str(line)
output_by_method = {}
line = f.readline()
while line != '' and line != '\n':
output = Output.from_json_str(line)
output_by_method[output.method] = output
line = f.readline()
data.append((myinput, output_by_method))
return data
|
TypeScript
|
UTF-8
| 1,079
| 2.703125
| 3
|
[] |
no_license
|
import mongoose from "mongoose";
export interface ScanAttrs {
_id?: mongoose.Schema.Types.ObjectId;
scanContent: string;
timeStamp: Date;
errorCode?: string;
_line?: mongoose.Schema.Types.ObjectId;
_user?: mongoose.Schema.Types.ObjectId;
}
interface ScanModel extends mongoose.Model<ScanDoc> {
build(attrs: ScanAttrs): ScanDoc;
}
interface ScanDoc extends mongoose.Document {
_id: mongoose.Schema.Types.ObjectId;
scanContent: string;
timeStamp: Date;
errorCode?: string;
_line?: mongoose.Schema.Types.ObjectId;
_user?: mongoose.Schema.Types.ObjectId;
}
export const scanSchema = new mongoose.Schema({
scanContent: {
type: String,
required: true,
index: true,
sparse: true,
},
timeStamp: { type: Date, default: Date.now },
errorCode: {
type: String,
required: true,
index: true,
default: "e000",
},
_line: { type: mongoose.Schema.Types.ObjectId, ref: "Line" },
_user: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
});
export const Scan = mongoose.model<ScanDoc, ScanModel>("Scan", scanSchema);
|
Java
|
UTF-8
| 255
| 2.21875
| 2
|
[] |
no_license
|
package org.cen.vision.filters;
public class FilterInterruptor {
private boolean interrupted = false;
public boolean isInterrupted() {
return interrupted;
}
public void setInterrupted(boolean interrupted) {
this.interrupted = interrupted;
}
}
|
JavaScript
|
UTF-8
| 7,882
| 2.53125
| 3
|
[] |
no_license
|
// components/commoditSpecChoose/index.js
import { getShopDetailSkuList } from "../../services/home/shop";
Component({
/**
* 组件的属性列表
*/
properties: {
detail: {
type: Object,
value: {}
},
show: {
type: Boolean,
value: false
}
},
/**
* 组件的初始数据
*/
data: {
initList: [], // 后端返回的原始数据, 用来最后获取sku
select: {}, // 选中的数据 sku
specList: [], // 处理过的数据,用来渲染页面
// specList: [{
// title: '标题',
// list: ['红色', '黄色'],
// active: 0, // 选中
// unActiveAbleList: [], // 未选中的可用列表
// activeAbleList: [], // 已选中的可用列表
// }]
skuAllStr: '', // 所有的sku数据字符串,用来查询可选选项
count: 1
},
lifetimes: {
attached() {
this.getShopDetailSkuList();
}
},
methods: {
getShopDetailSkuList: function () {
getShopDetailSkuList({id: this.properties.detail.id}).then(res => {
this.data.initList = res;
let result = this.conversionData(res.map(i => {
this.data.skuAllStr += i.skuStr;
return i.skuStr;
}));
this.setData({
specList: result.map(i => {
return {
title: i.title,
list: i.list,
active: i.list.length===1?0:-1,
unActiveAbleList: i.list,
activeAbleList: i.list
}
})
});
// 检查 规格
this.checkAbleSpec();
});
},
// 将后端传过来的数据 转化成二维数组
conversionData: function (arry) {
let map = new Map();
for (let str of arry) {
let sku = JSON.parse(str);
let keys = Object.keys(sku);
for (let i = 0; i < keys.length; i++) {
let set = map.get(keys[i]) || new Set();
set.add(sku[keys[i]])
map.set(keys[i], set)
}
}
return [...map].map(i => {
return {
title: i[0],
list: [...i[1]],
}
});
},
/**
* 选中了某一规格 步骤1 将方框置成红色
*/
selectedSpec: function (e) {
if (e.currentTarget.dataset.disabled) {
return;
}
let gIndex = e.currentTarget.dataset.gi;
let index = e.currentTarget.dataset.i;
if (this.data.specList[gIndex].active === index) {
this.data.specList[gIndex].active = -1;
} else {
this.data.specList[gIndex].active = index;
}
this.checkAbleSpec();
},
/**
* 检查 可用规格的列表 步骤2
* 规则1 ,未选中的可选列表 按照已选中的数据去搜索
* 规则2,已选中的可选列表 按照排除本身后的已选中数据去搜索
*/
checkAbleSpec: function () {
//规则1 获取未选中可用的规格
let active = '[^{}]*';
for (let i = 0; i < this.data.specList.length; i++) {
if (this.data.specList[i].active >= 0) {
// active[this.data.specList[i].title] = this.data.specList[i].list[this.data.specList[i].active];
active = active + `"${this.data.specList[i].title}":"${this.data.specList[i].list[this.data.specList[i].active]}"` + '[^{}]*'
}
}
let reg = new RegExp('\{' + active + '\}', 'g');
let result = this.data.skuAllStr.match(reg);
let unActiveList = this.conversionData(result); // [{list: []}]
//规则2 获取 已选中 可用规格列表
let activeList = [];
// 取得所有选中的列表,封装成map
let searchList = new Map(this.data.specList.filter(i => {
return i.active !== -1;
}).map(i => {
return [i.title, i.list[i.active]]
}));
// 循环获取 每一个已选中列表的 可选列表
for (let i = 0; i < this.data.specList.length; i++) {
if (this.data.specList[i].active !== -1) {
// 复制一份选中的 数据
let searchCurrent = new Map(searchList);
// 删除自己当前选中的数据,剩下的就是其他选中的数据
searchCurrent.delete(this.data.specList[i].title);
// 拼装搜索规则2
let selectReg = '[^{}]*';
for (let [key, value] of searchCurrent.entries()) {
selectReg += `"${key}":"${value}"` + '[^{}]*';
}
let reg2 = new RegExp('\{' + selectReg + '\}', 'g');
let result2 = this.data.skuAllStr.match(reg2); // [{"颜色":"红色","数量":"4袋装","尺寸":"S"}]
// 提取数组中 当前规格的所有可用
let currentSet = new Set();
result2.forEach(item => {
let obj = JSON.parse(item);
currentSet.add(obj[this.data.specList[i].title])
})
activeList.push({list: [...currentSet]});
} else {
// 如果是未选中,则占位即可。因为未选中,这里不定义,在规则1中定义
activeList.push({list: []})
}
}
// 赋值,未选中/已选中 可用列表
for (let i = 0; i < this.data.specList.length; i++) {
this.data.specList[i].unActiveAbleList = unActiveList[i].list;
this.data.specList[i].activeAbleList = activeList[i].list;
}
// 如果可用sku 只有一条
if (result.length === 1) {
this.data.select = this.data.initList.find(i => {
return i.skuStr === result[0]
})
if(this.data.count > this.data.select.quantity){
this.data.count = this.data.select.quantity;
}
} else {
this.data.select = {};
}
this.setData({
specList: this.data.specList,
select: this.data.select,
count: this.data.count
})
},
countChange: function (e) {
let count = (this.data.count + e.currentTarget.dataset.num) || 1;
if(count > (this.data.select.quantity||this.data.detail.quantity)){
count = (this.data.select.quantity||this.data.detail.quantity);
}
this.setData({
count: count
})
},
confirm: function () {
let all = this.data.specList.every(i => {
return i.active !== -1;
})
if (all) {
this.triggerEvent('confirm', {sku: this.data.select, count: this.data.count})
} else {
wx.showToast({
title: '请选择商品规格',
icon: 'none'
})
}
},
cancel: function () {
this.triggerEvent('cancel')
}
},
})
|
Java
|
UTF-8
| 2,259
| 2.0625
| 2
|
[] |
no_license
|
package fr.toinetoine1.practice.events;
import fr.badblock.gameapi.BadListener;
import fr.badblock.gameapi.players.BadblockPlayer;
import fr.toinetoine1.practice.Practice;
import fr.toinetoine1.practice.data.PPlayer;
import fr.toinetoine1.practice.database.request.DataRequest;
import fr.toinetoine1.practice.scoreboard.PracticeScoreboard;
import fr.toinetoine1.practice.utils.HotBarSelector;
import org.bukkit.GameMode;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scheduler.BukkitRunnable;
public class PlayerJoinListener extends BadListener {
@EventHandler
public void onJoin(PlayerJoinEvent event) {
BadblockPlayer badblockPlayer = (BadblockPlayer) event.getPlayer();
PPlayer pPlayer = DataRequest.selectUser(badblockPlayer);
badblockPlayer.setGameMode(GameMode.ADVENTURE);
for (PotionEffect effect : badblockPlayer.getActivePotionEffects())
badblockPlayer.removePotionEffect(effect.getType());
event.setJoinMessage("");
((CraftPlayer) badblockPlayer).getHandle().setAbsorptionHearts(0.0f);
badblockPlayer.teleport(Practice.getSpawnLoc());
PracticeScoreboard practiceScoreboard = new PracticeScoreboard(badblockPlayer);
pPlayer.setScoreboard(practiceScoreboard);
pPlayer.setCurrentTime(System.currentTimeMillis());
HotBarSelector.giveSelector(badblockPlayer);
new BukkitRunnable() {
@Override
public void run() {
badblockPlayer.sendMessage(Practice.PREFIX + "§6Bienvenue sur la Bêta-test du §bPractice");
badblockPlayer.sendMessage(Practice.PREFIX + "§6Elle est disponible dans le but de le perfectionner et de trouver tous les potentiels bugs");
badblockPlayer.sendMessage(Practice.PREFIX + "§6Si vous trouvez un bug §cmineur§6, merci de le report sur le discord staff dans le salon #bugs");
badblockPlayer.sendMessage(Practice.PREFIX + "§6Si le bug est §cmajeur§6, envoyez-un MP à Toinetoine1 ;)");
}
}.runTaskLater(Practice.getInstance(), 5);
}
}
|
C++
|
UTF-8
| 1,251
| 3.78125
| 4
|
[] |
no_license
|
// searching -- regular -- O(n)
// searching -- bst -- O(log n)
// insertion -- regualr -- O(n)
// insertion -- bst -- O(n)
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *left, *right;
};
Node *new_node(int value){
Node *temp = new Node;
temp->data = value;
temp->left = temp->right = NULL;
return temp;
}
void inorder(Node *root){
if(root==NULL) return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
Node* search(Node *root, int value){
if(root==NULL || root->data == value){
return root;
}
if(value<root->data)
return search(root->left, value);
return search(root->right, value);
}
Node* insert(Node *node, int value){
if(node==NULL) return new_node(value);
if(value<node->data)
node->left = insert(node->left, value);
else if(value>node->data)
node->right = insert(node->right, value);
return node;
}
int main(){
Node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
inorder(root);
Node *s = search(root, 40);
if(s->data == 40){
cout<<"\nItem found";
}
else cout<<"\nItem not found";
return 0;
}
|
PHP
|
UTF-8
| 1,775
| 2.609375
| 3
|
[] |
no_license
|
<?php
include("prod_conn.php");
//query for retreving individual certificates within a project
$query = "SELECT
DATE_FORMAT(PAYMENT_DATE,'%d-%b-%Y') \"Donation Date\",
DISPLAYNAME \"Donor Name\",
FORMAT(AMOUNT_FOR_PROJECT+AMOUNT_FOR_OPERATIONS_GRANT,0) \"Total Donation =\",
FORMAT(AMOUNT_FOR_PROJECT,0) \"Project Donation +\",
FORMAT(AMOUNT_FOR_OPERATIONS_GRANT,0) \"Donation for UC\",
VILLAGE_TOWN \"Donor Location\",
LOCATION \" Project Location\",
PROJECT_TITLE \"Project\"
FROM
(SELECT
CERTIFICATE_ID,
PAYMENT_DATE,
DISPLAYNAME,
AMOUNT_FOR_PROJECT,
AMOUNT_FOR_OPERATIONS_GRANT,
VILLAGE_TOWN
FROM DONORS JOIN POSTPAY_CERTIFICATES USING (DONOR_ID) JOIN PAYMENTS USING (PAYMENT_ID)
WHERE DONOR_ID=".$_SESSION['SESS_DONOR_ID']."
ORDER BY PAYMENT_DATE DESC)INFO
LEFT OUTER JOIN PROJECT_CERTIFICATES USING (CERTIFICATE_ID) LEFT OUTER JOIN PROJECTS USING (PROJECT_ID)";
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbdatabase");
$result = mysql_query($query);
//loop thru the field names to print the correct headers
$i = 0;
echo "<table style='font-size:12px'>";
echo "<thead><tr>";
while ($i < mysql_num_fields($result)){
echo "<th bgcolor=\"CCCCFF\">". mysql_field_name($result, $i) ."</th>";
$i++;
}
echo "</thead></tr>";
//display the data
$i = 1;
while ($rows = mysql_fetch_array($result,MYSQL_ASSOC)){
// variable for coloring oddeven rows
$oddeven = $i & 1;
if ($oddeven == 0){$color = "CCCFFF";}
else {$color = "FFFFFF";}
echo "<tr bgcolor=\"$color\">";
foreach ($rows as $data){echo "<td align=\"right\">".$data ."</td>";}
echo "</tr>";
$i++;
}
echo "</table>";
?>
|
C++
|
UTF-8
| 2,555
| 2.5625
| 3
|
[] |
no_license
|
#include <cstdio>
#include <vector>
#include <iostream>
#include "parsing.h"
enum opcode {
AND = 0x00,
OR = 0x01,
XOR = 0x02,
NOT = 0x03,
ADD = 0x04,
ADC = 0x05,
SUB = 0x06,
MULT = 0x07,
DIV = 0x08,
CMP = 0x09,
XCHG = 0x0a,
MOV = 0x0b,
LOAD = 0x0c,
STORE = 0x0d,
PUSH = 0x0e,
POP = 0x0f,
MOVIU = 0x10,
ADDI = 0x11,
ADDIU = 0x12,
CMPIU = 0x13,
SHIFT = 0x14,
JL = 0x15,
JNE = 0x16,
JR = 0x17,
JSR = 0x18,
UNUSED_19 = 0x19,
JMP = 0x1a,
SYS = 0x1b,
SWAPCC = 0x1c,
UNUSED_1d = 0x1d,
UNUSED_1e = 0x1e,
HALT = 0x1f,
};
typedef unsigned int uint;
int main()
{
int l = 1;
printf("signed relative 27 bits, shift 2\n");
{
uint addr = 0x100;
std::vector<uint> values = {0, 1, addr + 0, addr + 0x100, 1 << 28, 1 << 29, (1 << 29) + addr};
for(uint& u : values) {
printf("%08X -> %08X\n", u, instr_infos[opcode::JL].Encode(u, l++, addr));
}
}
{
uint addr = (1 << 29) + 4;
std::vector<uint> values = {0};
for(uint& u : values) {
printf("%08X -> %08X\n", u, instr_infos[opcode::JL].Encode(u, l++, addr));
}
}
printf("signed relative 24 bits, shift 2\n");
{
uint addr = 0x100;
std::vector<uint> values = {0, 1, addr + 0, addr + 0x100, 1 << 25, 1 << 26, (1 << 26) + addr};
for(uint& u : values) {
printf("%08X -> %08X\n", u, instr_infos[opcode::JSR].Encode(u, l++, addr));
}
}
{
uint addr = (1 << 26) + 4;
std::vector<uint> values = {0};
for(uint& u : values) {
printf("%08X -> %08X\n", u, instr_infos[opcode::JSR].Encode(u, l++, addr));
}
}
printf("signed 24 bits\n");
{
std::vector<uint> values = {0, 1, 1 << 24, (uint)(-1), (uint)(-(1 << 24) + 1), (uint)(-(1 << 24) - 1)};
for(uint& u : values) {
printf("%08X -> %08X\n", u, instr_infos[opcode::ADDI].Encode(u, l++, 0));
}
}
printf("unsigned 24 bits\n");
{
std::vector<uint> values = {0, 1, (1 << 24) - 1, 1 << 24, };
for(uint& u : values) {
printf("%08X -> %08X\n", u, instr_infos[opcode::ADDIU].Encode(u, l++, 0));
}
}
printf("unsigned 16 bits\n");
{
std::vector<uint> values = {0, 1, (1 << 16) - 1, 1 << 16};
for(uint& u : values) {
printf("%08X -> %08X\n", u, instr_infos[opcode::MOVIU].Encode(u, l++, 0));
}
}
}
|
Python
|
UTF-8
| 593
| 2.96875
| 3
|
[
"Apache-2.0"
] |
permissive
|
#Print unusual street names from the dataset
expected = ["Street", "Avenue", "Boulevard", "Drive", "Court", "Place", "Square", "Lane", "Road",
"Trail", "Parkway", "Commons", "Circle", "Way", "Extension", "Turnpike", "Broadway", "Terrace", "Plaza", "View"]
osm_file = open("albany.osm", "r")
for event, elem in ET.iterparse(osm_file):
if is_street_name(elem):
street_name = elem.attrib['v']
m = street_type_re.search(street_name)
if m:
street_type = m.group()
if street_type not in expected:
print street_name
|
Ruby
|
UTF-8
| 296
| 3.609375
| 4
|
[] |
no_license
|
class Character
attr_reader(:name, :nick_name, :occupation)
def initialize(name, nick_name, occupation)
@name = name
@nick_name = nick_name
@occupation = occupation
end
def introduce
return "I'm #{name} but you can call me #{nick_name}. I'm a #{occupation}"
end
end
|
Java
|
UTF-8
| 2,429
| 2.203125
| 2
|
[] |
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 fr.afcepf.atod.wine.business.order.impl;
import fr.afcepf.atod.vin.data.exception.WineException;
import fr.afcepf.atod.wine.business.order.api.IBuOrder;
import fr.afcepf.atod.wine.data.order.api.IDaoOrder;
import fr.afcepf.atod.wine.data.order.impl.DaoOrder;
import fr.afcepf.atod.wine.entity.Customer;
import fr.afcepf.atod.wine.entity.Order;
import fr.afcepf.atod.wine.entity.OrderDetail;
import fr.afcepf.atod.wine.entity.Product;
import java.util.HashSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author ronan
*/
@Service
public class BuOrder implements IBuOrder {
/**
* quantity initial = 1
*/
private static final int QUANTITY_INIT = 1;
@Autowired
private IDaoOrder daoOrder;
/**
*
* @param order
* @param product
* @return
* @throws WineException
*/
@Override
public Order addItemCart(Order order, Product product) throws WineException {
boolean itemFoundInCart = false;
if (order.getOrdersDetail()== null) {
order.setOrdersDetail(new HashSet<OrderDetail>());
insertNewOrderDetail(order, product);
} else {
for (OrderDetail od : order.getOrdersDetail()) {
if (od.getProductOrdered().getId() == product.getId()) {
od.setQuantite(od.getQuantite() + 1);
itemFoundInCart = true;
}
}
if (itemFoundInCart == false) {
insertNewOrderDetail(order, product);
}
}
return order;
}
private void insertNewOrderDetail(Order order, Product product) {
order.getOrdersDetail().add(
new OrderDetail(null,QUANTITY_INIT, order, product));
}
/**
* enregister une nouvelle commande a la base
*/
@Override
public Order addNewOrder(Order order) throws WineException {
daoOrder.insertObj(order);
return order;
}
@Override
public Order getLastOrderByCustomer(Customer customer) {
return daoOrder.getLastOrderByCustomer(customer);
}
}
|
Python
|
UTF-8
| 902
| 4.3125
| 4
|
[] |
no_license
|
"""
File: ds09.py
Author: Ali Cope
Use Hash Tables (sets and dictionaries) in Python to solve problems.
Assignment: Write a program to read through a census file and keep track of the number of people in different education levels.
"""
def get_filename():
name = input("Please enter a filename: ")
return name
def readFile(filename):
#create hash table
education_level = {}
f = open(filename, "r")
for line in f:
x = line.split(",")
education = x[3]
if education in education_level:
education_level[education] += 1
else:
education_level[education] = 1
f.close()
return education_level
def main():
file = get_filename()
results = readFile(file)
for level, number in results.items():
print("{} -- {}".format(number, level))
if __name__ == "__main__":
main()
|
Shell
|
UTF-8
| 323
| 3.03125
| 3
|
[] |
no_license
|
#!/bin/bash
if [ -z $(docker images -q 03_sample:latest) ]
then
# Preventing error ADD failed: Forbidden path outside the build context: ../shared/conf/httpd.properties
cp -r ../shared/conf .
cp -r ../shared/www .
docker build -t 03_sample .
rm -rf ./conf ./www # Cleanup
fi
docker run -it 03_sample
|
SQL
|
UTF-8
| 40,415
| 2.703125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
-- phpMyAdmin SQL Dump
-- version 4.7.7
-- https://www.phpmyadmin.net/
--
-- Host: localhost:3306
-- Generation Time: Mar 15, 2018 at 01:18 PM
-- Server version: 5.6.38
-- PHP Version: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `wpsuppor_cnk`
--
-- --------------------------------------------------------
--
-- Table structure for table `prd_customer`
--
CREATE TABLE `prd_customer` (
`id` int(11) NOT NULL,
`submission_id` int(11) NOT NULL,
`customer_name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`contact` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `prd_customer`
--
INSERT INTO `prd_customer` (`id`, `submission_id`, `customer_name`, `email`, `address`, `contact`) VALUES
(26, 2, 'Hong Ye', 'hongye@wp.com', 'Hougang', 9456875),
(27, 2, 'Alvin', 'alvin@wp.com', 'Punggol', 98989852),
(28, 1, 'Sandra', 'sandra@wp.com', 'Jalan Bidadari', 8526326),
(29, 1, 'Yu Ting', 'yuting@wp.com', 'Commonwealth', 95252632),
(30, 1, 'asdas', 'asd@s.com', 'asdasd', 23232),
(31, 1, 'Harry', 'harry@wp.com', 'Holland', 98585858),
(32, 1, 'Catherina Woods', 'catwoods@gmail.com', 'Woodlands', 91112112),
(33, 2, 'Test', 'test@customer.com', 'NY', 2143105984),
(34, 2, 'test2', 'test2@customer.com', 'la', 2133354123),
(35, 1, 'dj', 'dj@gmail.com', '1203', 123123),
(36, 1, 'ABc', 'abc@gmail.com', '1020393', 123456),
(37, 1, 'rahu', 'ra@gmail.cm', 'sdfasdf', 0),
(38, 1, 'John', 'john@gmail.com', 'Jurong', 98888888),
(39, 1, 'asfdsf', 'asdsad@adsad.com', 'sakldjsldjk', 2147483647),
(40, 2, '123', '123@23123.com', '23123', 2312),
(41, 1, 'test', 'test@gmail.com', 'retrtwte', 999999999),
(42, 1, 'Nihar', 'nihar@testmail.com', 'demo address', 2147483647),
(43, 1, 'sample', 'sample@kishan.com', 'abc\r\ngandhinagar3457', 1324657987),
(44, 2, 'demo', 'd@a.com', 'gyycfy', 2147483647),
(45, 2, 'sample', 'sample@kishan.com', 'dfgcfh', 2147483647),
(46, 2, '1', '1@2.com', '1', 1),
(47, 2, '1', '1@2.com', '2', 2),
(48, 1, 'Nazreen', 'nazreen@webpuppies.com.sg', 'Jurong West St 81', 2147483647),
(49, 1, 'John Doe', 'johndoe@webpuppies.com', 'Telok Blangah', 97875882),
(50, 1, 'Gary', 'gary@product.com', 'Gombak', 98765432),
(51, 1, 'Ronaldo', 'Ronaldo@yahoo.com', 'Brazil', 91613156),
(52, 1, 'WEB PUPS SUPPORT', 'support@webpuppies.com.sg', '138 ROBINSON', 66667777),
(53, 1, 'John', 'yiicakephp@gmail.com', 'test', 12121212),
(54, 1, 'Naz', 'nazreen@webpuppies.com.sg', 'Jurong West St 81', 94879740),
(55, 1, 'Tom', 'tom@gmail.com', 'Tom\'s House', 93888832),
(56, 1, 'Helen', 'Helen@mail.com', 'North Bridge Rd', 98876567),
(57, 1, 'Pauline', 'pauline@mail.com', 'East Coast Rd', 9009009),
(58, 1, 'fieztech', 'dev@fieztech.com', 'Testing qw 12', 2147483647),
(59, 1, 'leekim', 'leekim@webpuppies.com.sg', '123lokju', 81359722),
(60, 1, 'test', 'kenneth.lim@charleskeith.com', 'test', 91067433),
(61, 1, 'qwdsd', 'asdas@wdw.com', 'wqde', 8678234),
(62, 1, 'Bakar', 'bakar@gmail.com', 'kllk;kl', 98515151),
(63, 1, 'Test', 'Kenneth.lim@charleskeith.com', 'Test', 91067433),
(64, 2, 'A', 'Dapit.kesuma@charleskeith.com', 'A', 83759377),
(65, 1, 'David Tan', 'David.tan@charleskeith.com', 'Tai Seng', 87654321),
(66, 1, 'Cass', 'Cassandra.heng@charleskeith.com', 'London', 24681012),
(67, 1, 'Pei Fen', 'pf@cnk.com', 'Hougang Ave 5', 90000923),
(68, 1, 'Jumanji', 'rock@yahoo.com', 'Horthorne Rd', 97878787);
-- --------------------------------------------------------
--
-- Table structure for table `prd_defects`
--
CREATE TABLE `prd_defects` (
`id` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`defect_no` int(11) DEFAULT NULL,
`outlet_name` varchar(255) DEFAULT NULL,
`status` int(11) NOT NULL DEFAULT '1',
`initial_date` datetime DEFAULT NULL,
`updated_date` datetime DEFAULT NULL,
`u_by` int(11) DEFAULT NULL,
`customer_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `prd_defects`
--
INSERT INTO `prd_defects` (`id`, `user_id`, `defect_no`, `outlet_name`, `status`, `initial_date`, `updated_date`, `u_by`, `customer_id`) VALUES
(64, 1, 1064, 'CQM', 5, '2018-01-19 15:33:25', '2018-01-19 18:49:45', 1, 55),
(65, 1, 1065, 'Pedro NEX (PNX)', 4, '2018-01-23 13:39:15', '2018-03-08 19:42:33', 1, 56),
(66, 1, 1066, 'Pedro NEX (PNX)', 3, '2018-01-23 15:51:43', '2018-02-28 18:20:26', 9, 57),
(76, 1, 1076, 'Charles & Keith Changi Airport Terminal 4 (T4)', 3, '2018-03-08 12:47:21', '2018-03-08 12:47:21', 1, 67),
(77, 1, 1077, 'Charles & Keith IMM (IMM)', 2, '2018-03-15 13:09:40', '2018-03-15 13:09:40', 1, 68);
-- --------------------------------------------------------
--
-- Table structure for table `prd_defects_details`
--
CREATE TABLE `prd_defects_details` (
`id` int(11) NOT NULL,
`defect_product_id` int(11) DEFAULT NULL,
`defect_id` int(11) DEFAULT NULL,
`image` varchar(255) DEFAULT NULL,
`category_id` int(11) DEFAULT NULL,
`defect_type_id` int(11) DEFAULT NULL,
`notes` text,
`what_done_for_repair` text,
`repair_image` varchar(255) DEFAULT NULL,
`status` int(11) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `prd_defects_details`
--
INSERT INTO `prd_defects_details` (`id`, `defect_product_id`, `defect_id`, `image`, `category_id`, `defect_type_id`, `notes`, `what_done_for_repair`, `repair_image`, `status`) VALUES
(1, 18, 1, 'uploads/2e3cc77e494827b58a1bb24f073a9cb5.jpg', 40, 40, 'the shoe have sole issues', 'fix the sole', 'uploads/8e061f79a5740ffda7e2652e9bd634b6.jpg', 2),
(2, 18, 1, 'uploads/e781bb9257418da162319fe323b03281.jpg', 11, 11, 'the design not nice', 'then go buy other brands', 'uploads/85e722e88aaf5c45f61167c1d3f74ebb.jpg', 2),
(3, 19, 1, 'uploads/68d035d67376fd3cdb23b21aaace0463.jpg', 19, 23, 'it is not waterproof', 'waterproof padding added', 'uploads/c618943da276366d9807dc8d2162a74c.jpg', 2),
(4, 1, 1, 'uploads/1015a1622949c1ba1e2edfb6313c9d52.jpg', 1, 1, 'it gets oxidised very fast', 'de-oxidised the fabric', 'uploads/0ebfacabf1c1500daea224e3b08e7bf6.jpg', 1),
(5, 21, 20, 'uploads/4b9ac725b6446354bc4676706936f8bf.sig', 12, NULL, 'aasdfasdasdf', NULL, NULL, 1),
(6, 22, 21, 'uploads/f4f8d343937ed907ec89a79433c62176.jpg', 6, NULL, 'asdasdad', NULL, NULL, 1),
(7, 23, 22, 'uploads/f5de26b6018b4bd06a7263f0bc4bfba4.jpg', 1, NULL, 'asdasd', NULL, NULL, 1),
(8, 24, 23, 'uploads/198053d8a6ba41b2ea72ab6a903f2a8a.jpg', 2, NULL, 'dsfsdfds', NULL, NULL, 1),
(9, 25, 25, 'uploads/e83331de6b06bf18cd376f24a533591b.manifest', 27, NULL, '123456', NULL, NULL, 1),
(10, 26, 26, 'uploads/1c1da6449b1556d952a88a62b380ef51.manifest', 1, NULL, 'gjjjjjjjjjjjh', NULL, NULL, 1),
(11, 27, 27, 'uploads/08af17ae0347c380507a5017b293da3f.jpg', 2, NULL, 'hgvhg', NULL, NULL, 1),
(12, 28, 29, NULL, 1, NULL, '', NULL, NULL, 1),
(13, 29, 8, 'uploads/00806ab050de39d233d7b6650123ea5e.jpg', 27, NULL, 'hjhgjh', NULL, NULL, 1),
(14, 30, 8, 'uploads/af64f626a8568f4876d2ff10fec3c06c.jpg', 1, NULL, 'hjkgkjhk', NULL, NULL, 1),
(15, 31, 24, 'uploads/467972115549ba82d043a4247faac49a.png', 2, NULL, 'hjgjh', NULL, NULL, 1),
(16, 33, 33, 'uploads/ee7cbe5fd4d58fb6de259d88c2ad4dd7.jpg', 2, NULL, 'sdfsdf', 'sdasda', NULL, 2),
(17, 33, 33, 'uploads/7680af28aab0d6125d07e7f258dc0844.jpg', 2, NULL, 'fdg', NULL, NULL, 1),
(18, 34, 33, 'uploads/5b32bedd40f26dda5468118bd987ca95.jpg', 12, NULL, 'hjj', NULL, NULL, 1),
(24, 38, 37, 'uploads/9ce0504789dd581bf74de278b8144ddb.jpg', 67, NULL, 'i want this fix!', NULL, NULL, 1),
(25, 39, 38, 'uploads/1f0479d3de245db89cd5ca36c494c87f.jpg', 23, NULL, 'This is a picture of a ring', NULL, NULL, 1),
(26, 40, 39, 'uploads/36a74e0539718ce4f7c9922500c08611.jpg', 1, NULL, 'dvgbdfgbddf', 'rhgh', NULL, 2),
(27, 41, 39, NULL, 1, NULL, '', NULL, NULL, 1),
(28, 42, 39, NULL, 11, NULL, '', NULL, NULL, 1),
(29, 43, 41, 'uploads/cd616d92102a5a80d7c59daf9ec5e2dc.jpg', 1, NULL, '', NULL, NULL, 1),
(30, 44, 42, 'uploads/7bec321dcad05ceb2e0dcc21b77a761a.png', 7, NULL, 'check', 'sorted', NULL, 2),
(31, 45, 44, 'uploads/62431b80d7f33db2a5081c1965b5e8e7.jpg', 12, NULL, 'please', NULL, NULL, 1),
(32, 46, 45, 'uploads/10a091de10bf68f06184ff176cbf15e2.jpg', 40, NULL, 'asdf', NULL, NULL, 1),
(33, 47, 45, 'uploads/7d458eccda2ad574ebd9e47c38df9e6e.jpg', 2, NULL, 'sadfsad', NULL, NULL, 1),
(34, 48, 50, NULL, 2, NULL, '', 'Abc', 'uploads/4d22dd726dd775c46219c5b6f84e3c13.jpg', 2),
(35, 49, 51, 'uploads/2ff3ea7c06ed8f3ac7d46747d2013ec0.gif', 1, NULL, 'demo text', NULL, NULL, 1),
(40, 54, 57, 'uploads/939ef5e7dda359d138b4ff9e060c1bbc.jpg', 53, 53, 'Its Dirty', NULL, NULL, 1),
(41, 55, 57, 'uploads/884c5bf68f07c696cb8f815983c675bb.jpg', 24, 24, 'There\'s scratches!', NULL, NULL, 1),
(44, 58, 35, 'uploads/7b2686c930540c51637387842feff4c4.jpg', 27, 27, 'The bracelet got issues, the spring hook broke', '', NULL, 1),
(45, 58, 35, 'uploads/ca09a3e463ab1a782139c1e45e332455.jpg', 11, 11, 'Not only that, the design suck', '', NULL, 1),
(46, 58, 35, NULL, 7, 7, 'This is a new defect', '', NULL, 1),
(47, 59, 35, 'uploads/c236b460ef5a7d7f5df05619c080546a.jpg', 21, 21, 'Where is the C&K logo?', '', 'uploads/cc681b118e092766b073c536471a2dbf.jpg', 1),
(48, 60, 35, 'uploads/989b3c00f905cff6fec684b1ac6dc1bb.jpg', 76, 76, 'The shoe strap is missing', '', NULL, 1),
(50, 62, 58, 'uploads/c3ed168b010c58c590db7e0c29ef4b57.jpg', 40, 2, 'Updated', NULL, NULL, 1),
(53, 65, 59, 'uploads/0aaf85de3d9683b9402cb4de4ca1ce67.jpg', 1, 4, 'Ok', NULL, NULL, 1),
(55, 67, 60, 'uploads/a08ba58df51b59d42787ce66aec71180.png', 7, 30, 'Banana', NULL, NULL, 1),
(57, 69, 61, 'uploads/56fdb759a5af0c5182a5a451c03b998d.png', 12, 13, 'sdasdasdasda', NULL, NULL, 1),
(61, 73, 62, NULL, 2, 2, 'test', NULL, NULL, 1),
(65, 77, 64, NULL, 12, 16, 'Rim Broken', NULL, NULL, 1),
(70, 82, 67, NULL, 7, 7, 'Testing', NULL, NULL, 1),
(71, 83, 63, NULL, 57, 57, '---', NULL, NULL, 1),
(72, 84, 68, NULL, 1, 3, 'ddd', NULL, NULL, 1),
(74, 86, 69, NULL, 2, 2, 'test ', NULL, NULL, 1),
(76, 88, NULL, NULL, 1, 1, 'testing', NULL, NULL, 1),
(78, 90, 71, NULL, 34, 34, 'test', NULL, NULL, 1),
(79, 91, 72, NULL, 12, 15, 'Breakage', NULL, NULL, 1),
(81, 93, 73, NULL, 1, 47, 'As', NULL, NULL, 1),
(82, 94, 74, NULL, 1, 47, 'NA', NULL, NULL, 1),
(88, 100, 70, NULL, 1, 1, 'ac', NULL, NULL, 1),
(90, 102, 75, NULL, 40, 41, '', NULL, NULL, 1),
(91, 103, 66, NULL, 7, 7, 'Xxx', NULL, NULL, 1),
(92, 104, 76, NULL, 11, 11, 'Dirty', NULL, NULL, 1),
(93, 105, 65, NULL, 21, 54, 'Xxx', NULL, NULL, 1),
(94, 106, 77, NULL, 1, 1, 'test', NULL, NULL, 1);
-- --------------------------------------------------------
--
-- Table structure for table `prd_defect_category`
--
CREATE TABLE `prd_defect_category` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`ch_name` varchar(255) DEFAULT NULL,
`main_category` varchar(255) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`ch_main_category` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `prd_defect_category`
--
INSERT INTO `prd_defect_category` (`id`, `name`, `ch_name`, `main_category`, `description`, `ch_main_category`) VALUES
(1, 'Oxidised/ Tarnished', '氧化 / 玷污', 'Material Issues', 'Material Issues - Material Oxidized', '材料问题'),
(2, 'Broken Accessory', '配件损坏', 'Breakage', 'Breakage', '断裂'),
(3, 'Colour Run/Discolouration', '退色/材料变色', 'Material Issues', 'Material Issues - Colour Run', '材料问题'),
(4, 'Material Cracked', '材料断裂', 'Material Issues', 'Material Issues \n', '材料问题'),
(5, 'Material Peeling', '材料脱皮', 'Material Issues', 'Material Issues', '材料问题'),
(6, 'Poor Stitching', '针线缝不好', 'Stitching', 'Stitching', '车线问题'),
(7, 'Scratches on Accessory', '五金刮痕', 'Scratches', 'Scratches', '刮痕'),
(8, 'Scratches', '刮痕', 'Scratches', 'Scratches', '刮痕'),
(9, 'Wear & Tear', '磨损', 'Wear & Tear', 'Wear & Tear', '穿戴磨损'),
(10, 'Buckle drop off', '纽扣/扣子脱落', 'Breakage', 'Breakage', '断裂'),
(11, 'Design Issue', '设计问题', 'Others', 'Others', '其他'),
(12, 'Broken Arm', '眼架断裂', 'Breakage', 'Breakage', '断裂'),
(13, 'Broken Bridge', '鼻托断裂', 'Breakage', 'Breakage', '断裂'),
(14, 'Broken Hinge', '铰链断裂', 'Breakage', 'Breakage', '断裂'),
(15, 'Broken Pad Arm', '鼻垫架断裂', 'Breakage', 'Breakage', '断裂'),
(16, 'Broken Rim', '镜框断裂', 'Breakage', 'Breakage', '断裂'),
(17, 'Cracked Len', '镜片裂', 'Breakage', 'Breakage', '断裂'),
(18, 'Len Drop Off', '镜片脱落', 'Production Issues', 'Production Issues', '生产 问题'),
(19, 'Missing Accessory', '遗失配件', 'Production Issues', 'Production Issues', '生产 问题'),
(20, 'Missing Nose Pad', '遗失鼻垫', 'Missing Components', 'Missing Components', '零件脱落'),
(21, 'Missing precious stone', '遗失宝石', 'Production Issues', 'Production Issues', '生产 问题'),
(22, 'Missing Screw', '遗失螺丝', 'Production Issues', 'Production Issues', '生产 问题'),
(23, 'Poor Finishing', '质量低劣', 'Production Issues', 'Production Issues', '生产 问题'),
(24, 'Scratches on Frame', '眼眶刮痕', 'Scratches', 'Scratches', '刮痕'),
(25, 'Disfigured Frame', '镜架损毁', 'Others', 'Others', '其他'),
(26, 'Broken Temple', '支架断裂', 'Breakage', 'Breakage', '断裂'),
(27, 'Broken Spring Hook', '弹簧勾断裂', 'Breakage', 'Breakage', '断裂'),
(28, 'Lock loosen', '锁头松脱', 'Production Issues', 'Production Issues', '生产 问题'),
(29, 'Scratches on Bracelet', '手镯刮痕', 'Scratches', 'Scratches', '刮痕'),
(30, 'Scratches on stone', '宝石刮痕', 'Scratches', 'Scratches', '刮痕'),
(31, 'Scratches on Ring', '戒指刮痕', 'Scratches', 'Scratches', '刮痕'),
(32, 'Scratches on Necklace', '项链刮痕', 'Scratches', 'Scratches', '刮痕'),
(33, 'Scratches on Key Chain', '锁匙扣刮痕', 'Scratches', 'Scratches', '刮痕'),
(34, 'Scratches on Casing', '电话壳刮痕', 'Scratches', 'Scratches', '刮痕'),
(35, 'Missing Logo', '遗失票制', 'Production Issues', 'Production Issues', '生产 问题'),
(36, 'Manufacture Issue', '产值问题', 'Production Issues', 'Production Issues', '生产 问题'),
(37, 'Scratches on Ear Ring', '耳环刮痕', 'Scratches', 'Scratches', '刮痕'),
(38, 'Missing stopper', '遗失塞子', 'Missing Components', 'Missing Components', '零件脱落'),
(39, 'Scratches on bag', '包包刮痕', 'Scratches', 'Scratches', '刮痕'),
(40, 'Broken Strap Hook', '肩带勾断裂', 'Breakage', 'Breakage', '断裂'),
(41, 'Broken Strap', '肩带断裂', 'Breakage', 'Breakage', '断裂'),
(42, 'Faulty Lock', '锁头损坏', 'Material Issues', 'Material Issues', '材料问题'),
(43, 'Faulty Zipper', '拉链损坏', 'Material Issues', 'Material Issues', '材料问题'),
(44, 'Broken Zipper', '拉链断裂', 'Breakage', 'Breakage', '断裂'),
(45, 'Broken Inner Zipper', '内侧拉链断裂', 'Breakage', 'Breakage', '断裂'),
(46, 'Faulty Inner Zipper', '内侧拉链损坏', 'Material Issues', 'Material Issues', '材料问题'),
(47, 'Colour Run', '跑色', 'Material Issues', 'Material Issues', '材料问题'),
(48, 'Eyelet came off', '包孔脱落', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(49, 'Broken Chain', '链子破裂/断裂', 'Breakage', 'Breakage', '断裂'),
(50, 'Broken Lock', '锁扣破裂/断裂', 'Breakage', 'Breakage', '断裂'),
(51, 'Zipper Stuck', '拉链卡', 'Material Issues', 'Material Issues', '材料问题'),
(52, 'Glue Stain', '胶水导致的污点', 'Glue', 'Glue', '胶水'),
(53, 'Stained Hardware', '五金有污点', 'Stains', 'Stains', '污点'),
(54, 'Unfinished Stitching', '未完成针车', 'Stitching', 'Stitching', '车线问题'),
(55, 'Stitches Came Off', '车线脱落', 'Stitching', 'Stitching', '车线问题'),
(56, 'Untidy Stitching', '针车不均匀', 'Stitching', 'Stitching', '车线问题'),
(57, 'Glue Not Strong', '胶水粘得不牢固', 'Glue', 'Glue', '胶水'),
(58, 'Logo Upside Down', '牌子倒挂', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(59, 'Loose Screws', '螺丝松动', 'Production Issues', 'Production Issues', '生产 问题'),
(60, 'Unfinished Gluing', '胶水未干', 'Glue', 'Glue', '胶水'),
(61, 'Slanted Flap', '手袋皮瓣歪', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(62, 'Slanted Lock/Ornament/Logo', '锁/饰品/商标歪', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(63, 'Scratches on Shoes', '学子刮痕', 'Scratches', 'Scratches', '刮痕'),
(64, 'Broken Heel', '靴跟断裂', 'Breakage', 'Breakage', '断裂'),
(65, 'Broken Heel Cap', '天皮/靴跟盖断裂', 'Breakage', 'Breakage', '断裂'),
(66, 'Material Stained', '材料染色', 'Material Issues', 'Material Issues', '材料问题'),
(67, 'Insole Peeled off', '靴垫脱皮', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(68, 'Outsole Dropped Off', '靴底脱落', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(69, 'Wrong side', '同边鞋', 'Wrong Contents & Packing', 'Wrong Contents & Packing', '包装错误'),
(70, 'Wrong size', '错码', 'Wrong Contents & Packing', 'Wrong Contents & Packing', '包装错误'),
(71, 'Nail Found', '出钉', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(72, 'Shaky Heel', '鞋跟摇晃', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(73, 'Shoe Tongue Came Off', '鞋舌脱落', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(74, 'Elastic Band Loosen', '补强带松弛', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(75, 'Slanted Heel', '鞋跟歪', 'Workmanship & Fitting', 'Workmanship & Fitting', '工艺 & 装配不符'),
(76, 'Missing Accessory', '遗失配件', 'Missing Components', 'Missing Components', '零件脱落'),
(77, 'Missing precious stone', '遗失宝石', 'Missing Components', 'Missing Components', '零件脱落'),
(78, 'Paper Stick', '包装纸', 'Others', 'Others', '其他');
-- --------------------------------------------------------
--
-- Table structure for table `prd_defect_products`
--
CREATE TABLE `prd_defect_products` (
`id` int(11) NOT NULL,
`product_name` varchar(255) DEFAULT NULL,
`defect_id` int(11) DEFAULT NULL,
`product_id` int(11) DEFAULT NULL,
`status` int(11) DEFAULT '1',
`articleno` int(11) DEFAULT NULL,
`size` int(11) DEFAULT NULL,
`color` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `prd_defect_products`
--
INSERT INTO `prd_defect_products` (`id`, `product_name`, `defect_id`, `product_id`, `status`, `articleno`, `size`, `color`) VALUES
(1, 'BELT', 1, 1, 1, NULL, NULL, NULL),
(2, 'SUNGLASS', 1, 2, 1, NULL, NULL, NULL),
(3, 'SUNGLASS', 1, 2, 1, NULL, NULL, NULL),
(4, 'SUNGLASS', 1, 2, 1, NULL, NULL, NULL),
(5, 'BELT', 3, 1, 1, NULL, NULL, NULL),
(6, 'SUNGLASS', 3, 2, 1, NULL, NULL, NULL),
(7, 'BRACELET', 3, 3, 1, NULL, NULL, NULL),
(8, 'RING', 3, 4, 1, NULL, NULL, NULL),
(9, 'NECKLACE', 3, 5, 1, NULL, NULL, NULL),
(10, 'KEY CHAIN', 3, 6, 1, NULL, NULL, NULL),
(11, 'HP CASING', 3, 7, 1, NULL, NULL, NULL),
(12, 'IPAD CASING', 3, 8, 1, NULL, NULL, NULL),
(13, 'EARRING', 3, 9, 1, NULL, NULL, NULL),
(14, 'BAG', 3, 10, 1, NULL, NULL, NULL),
(15, 'SHOES', 3, 11, 1, NULL, NULL, NULL),
(16, 'BELT', 2, 1, 1, NULL, NULL, NULL),
(17, 'BRACELET', 4, 3, 1, NULL, NULL, NULL),
(18, 'SHOES', 1, 11, 1, NULL, NULL, NULL),
(19, 'IPAD CASING', 1, 8, 1, NULL, NULL, NULL),
(20, 'BELT', 19, 1, 1, NULL, NULL, NULL),
(21, 'SUNGLASS', 20, 2, 1, NULL, NULL, NULL),
(22, 'BELT', 21, 1, 1, NULL, NULL, NULL),
(23, 'BELT', 22, 1, 1, NULL, NULL, NULL),
(24, 'BELT', 23, 1, 1, NULL, NULL, NULL),
(25, 'BRACELET', 25, 3, 1, NULL, NULL, NULL),
(26, 'BRACELET', 26, 3, 1, NULL, NULL, NULL),
(27, 'BELT', 27, 1, 1, NULL, NULL, NULL),
(28, 'RING', 29, 4, 1, NULL, NULL, NULL),
(29, 'BRACELET', 8, 3, 1, NULL, NULL, NULL),
(30, 'RING', 8, 4, 1, NULL, NULL, NULL),
(31, 'BELT', 24, 1, 1, NULL, NULL, NULL),
(32, 'SUNGLASS', 29, 2, 1, NULL, NULL, NULL),
(33, 'BELT', 33, 1, 1, NULL, NULL, NULL),
(34, 'SUNGLASS', 33, 2, 1, NULL, NULL, NULL),
(38, 'SHOES', 37, 11, 1, NULL, NULL, NULL),
(39, 'EARRING', 38, 9, 1, NULL, NULL, NULL),
(40, 'KEY CHAIN', 39, 6, 1, NULL, NULL, NULL),
(41, 'BELT', 39, 1, 1, NULL, NULL, NULL),
(42, 'RING', 39, 4, 1, NULL, NULL, NULL),
(43, 'BELT', 41, 1, 1, NULL, NULL, NULL),
(44, 'RING', 42, 4, 1, NULL, NULL, NULL),
(45, 'SUNGLASS', 44, 2, 1, NULL, NULL, NULL),
(46, 'SHOES', 45, 11, 1, NULL, NULL, NULL),
(47, 'BELT', 45, 1, 1, NULL, NULL, NULL),
(48, 'BELT', 50, 1, 1, NULL, NULL, NULL),
(49, 'SUNGLASS', 51, 2, 1, NULL, NULL, NULL),
(54, 'BAG', 57, 10, 1, NULL, NULL, NULL),
(55, 'SUNGLASS', 57, 2, 1, NULL, NULL, NULL),
(58, 'BRACELET', 35, 3, 1, NULL, NULL, NULL),
(59, 'BAG', 35, 10, 1, NULL, NULL, NULL),
(60, 'SHOES', 35, 11, 1, NULL, NULL, NULL),
(62, 'SHOES', 58, 11, 1, NULL, NULL, NULL),
(65, 'BELT', 59, 1, 1, NULL, NULL, NULL),
(67, 'BRACELET', 60, 3, 1, NULL, NULL, NULL),
(69, 'SUNGLASS', 61, 2, 1, NULL, NULL, NULL),
(73, 'BELT', 62, 1, 1, NULL, NULL, NULL),
(77, 'SUNGLASS', 64, 2, 1, 1234, 0, 'Black'),
(82, 'BAG', 67, 10, 1, 12333, 23, 'Red'),
(83, 'BAG', 63, 10, 1, 6666, 32, 'Yellow'),
(84, 'BELT', 68, 1, 1, 1, 25, 'red'),
(86, 'BELT', 69, 1, 1, 113, 10, 'black2'),
(88, 'BRACELET', NULL, 3, 1, 16, 40, 'Blue'),
(90, 'HP CASING', 71, 7, 1, 1234, 42, 'White'),
(91, 'SUNGLASS', 72, 2, 1, 0, 36, 'Red'),
(93, 'SHOES', 73, 11, 1, 0, 34, 'Black'),
(94, 'BAG', 74, 10, 1, 0, 0, 'Black'),
(100, 'BRACELET', 70, 3, 1, 12, 12, 'asda'),
(102, 'SHOES', 75, 11, 1, 0, 37, 'Orange'),
(103, 'SHOES', 66, 11, 1, 9087, 40, 'Black'),
(104, 'RING', 76, 4, 1, 121, 20, 'Dark Blue'),
(105, 'BAG', 65, 10, 1, 1990, 10, 'Black'),
(106, 'RING', 77, 4, 1, 5559, 35, 'Red');
-- --------------------------------------------------------
--
-- Table structure for table `prd_email_logs`
--
CREATE TABLE `prd_email_logs` (
`id` int(11) NOT NULL,
`email` varchar(255) DEFAULT NULL,
`subject` varchar(255) DEFAULT NULL,
`body` text,
`status` varchar(15) NOT NULL DEFAULT 'pending',
`initial_date` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `prd_email_logs`
--
INSERT INTO `prd_email_logs` (`id`, `email`, `subject`, `body`, `status`, `initial_date`) VALUES
(7, 'sandra@wp.com', 'test', '<p><strong>this is a test</strong></p>\r\n', 'Sent', '2018-01-03 14:08:34'),
(8, 'asdasd@sdda.com', 'Product Repaired', '<p><strong>Lorer Ipsum</strong></p>\r\n', 'Sent', '2018-01-05 01:33:25'),
(9, 'hongye@wp.com', 'Product Repaired', '<p>Hi Man,</p>\r\n\r\n<p>Your product is repaired.. Please collect it.</p>\r\n', 'Sent', '2018-01-05 01:51:02'),
(10, 'nazreen@webpuppies.com.sg', 'Your Item is ready for collection', '<p>Please collect your item now.</p>\r\n', 'Sent', '2018-01-05 16:03:34'),
(11, 'nazreen@webpuppies.com.sg', 'Your Item is ready for collection', '<p>Test 123</p>\r\n', 'Sent', '2018-01-05 16:32:03'),
(12, 'nazreen@webpuppies.com.sg', 'Your Item is ready for collection', '<p>Hi Nazreen,</p>\r\n\r\n<p> </p>\r\n\r\n<p>Your Item is ready for collection,</p>\r\n\r\n<p> </p>\r\n\r\n<p>Item: Bags / Shades<br />\r\nOutlet: Tanjong Pagar CK Outlet<br />\r\nOperating Hours: 8am - 10pm</p>\r\n\r\n<p>Please bring your receipt to verify collection.</p>\r\n\r\n<p>Thank you.<br />\r\nRegards,<br />\r\nCharles & Keith Representative<br />\r\n<a href=\"http://www.charleskeith.com/\"><img alt=\"\" src=\"https://canalwalk.co.za/wp-content/uploads/2016/10/Tenant-List58.png\" style=\"height:200px; width:200px\" /></a></p>\r\n', 'Sent', '2018-01-20 13:17:13'),
(13, 'tom@gmail.com', 'Hello', '<p>Test</p>\r\n', 'Sent', '2018-01-23 12:59:15'),
(14, 'nazreen@webpuppies.com.sg', 'test', '<p>Hi Nazreen,</p>\r\n\r\n<p> </p>\r\n\r\n<p>Your Item is ready for collection,</p>\r\n\r\n<p> </p>\r\n\r\n<p>Item: Bags / Shades<br />\r\nOutlet: Tanjong Pagar CK Outlet<br />\r\nOperating Hours: 8am - 10pm</p>\r\n\r\n<p>Please bring your receipt to verify collection.</p>\r\n\r\n<p>Thank you.<br />\r\nRegards,<br />\r\nCharles & Keith Representative<br />\r\n<a href=\"http://www.charleskeith.com/\"><img alt=\"\" src=\"https://canalwalk.co.za/wp-content/uploads/2016/10/Tenant-List58.png\" /></a></p>\r\n', 'Sent', '2018-01-23 13:05:20'),
(15, 'Helen@mail.com', 'Testing 123', '<p>testing 123</p>\r\n', 'Sent', '2018-01-23 15:29:02'),
(16, 'nazreen@webpuppies.com.sg', 'Your Item is ready for collection', '<p><a href=\"mailto:nazreen@webpuppies.com.sg\">c</a>heck the name</p>\r\n', 'Sent', '2018-01-23 15:44:06'),
(17, 'pauline@mail.com', NULL, 'Hello', 'Sent', '2018-01-23 22:32:37'),
(18, 'pauline@mail.com', NULL, '', 'Sent', '2018-01-24 00:45:45'),
(19, 'pauline@mail.com', NULL, '', 'Sent', '2018-01-24 00:45:46'),
(20, 'pauline@mail.com', 'testing', 'hihi', 'Sent', '2018-01-26 01:45:28'),
(21, 'nazreen@webpuppies.com.sg', 'test', 'sssss', 'Sent', '2018-01-26 01:46:42'),
(22, 'nazreen@webpuppies.com.sg', 'test', 'test', 'Sent', '2018-01-26 01:48:15'),
(23, 'nazreen@webpuppies.com.sg', 'tttt', 'tttt', 'Sent', '2018-01-26 01:49:52'),
(24, 'leekim@webpuppies.com.sg', 'test', 'tesy', 'Sent', '2018-01-26 01:53:18');
-- --------------------------------------------------------
--
-- Table structure for table `prd_images`
--
CREATE TABLE `prd_images` (
`id` int(11) NOT NULL,
`product_id` int(11) DEFAULT NULL,
`defect_id` int(11) DEFAULT NULL,
`images` varchar(255) DEFAULT NULL,
`status` int(11) NOT NULL DEFAULT '1',
`what_done_for_repair` text,
`repair_image` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `prd_images`
--
INSERT INTO `prd_images` (`id`, `product_id`, `defect_id`, `images`, `status`, `what_done_for_repair`, `repair_image`) VALUES
(8, 1, 62, 'uploads/4baacc29ee92cf3ce5e0c151e9da958b.png', 1, NULL, NULL),
(9, 1, 62, 'uploads/3a2472cb6914ca088da5db7f6084a4d0.png', 1, NULL, NULL),
(16, 2, 64, 'uploads/a5397f5d431340a2a9b152e548c689eb.png', 1, 'This is a nose', 'uploads/19018df91cf11620eb49fa0f1fda60a5.jpg'),
(17, 2, 64, 'uploads/10240b2bea88d17449491455b421b939.png', 1, 'Bag handle is loose', NULL),
(29, 10, 63, 'uploads/03b60a7e6be3827b79c0249e9ac41baa.jpg', 1, NULL, NULL),
(30, 10, 63, 'uploads/b35a609d8215e1e9e1ea1651aab3d68d.png', 1, NULL, NULL),
(31, 10, 63, 'uploads/d4c7d368ddda948968f7247a77930f2a.png', 1, NULL, NULL),
(34, 1, 69, 'uploads/7a99def0c55428f1b4a9ad895e1723eb.png', 1, NULL, NULL),
(35, 1, 69, 'uploads/7077a41be1aeacd31f44ed07255ba5b9.png', 1, NULL, NULL),
(37, 3, NULL, 'uploads/c94ff3256062a65f766d2b20090fac60.png', 1, NULL, NULL),
(39, 7, 71, 'uploads/b70d9e96734644c634eea08e043e8c1a.jpg', 1, NULL, NULL),
(40, 2, 72, 'uploads/ed65e911fdd26dd28da8da87a6432bef.png', 1, '', NULL),
(41, 2, 72, 'uploads/8f6d714c3abae8183cffc44e22957646.png', 1, '', NULL),
(42, 2, 72, 'uploads/9acf75852bcd9173144a3c256a160a34.png', 1, '', NULL),
(44, 11, 73, 'uploads/703514a854119d4967f0e5eb2cc84fe1.png', 1, NULL, NULL),
(45, 10, 74, 'uploads/26cb7b024034562e47cf0a8667ef0fe1.jpg', 1, NULL, NULL),
(51, 3, 70, 'uploads/7cee5c3109e92f18e693ee75e8231290.png', 1, NULL, NULL),
(52, 3, 70, 'uploads/82432bc147ac563d59c5ff68bf5dfd6b.png', 1, NULL, NULL),
(54, 11, 66, 'uploads/b5421a67fa1e32a9123872ae7995c2ea.gif', 2, 'Patch a few glue on the side', 'uploads/58bdefeba0b9bc4d7b2193679942b651.png'),
(55, 4, 76, 'uploads/0e4b02bcd1d74f83131e1213066f27c2.png', 1, '', 'uploads/761b44ca19f3869a69bb6a2d3eb59c7d.jpg'),
(56, 10, 65, 'uploads/639751d985a9927dd2ba9e74cc336387.jpg', 1, NULL, NULL),
(57, 10, 65, 'uploads/8f4297cfc3ca3304469682f65a89134e.png', 1, NULL, NULL),
(58, 4, 77, 'uploads/1698a7e35ffbeddd242ab09f3546bdbf.png', 1, NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `prd_outlet`
--
CREATE TABLE `prd_outlet` (
`id` int(11) NOT NULL,
`name` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`location` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`contact_no` int(18) NOT NULL,
`email` varchar(50) NOT NULL,
`outlet_type` int(11) DEFAULT '1' COMMENT '1=Charles & Keith 2=Pedro'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `prd_outlet`
--
INSERT INTO `prd_outlet` (`id`, `name`, `location`, `contact_no`, `email`, `outlet_type`) VALUES
(43, 'Pedro NEX (PNX)', 'NEX Mall #01-80/81', 66340979, 'nex.pedro@pedroshoes.com', 2),
(41, 'Pedro JEM (PJM)', 'JEM #01-41', 68379011, 'jem.pedro@pedroshoes.com', 2),
(42, 'Pedro ION (ION)', 'ION Orchard #B3-10', 62382067, 'ion.pedro@pedroshoes.com', 2),
(1, 'Charles & Keith 313 (313)', '313@Somerset #02-46/47/48/49', 65095040, '313@charleskeith.com\r\n', 1),
(40, 'Pedro Bugis Junction (PBG)', 'Bugis Junction #01-03', 63380538, 'bg.pedro@pedroshoes.com', 2),
(39, 'Pedro Anchorpoint (PAP)', 'Anchorpoint #01-29', 64726963, 'ap.pedro@pedroshoes.com', 2),
(2, 'Charles & Keith Anchorpoint (AP)', 'Anchorpoint #01-30/31', 64726937, 'CKSAnchorpoint@charleskeith.com\r\n', 1),
(12, 'Charles & Keith Bugis Junction (BG)', 'Bugis Junction #01-06/07/08', 63380537, 'CKSBugisjuction@charleskeith.com\r\n', 1),
(13, 'Charles & Keith Bedok Mall (BDM)', 'Bedok Mall #01-31', 67025521, 'bdm@charleskeith.com\r\n', 1),
(14, 'Charles & Keith Central (CEN)', 'Central #01-51/52', 63275036, 'CKSCentral@charleskeith.com\r\n', 1),
(15, 'Charles & Keith City Square Mall (CQM)', 'City Square Mall #01-34/35', 65095041, 'CKSCitySquareMall@charleskeith.com\r\n', 1),
(16, 'Charles & Keith City Link Mall (CTL)', 'City Link Mall #B1-32/34', 63380913, 'CKSCityLink@charleskeith.com\r\n', 1),
(17, 'Charles & Keith Causeway Point (CWP)', 'Causeway Point #01-28', 67671306, 'CKSCausewayPoint@charleskeith.com\r\n', 1),
(18, 'Charles & Keith Great World City (GWC)', 'Great World City #01-38', 68380372, 'gwc@charleskeith.com\r\n', 1),
(19, 'Charles & Keith ION Orchard (ION)', 'ION Orchard #B3-58', 62381840, 'CKSION@charleskeith.com\r\n', 1),
(20, 'Charles & Keith IMM (IMM)', 'IMM #02-13', 65639020, 'cks.imm@charleskeith.com\r\n', 1),
(21, 'Charles & Keith JEM (JEM)', 'JEM #01-58', 68379010, 'jem@charleskeith.com\r\n', 1),
(22, 'Charles & Keith Jurong Point Shopping Centre (JP)', 'Jurong Point Shopping Centre #02-02/03', 67920986, 'CKSJurongPoint@charleskeith.com\r\n', 1),
(23, 'Charles & Keith Marina Bay Sands (MBS)', 'Marina Bay Sands #B2-99', 66340843, 'mbs@charleskeith.com\r\n', 1),
(24, 'Charles & Keith Marina Square (MS)', 'Marina Square #02-107/108', 63380919, 'CKSMarinaSquare@charleskeith.com\r\n', 1),
(25, 'Charles & Keith Takashimaya S. C. (NAC)', 'Takashimaya S. C. #B2-12/14', 67370152, 'nac@charleskeith.com\r\n', 1),
(26, 'Charles & Keith Velocity @ Novena (NV)', 'Velocity @ Novena #01-13/14', 63536063, 'nv@charleskeith.com\r\n', 1),
(27, 'Charles & Keith NEX (NEX)', 'NEX #01-39/40', 66347445, 'nex@charleskeith.com\r\n', 1),
(28, 'Charles & Keith Plaza Singapura (PS)', 'Plaza Singapura #02-28/28A', 63349331, 'CKSPlazaSingapura@charleskeith.com\r\n', 1),
(29, 'Charles & Keith Raffles City Shopping Centre (RC)', 'Raffles City Shopping Centre #03-31/32', 63349066, 'CKSRafflesCIty@charleskeith.com\r\n', 1),
(30, 'Charles & Keith Suntec City Mall (STC)', 'Suntec City Mall #01-338', 63391300, 'stc@charleskeith.com\r\n', 1),
(31, 'Charles & Keith Changi Airport Terminal 1 (T1)', 'Changi Airport Terminal 1 #02-51', 62148044, 'CKST1@charleskeith.com\r\n', 1),
(32, 'Charles & Keith Changi Airport Terminal 2 (T2)', 'Changi Airport Terminal 2 #026-057', 65438055, 't2@charleskeith.com\r\n', 1),
(33, 'Charles & Keith Changi Airport Terminal 3 (T3)', 'Changi Airport Terminal 3 #02-53', 64467283, 'CKST3@charleskeith.com\r\n', 1),
(34, 'Charles & Keith Changi Airport Terminal 4 (T4)', 'Changi Airport Terminal 4 #02-30', 65811648, 'ckst4@charleskeith.com\r\n', 1),
(35, 'Charles & Keith Tampines Mall (TM)', 'Tampines Mall #01-13/14', 62609711, 'CKSTampinesMall@charleskeith.com\r\n', 1),
(36, 'Charles & Keith VivoCity (VC)', 'VivoCity #02-184/185', 63765013, 'CKSVivocity@charleskeith.com\r\n', 1),
(37, 'Charles & Keith Wisma Atria Shopping Centre WA', 'Wisma Atria Shopping Centre #B1-18/19', 62383312, 'wa@charleskeith.com\r\n', 1),
(38, 'Charles & Keith Waterway Point (WWP)', 'Waterway Point #01-51', 63858153, 'cks.wwp@charleskeith.com\r\n', 1),
(44, 'Pedro Marina Bay Sands (PMB)', 'Marina Bay Sands #B2-100', 66349454, 'mbs.pedro@pedroshoes.com', 2),
(45, 'Pedro Plaza Singapura (PPS)', 'Plaza Singapura #01-03', 63380536, 'ps.pedro@pedroshoes.com', 2),
(46, 'Pedro Suntec City Mall (PST)', 'Suntec City Mall #01-339', 63383976, 'stc.pedro@pedroshoes.com', 2),
(47, 'Pedro VivoCity (PVC)', 'VivoCity #02-186', 63765012, 'vivo.pedro@pedroshoes.com', 2),
(48, 'Pedro Wisma Atria Shopping Centre (PWA)', 'Wisma Atria Shopping Centre #B1-32/33/34', 68359517, 'ws.pedro@pedroshoes.com', 2),
(49, 'Pedro 313 (P13)', '313@Somerset #02-25/26/27', 65095038, '313.pedro@pedroshoes.com', 2),
(50, 'Pedro IMM (PIM)', 'IMM Mall #02-48', 65639019, 'imm.pedro@pedroshoes.com', 2);
-- --------------------------------------------------------
--
-- Table structure for table `prd_products`
--
CREATE TABLE `prd_products` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`ch_name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `prd_products`
--
INSERT INTO `prd_products` (`id`, `name`, `ch_name`) VALUES
(1, 'BELT', '腰带'),
(2, 'SUNGLASS', '墨镜'),
(3, 'BRACELET', '手镯'),
(4, 'RING', '戒子'),
(5, 'NECKLACE', '项链'),
(6, 'KEY CHAIN', '钥匙扣'),
(7, 'HP CASING', '电话壳'),
(8, 'IPAD CASING', '平板壳'),
(9, 'EARRING', '耳环'),
(10, 'BAG', '包包'),
(11, 'SHOES', '鞋');
-- --------------------------------------------------------
--
-- Table structure for table `prd_product_defect_category`
--
CREATE TABLE `prd_product_defect_category` (
`id` int(11) NOT NULL,
`product_id` int(11) DEFAULT NULL,
`defect_category_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `prd_product_defect_category`
--
INSERT INTO `prd_product_defect_category` (`id`, `product_id`, `defect_category_id`) VALUES
(1, 1, 1),
(2, 1, 2),
(3, 1, 3),
(4, 1, 4),
(5, 1, 5),
(6, 1, 6),
(7, 1, 7),
(8, 1, 8),
(9, 1, 9),
(10, 1, 10),
(11, 1, 11),
(12, 2, 1),
(13, 2, 12),
(14, 2, 13),
(15, 2, 14),
(16, 2, 15),
(17, 2, 16),
(18, 2, 17),
(19, 2, 18),
(20, 2, 19),
(21, 2, 20),
(22, 2, 21),
(23, 2, 22),
(24, 2, 23),
(25, 2, 24),
(26, 2, 11),
(27, 2, 25),
(28, 2, 26),
(29, 3, 1),
(30, 3, 27),
(31, 3, 28),
(32, 3, 19),
(33, 3, 21),
(34, 3, 23),
(35, 3, 7),
(36, 3, 29),
(37, 3, 30),
(38, 3, 9),
(39, 3, 11),
(40, 4, 1),
(41, 4, 19),
(42, 4, 21),
(43, 4, 23),
(44, 4, 7),
(45, 4, 31),
(46, 4, 30),
(47, 4, 9),
(48, 4, 11),
(49, 5, 1),
(50, 5, 27),
(51, 5, 28),
(52, 5, 19),
(53, 5, 21),
(54, 5, 23),
(55, 5, 7),
(56, 5, 32),
(57, 5, 30),
(58, 5, 9),
(59, 5, 11),
(60, 6, 1),
(61, 6, 27),
(62, 6, 28),
(63, 6, 19),
(64, 6, 23),
(65, 6, 7),
(66, 6, 33),
(67, 6, 9),
(68, 6, 11),
(69, 7, 19),
(70, 7, 23),
(71, 7, 34),
(72, 7, 6),
(73, 7, 35),
(74, 7, 9),
(75, 7, 11),
(76, 7, 36),
(77, 8, 19),
(78, 8, 23),
(79, 8, 34),
(80, 8, 6),
(81, 8, 35),
(82, 8, 9),
(83, 8, 11),
(84, 9, 1),
(87, 9, 23),
(88, 9, 37),
(89, 9, 30),
(90, 9, 9),
(91, 9, 38),
(92, 9, 11),
(93, 10, 1),
(94, 10, 21),
(95, 10, 23),
(96, 10, 6),
(97, 10, 35),
(98, 10, 7),
(99, 10, 39),
(100, 10, 40),
(101, 10, 41),
(102, 10, 2),
(103, 10, 42),
(104, 10, 43),
(105, 10, 44),
(106, 10, 45),
(107, 10, 46),
(108, 10, 47),
(109, 10, 11),
(110, 10, 48),
(111, 10, 49),
(112, 10, 50),
(113, 10, 16),
(114, 10, 51),
(115, 10, 57),
(116, 10, 52),
(117, 10, 53),
(118, 10, 54),
(119, 10, 55),
(120, 10, 56),
(121, 10, 58),
(122, 10, 59),
(123, 10, 60),
(124, 10, 61),
(125, 10, 62),
(126, 11, 1),
(127, 11, 19),
(128, 11, 23),
(129, 11, 6),
(130, 11, 7),
(131, 11, 63),
(132, 11, 40),
(133, 11, 2),
(134, 11, 41),
(135, 11, 64),
(136, 11, 65),
(137, 11, 47),
(138, 11, 66),
(139, 11, 11),
(140, 11, 36),
(141, 11, 67),
(142, 11, 68),
(143, 11, 48),
(144, 11, 69),
(145, 11, 70),
(146, 11, 71),
(147, 11, 72),
(148, 11, 73),
(149, 11, 74),
(150, 11, 75),
(151, 9, 77),
(152, 9, 76),
(153, 10, 76),
(154, 10, 78),
(155, 11, 76),
(156, NULL, NULL),
(157, NULL, NULL),
(158, NULL, NULL),
(159, NULL, NULL),
(160, NULL, NULL),
(161, NULL, NULL),
(162, NULL, NULL),
(163, NULL, NULL),
(164, NULL, NULL),
(165, NULL, NULL),
(166, NULL, NULL),
(167, NULL, NULL),
(168, NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `prd_users`
--
CREATE TABLE `prd_users` (
`id` int(11) NOT NULL,
`name` varchar(100) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`access_token` varchar(255) DEFAULT NULL,
`password_reset_token` varchar(255) DEFAULT NULL,
`user_type` int(11) NOT NULL DEFAULT '2' COMMENT '1=Admin 2=Staff 3=Repair Center',
`initial_date` datetime DEFAULT NULL,
`deleted` int(11) NOT NULL DEFAULT '0',
`employer_id` int(11) DEFAULT NULL,
`contact_no` int(11) DEFAULT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1=Active 0=Inactive'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `prd_users`
--
INSERT INTO `prd_users` (`id`, `name`, `email`, `password`, `access_token`, `password_reset_token`, `user_type`, `initial_date`, `deleted`, `employer_id`, `contact_no`, `status`) VALUES
(1, 'Admin', 'admin@product.com', '202cb962ac59075b964b07152d234b70', NULL, NULL, 1, NULL, 0, 1, 91252525, 1),
(2, 'Staff', 'staff@product.com', '202cb962ac59075b964b07152d234b70', NULL, NULL, 2, NULL, 0, 2, 91252525, 1),
(9, 'Repairman', 'repair@product.com', '202cb962ac59075b964b07152d234b70', NULL, NULL, 3, NULL, 0, 3, 91252525, 1),
(11, 'Sarah', 'sarah@product.com', '202cb962ac59075b964b07152d234b70', NULL, NULL, 2, NULL, 0, 5221, 95855221, 0),
(12, 'Jason Han', 'jason@product.com', '202cb962ac59075b964b07152d234b70', NULL, NULL, 3, NULL, 0, 4578, 65858547, 1),
(14, 'Abhi', 'abhi@product.com', '202cb962ac59075b964b07152d234b70', NULL, NULL, 3, NULL, 0, 2234, 11122322, 1),
(16, 'Francis', 'francis@product.com', '202cb962ac59075b964b07152d234b70', NULL, NULL, 2, NULL, 0, 1102, 999, 0),
(17, 'Harry', 'harry@product.com', '202cb962ac59075b964b07152d234b70', NULL, NULL, 2, NULL, 0, 1025, 98555558, 1);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `prd_customer`
--
ALTER TABLE `prd_customer`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_defects`
--
ALTER TABLE `prd_defects`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_defects_details`
--
ALTER TABLE `prd_defects_details`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_defect_category`
--
ALTER TABLE `prd_defect_category`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_defect_products`
--
ALTER TABLE `prd_defect_products`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_email_logs`
--
ALTER TABLE `prd_email_logs`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_images`
--
ALTER TABLE `prd_images`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_outlet`
--
ALTER TABLE `prd_outlet`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_products`
--
ALTER TABLE `prd_products`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_product_defect_category`
--
ALTER TABLE `prd_product_defect_category`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `prd_users`
--
ALTER TABLE `prd_users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `employer_id` (`employer_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `prd_customer`
--
ALTER TABLE `prd_customer`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=69;
--
-- AUTO_INCREMENT for table `prd_defects`
--
ALTER TABLE `prd_defects`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=78;
--
-- AUTO_INCREMENT for table `prd_defects_details`
--
ALTER TABLE `prd_defects_details`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=95;
--
-- AUTO_INCREMENT for table `prd_defect_category`
--
ALTER TABLE `prd_defect_category`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=80;
--
-- AUTO_INCREMENT for table `prd_defect_products`
--
ALTER TABLE `prd_defect_products`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=107;
--
-- AUTO_INCREMENT for table `prd_email_logs`
--
ALTER TABLE `prd_email_logs`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;
--
-- AUTO_INCREMENT for table `prd_images`
--
ALTER TABLE `prd_images`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=59;
--
-- AUTO_INCREMENT for table `prd_outlet`
--
ALTER TABLE `prd_outlet`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=52;
--
-- AUTO_INCREMENT for table `prd_products`
--
ALTER TABLE `prd_products`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `prd_product_defect_category`
--
ALTER TABLE `prd_product_defect_category`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=169;
--
-- AUTO_INCREMENT for table `prd_users`
--
ALTER TABLE `prd_users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java
|
UTF-8
| 8,170
| 1.960938
| 2
|
[] |
no_license
|
package com.voidwhile.system.entity;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.voidwhile.common.util.SpringContextHelper;
import com.voidwhile.system.service.SysOrganizationService;
/**
* CopyRright (c) 2017:
*
* @Description: 系统用户表 实体类
* @author: zhanzheng
* @Create Date: 2014年10月24日 上午10:15:11
*
* @Version: v1.0
*/
@JsonIgnoreProperties(value = { "plainPassword", "password", "phoneCode", "isSystem" })
public class SysUser {
private Long uid;
/**
* @Fields supplierId : 企业Id
*/
private String supplierId;
/**
* @Fields userName : 用户名
*/
private String userName;
/**
* @Fields plainPassword : 明文密码
*/
private String plainPassword;
/**
* @Fields password : 加密密码
*/
private String password;
/**
* @Fields realName : 姓名
*/
private String realName;
/**
* @Fields deptId : 用户所在部门
*/
private String deptId;
/**
* @Fields gender : 性别(1男 2女 0未知)
*/
private String gender;
/**
* @Fields birthday : 出生日期
*/
private Date birthday;
/**
* @Fields portrait : 头像
*/
private String portrait;
/**
* @Fields tel : 电话
*/
private String tel;
/**
* @Fields phone : 手机
*/
private String phone;
/**
* @Fields qq : qq
*/
private String qq;
/**
* @Fields email : email
*/
private String email;
/**
* @Fields phoneCode : 手机串码
*/
private String phoneCode;
/**
* @Fields lastLogin : 最近登录时间
*/
private Date lastLogin;
/**
* @Fields lastDevice : 最近登录设备
*/
private String lastDevice;
/**
* @Fields lastIp : 登录登录Ip
*/
private String lastIp;
/**
* @Fields loginNum : 登录次数
*/
private Integer loginNum;
/**
* @Fields status : 用户状态(1有效,0失效)
*/
private String status;
/**
* @Fields isSystem : 是否系统默认(1是,0不是)
*/
private String isSystem;
private String imgpath;
/**
* user_position : 职位
*/
private String userPosition;
/**
* @Fields createTime : 注册时间
*/
private Date createTime;
/**
* @Fields updateTime : 修改时间
*/
private Date updateTime;
public SysUser() {
// TODO Auto-generated constructor stub
}
public SysUser(String uid,String imgpath) {
this.imgpath = imgpath;
}
public SysUser(Long uid, String userName, String realName, String deptId, String gender, String email, String phone) {
this.uid = uid;
this.userName = userName;
this.realName = realName;
this.deptId = deptId;
this.gender = gender;
this.email = email;
this.phone=phone;
}
public SysUser(Long uid, String userName, String realName, String deptId, String gender, String email, String phone,Date updateTime) {
this.uid = uid;
this.userName = userName;
this.realName = realName;
this.deptId = deptId;
this.gender = gender;
this.email = email;
this.phone=phone;
this.updateTime = updateTime;
}
public SysUser(Long uid, String supplierId, String realName, String deptId, String attr1) {
this.uid = uid;
this.supplierId = supplierId;
this.realName = realName;
this.deptId = deptId;
}
public Long getUid() {
return uid;
}
public void setUid(Long uid) {
this.uid = uid;
}
public String getSupplierId() {
return supplierId;
}
public void setSupplierId(String supplierId) {
this.supplierId = supplierId == null ? null : supplierId.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getPlainPassword() {
return plainPassword;
}
public void setPlainPassword(String plainPassword) {
this.plainPassword = plainPassword == null ? null : plainPassword.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName == null ? null : realName.trim();
}
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId == null ? null : deptId.trim();
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender == null ? null : gender.trim();
}
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
public Date getBirthday() {
return birthday;
}
@DateTimeFormat(pattern = "yyyy-MM-dd")
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPortrait() {
return portrait;
}
public void setPortrait(String portrait) {
this.portrait = portrait == null ? null : portrait.trim();
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel == null ? null : tel.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq == null ? null : qq.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getPhoneCode() {
return phoneCode;
}
public void setPhoneCode(String phoneCode) {
this.phoneCode = phoneCode == null ? null : phoneCode.trim();
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
public String getLastDevice() {
return lastDevice;
}
public void setLastDevice(String lastDevice) {
this.lastDevice = lastDevice == null ? null : lastDevice.trim();
}
public String getLastIp() {
return lastIp;
}
public void setLastIp(String lastIp) {
this.lastIp = lastIp == null ? null : lastIp.trim();
}
public Integer getLoginNum() {
return loginNum;
}
public void setLoginNum(Integer loginNum) {
this.loginNum = loginNum;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status == null ? null : status.trim();
}
public String getIsSystem() {
return isSystem;
}
public void setIsSystem(String isSystem) {
this.isSystem = isSystem == null ? null : isSystem.trim();
}
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getImgpath() {
return imgpath;
}
public void setImgpath(String imgpath) {
this.imgpath = imgpath;
}
public String getDeptName() {
String deptName = "";
try {
SysOrganizationService organizationService = (SysOrganizationService) SpringContextHelper.getBean(SysOrganizationService.class);
SysOrganization org = organizationService.getById(deptId);
if (org != null) {
deptName = org.getOrgName();
}
} catch (Exception e) {
}
return deptName;
}
public String getUserPosition() {
return userPosition;
}
public void setUserPosition(String userPosition) {
this.userPosition = userPosition;
}
}
|
Markdown
|
UTF-8
| 1,223
| 2.90625
| 3
|
[
"Apache-2.0"
] |
permissive
|
title: ParseToDate
# ParseToDate Expression
`ParseToDate` is a link:spark-sql-Expression-RuntimeReplaceable.adoc[RuntimeReplaceable] expression that <<creating-instance, represents>> the link:spark-sql-functions-datetime.adoc#to_date[to_date] function (in logical query plans).
[source, scala]
----
// DEMO to_date(e: Column): Column
// DEMO to_date(e: Column, fmt: String): Column
----
As a `RuntimeReplaceable` expression, `ParseToDate` is replaced by link:spark-sql-Optimizer.adoc#ReplaceExpressions[Catalyst Optimizer] with the <<child, child>> expression:
* `Cast(left, DateType)` for `to_date(e: Column): Column` function
* `Cast(Cast(UnixTimestamp(left, format), TimestampType), DateType)` for `to_date(e: Column, fmt: String): Column` function
[source, scala]
----
// FIXME DEMO Conversion to `Cast(left, DateType)`
// FIXME DEMO Conversion to `Cast(Cast(UnixTimestamp(left, format), TimestampType), DateType)`
----
=== [[creating-instance]] Creating ParseToDate Instance
`ParseToDate` takes the following when created:
* [[left]] Left link:expressions/Expression.md[expression]
* [[format]] `format` link:expressions/Expression.md[expression]
* [[child]] Child link:expressions/Expression.md[expression]
|
Markdown
|
UTF-8
| 1,589
| 2.53125
| 3
|
[] |
no_license
|
# Article 1
Les modes de production raisonnés en agriculture consistent en la mise en oeuvre, par l'exploitant agricole sur l'ensemble de son exploitation dans une approche globale de celle-ci, de moyens techniques et de pratiques agricoles conformes aux exigences du référentiel de l'agriculture raisonnée.
Le référentiel porte sur le respect de l'environnement, la maîtrise des risques sanitaires, la santé et la sécurité au travail et le bien-être des animaux. Ses exigences concernent notamment :
- l'accès de l'exploitant et de ses salariés à l'information et la formation nécessaires à la conduite de l'exploitation agricole ;
- la mise en oeuvre d'un système d'enregistrement et de suivi des opérations effectuées et des produits utilisés pour les besoins des cultures et des animaux ;
- la maîtrise des intrants agricoles ainsi que des effluents et des déchets produits par l'exploitation ;
- l'usage justifié de moyens appropriés de protection des cultures et de la santé des animaux de l'exploitation ;
- l'équilibre de la fertilisation des cultures ;
- la mise en oeuvre de pratiques culturales permettant la préservation des sols et limitant les risques de pollutions ;
- la participation à une gestion économe et équilibrée des ressources en eau ;
- la prise en compte de règles dans les domaines de la sécurité sanitaire et de l'hygiène ;
- la prise en compte des besoins des animaux en matière d'alimentation et de bien-être ;
- la contribution de l'exploitation à la protection des paysages et de la diversité biologique.
|
Java
|
UTF-8
| 3,715
| 1.601563
| 2
|
[] |
no_license
|
/*
* Decompiled with CFR 0.151.
*
* Could not load the following classes:
* android.os.Handler
*/
package com.zhiyun.renderengine.business.display;
import android.os.Handler;
import com.zhiyun.renderengine.bean.TextureFormat;
import com.zhiyun.renderengine.business.display.DisplayRender;
import com.zhiyun.renderengine.business.display.DisplayRender$l$a;
import d.v.b0.c.b;
public class DisplayRender$l
implements b {
public final /* synthetic */ DisplayRender a;
public DisplayRender$l(DisplayRender displayRender) {
this.a = displayRender;
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public void a(byte[] object, TextureFormat object2, int n10, int n11, float[] fArray, int n12) {
object2 = this.a;
int n13 = DisplayRender.d((DisplayRender)object2);
if (n13 != n10 || (n13 = DisplayRender.f((DisplayRender)(object2 = this.a))) != n11) {
object2 = this.a;
boolean bl2 = true;
DisplayRender.h((DisplayRender)object2, bl2);
}
object2 = DisplayRender.i(this.a);
synchronized (object2) {
block6: {
Object object3;
block8: {
block7: {
DisplayRender displayRender = this.a;
DisplayRender.k(displayRender, object);
object = this.a;
DisplayRender.l((DisplayRender)object, fArray);
object = this.a;
DisplayRender.m((DisplayRender)object, n12);
object = this.a;
DisplayRender.e((DisplayRender)object, n10);
object = this.a;
DisplayRender.g((DisplayRender)object, n11);
object = this.a;
object = DisplayRender.j((DisplayRender)object);
if (object == null) break block6;
object = this.a;
if ((object = DisplayRender.n((DisplayRender)object)) == null) break block7;
object = this.a;
object = DisplayRender.n((DisplayRender)object);
int n14 = ((byte[])object).length;
object3 = this.a;
n10 = ((byte[])(object3 = DisplayRender.j((DisplayRender)object3))).length;
if (n14 == n10) break block8;
}
object = this.a;
object3 = DisplayRender.j((DisplayRender)object);
n10 = ((byte[])object3).length;
object3 = new byte[n10];
DisplayRender.o((DisplayRender)object, object3);
}
object = this.a;
object = DisplayRender.j((DisplayRender)object);
object3 = this.a;
object3 = DisplayRender.n((DisplayRender)object3);
Object object4 = this.a;
object4 = DisplayRender.j((DisplayRender)object4);
n11 = ((Object)object4).length;
fArray = null;
System.arraycopy(object, 0, object3, 0, n11);
}
return;
}
}
public void b(int n10, int n11) {
Handler handler = DisplayRender.q(this.a);
if (handler != null) {
handler = DisplayRender.q(this.a);
DisplayRender$l$a displayRender$l$a = new DisplayRender$l$a(this, n10, n11);
handler.post((Runnable)displayRender$l$a);
}
}
}
|
Java
|
UTF-8
| 5,150
| 2.71875
| 3
|
[] |
no_license
|
package com.photon.codechallenge.shortestpath.utils;
import com.photon.codechallenge.shortestpath.utils.LowCostPathFinder;
import com.photon.codechallenge.shortestpath.utils.SampleInputs;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests to verify the correctness of the lowest cost path algorithm.
*/
public class LowCostPathFinderTest {
@Test
public void test6X5NormalMatrix() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_1) == 16);
assertEquals(LowCostPathFinder.getStatus(), "Yes");
assertEquals(LowCostPathFinder.getResultantPath(), "[1 2 3 4 4 5]");
}
@Test
public void test6X5NormalMatrix1() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_2) == 11);
assertEquals(LowCostPathFinder.getStatus(), "Yes");
assertEquals(LowCostPathFinder.getResultantPath(), "[1 2 1 5 4 5]");
}
@Test
/**
* 5X3 matrix with no path <50
*/
public void test5X3MatrixWithNoValidPath() {
// assertTrue(CommonUtils.findShortestPathInternal(SampleInputs.TEST_CASE_3) ==
// 48);
}
@Test
public void test1X5NormalMatrix() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_4) == 26);
assertEquals(LowCostPathFinder.getStatus(), "Yes");
assertEquals(LowCostPathFinder.getResultantPath(), "[1 1 1 1 1]");
}
@Test
public void test5X1NormalMatrix() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_5) == 3);
assertEquals(LowCostPathFinder.getStatus(), "Yes");
assertEquals(LowCostPathFinder.getResultantPath(), "[4]");
}
/**
* Non numeric input, Optional
*/
@Test
public void testNonNumeric() {
// assertTrue(CommonUtils.findShortestPathInternal(SampleInputs.TEST_CASE_6) ==
// 11);
}
@Test
public void testNoInputMatrix() {
// assertTrue("Empty Input", !CommonUtils.isValidInput(TEST_CASE_7));
}
@Test
/**
* Starting with >50
*/
public void testMatrixWithStartingGraterThanThreshold() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_8) == 0);
assertEquals(LowCostPathFinder.getStatus(), "No");
assertEquals(LowCostPathFinder.getResultantPath(), "[]");
}
@Test
public void testMatrixWithOneValueGraterThanThreshold() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_9) == 14);
assertEquals(LowCostPathFinder.getStatus(), "Yes");
assertEquals(LowCostPathFinder.getResultantPath(), "[3 2 1 3]");
}
@Test
public void testMatrixWithNegativeValues() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_10) == 0);
assertEquals(LowCostPathFinder.getStatus(), "Yes");
assertEquals(LowCostPathFinder.getResultantPath(), "[2 3 4 1]");
}
@Test
/**
* Complete path vs. lower cost incomplete path
*/
public void testMatrixWithCompletePathLowerCost() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_11) == 10);
assertEquals(LowCostPathFinder.getStatus(), "Yes");
assertEquals(LowCostPathFinder.getResultantPath(), "[4 4]");
}
@Test
/**
* Longer incomplete path vs. shorter lower cost incomplete path
*/
public void testMatrixWithLongerIncompletePathShorterLowerCost() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_12) == 10);
assertEquals(LowCostPathFinder.getStatus(), "No");
assertEquals(LowCostPathFinder.getResultantPath(), "[4 4]");
}
@Test
public void testMatrixWithLargeNoOfColumns() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_13) == 20);
assertEquals(LowCostPathFinder.getStatus(), "Yes");
assertEquals(LowCostPathFinder.getResultantPath(), "[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]");
}
@Test
public void testMatrixWith3X5() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_14) == 48);
assertEquals(LowCostPathFinder.getStatus(), "No");
assertEquals(LowCostPathFinder.getResultantPath(), "[1 1 1]");
}
@Test
public void testMatrixWith5X6() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.TEST_CASE_15) == 11);
assertEquals(LowCostPathFinder.getStatus(), "Yes");
assertEquals(LowCostPathFinder.getResultantPath(), "[1 2 1 5 4 5]");
}
@Test
public void testCommonCases() {
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.GENERAL_TEST_CASE_1) == 10);
assertEquals(LowCostPathFinder.getStatus(), "No");
assertEquals(LowCostPathFinder.getResultantPath(), "[4 4]");
assertTrue(LowCostPathFinder.findShortestPath(SampleInputs.GENERAL_TEST_CASE_2) == 48);
assertEquals(LowCostPathFinder.getStatus(), "No");
assertEquals(LowCostPathFinder.getResultantPath(), "[2 2 2]");
}
}
|
Java
|
UTF-8
| 3,127
| 2.078125
| 2
|
[] |
no_license
|
package hello;
import com.fasterxml.jackson.databind.ObjectMapper;
import hello.model.Media;
import hello.model.MediaEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.List;
@Repository
public class MediaEntryRepository {
@Autowired
private ResourceLoader resourceLoader;
//@Autowired
//private ResourceLoader resourceLoader2;
private File myFile;
private File myFile2;
@PostConstruct
private void init() throws IOException {
Resource resource = resourceLoader.getResource("classpath:MediaEntries.json");
if (resource != null) {
myFile = resource.getFile();
}
}
public MediaEntry getMediaById(String id) {
final ObjectMapper mapper = new ObjectMapper();
Media readValues = null;
MediaEntry readValue=null;
try {
readValues = mapper.readValue(myFile, Media.class);
//System.out.println("ID Param is: "+id);
for (MediaEntry m: readValues.getEntries()) {
//System.out.println("ID: " + m.getIdUri());
if ( m.getIdUri().equalsIgnoreCase(id)) {
//System.out.println("ID Found is: " + m.getIdUri());
readValue = m;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return readValue;
}
//@Override
public Page<MediaEntry> getAllMedia(Pageable pageable) {
final ObjectMapper mapper = new ObjectMapper();
Media readValues = null;
Page<MediaEntry> searchResults = null;//mediaRepository.findAll(pageable);
try {
readValues = mapper.readValue(myFile, Media.class);
searchResults = new PageImpl<MediaEntry>(readValues.getEntries(), pageable,2);
//(Page<MediaEntry>) readValues.getEntries();
//mapper.readValue(myFile,Media.class);
} catch (IOException e) {
e.printStackTrace();
}
//searchResults = mediaRepository.findAll();
return searchResults;//new PageImpl<>(searchResults, pageable,1);
}
public List<MediaEntry> getMediaList()
{
final ObjectMapper mapper = new ObjectMapper();
Media readValues = null;
List<MediaEntry> searchResults = null;//mediaRepository.findAll(pageable);
try {
readValues = mapper.readValue(myFile, Media.class);
searchResults = readValues.getEntries();
} catch (IOException e) {
e.printStackTrace();
}
return searchResults;
}
// @Override
// public List<MpxNotificationInfo> getNotifications(Long sequence) {
// return null;
// }
}
|
JavaScript
|
UTF-8
| 2,644
| 2.625
| 3
|
[] |
no_license
|
import React, { Component } from 'react';
class UserForm extends Component {
constructor() {
super();
this.state = {
fname: '',
lname: '',
email: '',
dob: '',
bio: ''
};
}
onChange = (e) => {
e.persist()
this.setState(state => (
{
...state,
[e.target.name]: e.target.value
}
));
}
onSubmit = (e) => {
e.preventDefault();
// get our form data out of state
const { localStorage } = window;
let localData = JSON.parse(localStorage.getItem('data')) || []
const theDataTobeAdded = {
fname : this.state.fname,
lname : this.state.lname,
email : this.state.lname,
dob : this.state.dob,
bio : this.state.bio,
id : localData.length
}
this.props.addatafunction(theDataTobeAdded)
let new_local_data = JSON.stringify([...localData, theDataTobeAdded])
localStorage.setItem('data', new_local_data)
this.setState({
fname : '',
lname : '',
email : '',
dob : '',
bio : ''
})
}
render() {
const { fname, lname, email, dob, bio } = this.state;
return (
<form onSubmit={this.onSubmit}>
<input
type="text"
name="fname"
value={fname}
required
onChange={this.onChange}
placeholder='First Name'
/>
<input
type="text"
name="lname"
required
value={lname}
onChange={this.onChange}
placeholder='Last Name'
/>
<input
type="email"
name="email"
required
value={email}
onChange={this.onChange}
placeholder='Email'
/>
<input
type="date"
name="dob"
required
value={dob}
onChange={this.onChange}
/>
<input
type="textarea"
name="bio"
required
value={bio}
onChange={this.onChange}
placeholder='Bio'
/>
<button type="submit">Submit</button>
</form>
);
}
}
export default UserForm;
|
Python
|
UTF-8
| 3,457
| 2.859375
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*- #
import random
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def init_review_dict():
"""
Initializes the dictionary with the review data.
# Returns:
review_dict: dict, dictionary with the review data.
"""
review_dict = {
'id_review_product': None,
'url': None,
'serie_url': None,
'review_text': None,
'review_date': None,
'writer_pseudo': None,
'review_rating': None,
'collect_date': str(time.strftime("%Y_%m_%d")),
}
return review_dict
def collect_reviews_data(driver, url):
"""
Collects the reviews data for the current page.
# Args:
driver: selenium driver
url: str, url of a product.
product_dict: dict, product's information
# Return:
product_dict: dict, dictionary with product's data.
"""
reviews_dicts = []
reviews = driver.find_elements_by_class_name("review-card")
for id_review, review in enumerate(reviews):
# Initialize the dictionary to save the data for the current review.
review_dict = init_review_dict()
# Review's ID
try:
review_dict['id_review_product'] = id_review + 1
except:
pass
# Review's url
try:
review_dict['url'] = url
except:
pass
# Serie's url
try:
links = driver.find_elements_by_xpath('//*[@id="content-layout"]/div/a')
review_dict['serie_url'] = links[-1].get_attribute('href')
if review_dict['serie_url'] == review_dict['url']:
review_dict['serie_url'] = links[-2].get_attribute('href')
except:
pass
# Review's rating
try:
review_dict['review_rating'] = review.find_element_by_class_name("stareval-note").get_attribute("textContent")
except:
pass
# Review's date
try:
review_dict['review_date'] = review.find_element_by_class_name("review-card-meta-date").get_attribute("textContent").strip().replace('\n','').replace('Publiée le ','')
except:
pass
# Review's text
try:
review_dict['review_text'] = review.find_element_by_class_name("review-card-content").get_attribute("textContent").strip().replace('\n','').replace('\"',"'")
except:
pass
# Writer's pseudo
try:
review_dict['writer_pseudo'] = review.find_element_by_class_name("review-card-user-infos").find_element_by_tag_name("div").find_element_by_tag_name("a").get_attribute('textContent')
except:
pass
reviews_dicts.append(review_dict)
# Show other sections that contain reviews and collect them
try:
while driver.find_element_by_class_name("button-right").get_attribute('href') is not None:
more_reviews_btn = WebDriverWait(driver, 5).until(
EC.element_to_be_clickable((By.CLASS_NAME, 'button-right')))
driver.execute_script("arguments[0].scrollIntoView(true);", more_reviews_btn)
driver.execute_script("arguments[0].click();", more_reviews_btn)
reviews_dicts += collect_reviews_data(driver, url)
except:
pass
return reviews_dicts
|
C#
|
UTF-8
| 1,116
| 2.703125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Controls;
namespace MapGenerator
{
public class Test
{
Grid main = new Grid();
StackPanel stp = new StackPanel();
TextBlock size = new TextBlock();
TextBlock floorc = new TextBlock();
TextBlock floorn = new TextBlock();
TextBlock floorreal = new TextBlock();
public Test(Grid g)
{
main = g;
stp.Children.Add(size);
stp.Children.Add(floorc);
stp.Children.Add(floorn);
stp.Children.Add(floorreal);
main.Children.Add(stp);
}
public void updt(int h, int w, int fc, int fn, int fr)
{
size.Text = "height: "+h+ "width: " + w;
floorc.Text = "curcount: " + fc;
floorn.Text = "needcount: " + fn;
floorreal.Text = "realcount: " + fr;
}
}
}
|
PHP
|
UTF-8
| 559
| 2.703125
| 3
|
[] |
no_license
|
<?php
function smarty_function_grid_view($paras)
{
$gridview ="<table class='".$paras['css']."'><tr>";
foreach($paras['fields'] as $value){
$gridview.= "<td><strong>".strtoupper($value)."</strong></td>";
}
$gridview.= "</tr>";
for($i=0;$i<$paras['counts']; $i++)
{
$gridview.= "<tr>";
foreach($paras['data'][$i] as $value){
$gridview.= "<td>".$value."</td>";
}
$gridview.= "</tr>";
}
$gridview.= "</table>";
return $gridview;
}
?>
|
Python
|
UTF-8
| 2,155
| 3.90625
| 4
|
[
"MIT"
] |
permissive
|
'''
Description:
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:
1 <---
/ \
2 3 <---
\ \
5 4 <---
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from typing import List
from collections import defaultdict
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root:
# Quick response for empty tree
return []
# key: depth
# value: value of right-most node
self.side_view_dict = defaultdict( int )
self.max_depth = 0
def helper( node: TreeNode, depth: int):
if node:
if self.side_view_dict.get(depth, None) == None:
self.side_view_dict[depth] = node.val
self.max_depth = max( self.max_depth, depth)
# Let right sub-tree go before left sub-tree in order to get right side view
helper( node.right, depth+1 )
helper( node.left, depth+1 )
# ----------------------------------------
helper( node = root, depth = 0 )
return [ self.side_view_dict[depth] for depth in range(0, self.max_depth+1) ]
# n : the number of nodes in binary tree
## Time Complexity: O( n )
#
# The overhead in time is the cost of DFS traversal, which is of O( n ).
## Space Complexity: O( n )
#
# The overhead in space is the stroage for recursion stack, which is of O( n ).
def test_bench():
root = TreeNode( 1 )
root.left = TreeNode( 2 )
root.right = TreeNode( 3 )
root.left.right = TreeNode( 5 )
root.right.right = TreeNode( 4 )
# expected output:
'''
[1, 3, 4]
'''
print( Solution().rightSideView( root ) )
if __name__ == '__main__':
test_bench()
|
Markdown
|
UTF-8
| 2,653
| 3.515625
| 4
|
[] |
no_license
|
# url命名:
## 为什么需要url命名?
因为url是经常变化的。如果在代码中写死可能会经常改代码。给url取个名字,以后使用url的时候就使用他的名字进行反转就可以了,就不需要写死url了。
## 如何给一个url指定名称?
在`path`函数中,传递一个`name`参数就可以指定。示例代码如下:
```python
urlpatterns = [
path('',views.index,name='index'),
path('login/',views.login,name='login')
]
```
## 应用命名空间:
在多个app之间,有可能产生同名的url。这时候为了避免反转url的时候产生混淆,可以使用应用命名空间,来做区分。定义应用命名空间非常简单,只要在`app`的`urls.py`中定义一个叫做`app_name`的变量,来指定这个应用的命名空间即可。示例代码如下:
```python
# 应用命名空间
app_name = 'front'
urlpatterns = [
path('',views.index,name='index'),
path('login/',views.login,name='login')
]
```
以后在做反转的时候就可以使用`应用命名空间:url名称`的方式进行反转。示例代码如下:
```python
login_url = reverse('front:login')
```
## 应用(app)命名空间和实例命名空间:
一个app,可以创建多个实例。可以使用多个url映射同一个app。所以这就会产生一个问题。以后在做反转的时候,如果使用应用命名空间,那么就会发生混淆。为了避免这个问题。我们可以使用实例命名空间。实例命名空间也是非常简单,只要在`include`函数中传递一个`namespace`变量即可。示例代码如下:
```python
urlpatterns = [
path('',include('front.urls')),
# 同一个app下有两个实例
path('cms1/',include('cms.urls',namespace='cms1')),
path('cms2/',include('cms.urls',namespace='cms2')),
]
```
以后在做反转的时候,就可以根据实例命名空间来指定具体的url。示例代码如下:
```python
def index(request):
username = request.GET.get("username")
if username:
return HttpResponse('CMS首页')
else:
# 获取当前的命名空间
current_namespace = request.resolver_match.namespace
return redirect(reverse("%s:login"%current_namespace))
```
# url反转:
1. 如果在反转url的时候,需要添加参数,那么可以传递`kwargs`参数到`revers`函数中。示例代码如下:
```python
detail_url = reverse('detail',kwargs={"article_id":1,'page':2})
```
2. 如果想要添加查询字符串的参数,则必须手动的进行拼接。示例代码如下:
```python
login_url = reverse('login') + "?next=/"
```
|
C
|
UTF-8
| 1,514
| 2.953125
| 3
|
[] |
no_license
|
#include "shell.h"
/* global variable for ^C handling */
unsigned int sig_flag;
/**
* sig_handler - handles ^C signal interupt
* @uuv: unused variable (required for signal function prototype)
*
* Return: void
*/
static void sig_handler(int uuv)
{
(void) uuv;
if (sig_flag == 0)
_puts("\n$ ");
else
_puts("\n");
}
/**
* main - main function for the shell
* @argc: number of arguments passed to main
* @argv: array of arguments passed to main
* @environment: array of environment variables
*
* Return: 0 or exit status, or ?
*/
int main(int argc __attribute__((unused)), char **argv, char **environment)
{
size_t len_buffer = 0;
unsigned int is_pipe = 0, i;
vars_t vars = {NULL, NULL, NULL, 0, NULL, 0, NULL};
vars.argv = argv;
vars.env = make_env(environment);
signal(SIGINT, sig_handler);
if (!isatty(STDIN_FILENO))
is_pipe = 1;
if (is_pipe == 0)
_puts("$ ");
sig_flag = 0;
while (getline(&(vars.buffer), &len_buffer, stdin) != -1)
{
sig_flag = 1;
vars.count++;
vars.commands = tokenize(vars.buffer, ";");
for (i = 0; vars.commands && vars.commands[i] != NULL; i++)
{
vars.av = tokenize(vars.commands[i], "\n \t\r");
if (vars.av && vars.av[0])
if (check_for_builtins(&vars) == NULL)
check_for_path(&vars);
free(vars.av);
}
free(vars.buffer);
free(vars.commands);
sig_flag = 0;
if (is_pipe == 0)
_puts("$ ");
vars.buffer = NULL;
}
if (is_pipe == 0)
_puts("\n");
free_env(vars.env);
free(vars.buffer);
exit(vars.status);
}
|
Markdown
|
UTF-8
| 12,410
| 3.234375
| 3
|
[] |
no_license
|

# Rails View Templating
### Why is this important?
<!-- framing the "why" in big-picture/real world examples -->
*This workshop is important because:*
We want pages that users can see and interact with! And we want to take advantage of how easy Rails makes views... if we follow the "Rails way".
### Objectives
*After this lesson, developers will be able to:*
- Compare client-side and server-side templating.
- Describe how layouts, view templates, and partials fit together for Rails' server-side templating.
### Where should we be now?
*Before this workshop, developers should already be able to:*
- Start a Rails app with a route and controller for a home page view.
- Incorporate routes, a controller, and a model for a single resource.
- Read and write routes.
- Describe templating.
## Warmup: Client-side vs Server-side Template Rendering
Work with a partner to answer the following questions. Write your answers on your table.
1. What is HTML "templating"?
2. We've been rendering templates on the client side with Angular, React, and/or ES6 string template literals. This generally means the user will see part of the page, but the rest of the page is filled in after data comes back from an AJAX call. List at least one benefit and one drawback of this approach. (Consider things like page load time, number of HTTP requests, user interaction, search engines reading pages.)
3. Rails will render templates on the server side, adding data into an HTML file before sending it to the client side. List at least one benefit and one drawback of this approach. (Consider things like page load time, number of HTTP requests, user interaction, search engines reading pages.)
## Putting Together the Page
In Rails, the pages a user sees are rendered on the server side as a combination of a layout template and a view template. The view template, in turn, might be built up with one or more smaller "partial" templates. The server has stitches together these pieces into one HTML file before sending the completed file to the client side for display.
### Layout
When a Rails app is created, Rails will automatically add a main application layout file: **`app/views/layouts/application.html.erb`**.
We can use the main application layout for the lines of HTML that link site-wide CSS and JavaScript files. We can also use it for material like a footer that stays the same across all pages from multiple controllers.
<img src="https://raw.githubusercontent.com/sf-wdi-34/angular-routing/master/views_layouts_malcolm.png" alt="single goat show page with details" width="60%">
Templates are always rendered into a `<%= yield %>` tag in a layout. The `app/views/layouts/application.html.erb` layout already contains a `yield` statement, a `<head>` section, and links to the app's CSS and JavaScript files.
It is possible to use multiple layouts.
### View Templates
View templates contain all the content that's specific to one page.
Each controller will have its own directory inside `app/views` to contain the view templates used by that controller. For fully CRUD-able RESTful resources, there will be views for:
- index
- show
- new
- edit
### Partials
Partials allow us to take a portion of a template and move it into a separate file.
**Check for Understanding:** Why might we want to separate out portions of our HTML view templates?
<details><summary>Ideas</summary>
- A best practice is to always keep every template small. A rule of thumb would be to keep templates to about 50 lines for readability. If we wrote the bulk of our HTML directly in view templates, we'd quickly exceed this limit.
- We might have content that is repeated on more than one page associated with a controller - partials help us reuse HTML code for this content.
- Separating code into partials makes our views more modular and easier to change.
</details>
Partials are always named starting with an underscore: `app/views/products/_form.html.erb` or `app/views/shared/_menu.rb`.
### Adding Partials to a View Template
Partials are included from inside a view file. The syntax uses the view helper method `render`: `<%= render "form" %>`. Note that you don't include the starting `_` when rendering a partial.
Here is syntax for some use cases:
1. Most common: In a view, render a partial from a file called `app/views/products/_product.html.erb`.
```erb
<%- # inside app/views/products/show.html.erb %>
<%= render "product" %>
```
2. In a view, render a partial from a file inside a directory, called `app/views/shared/_footer.html.erb`.
```erb
<%- # inside app/views/products/show.html.erb %>
<%= render "shared/footer" %>
```
3. Less common: You can also pass data into a partial.
Pass a variable `product` to a partial to be used within the partial:
```erb
<%- # inside app/views/products/index.html.erb %>
<% @products.each do |product| %>
<%= render partial: "product", locals: {product: product} %>
<% end %>
or
<%= render partial: "customer", object: @customer %>
```
4. There's also a shorter syntax for the common pattern of repeating a partial for all items in a collection:
```erb
<%- # inside app/views/products/index.html.erb %>
<%= render partial: "product", collection: @products %>
```
The Layouts and Rendering Rails guide section on [using partials](http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials) has more information and examples.
#### Check for Understanding: Using Partials and Layouts
1) How can we split up pages into layout and views if the website is structured as shown below?
<img src="https://raw.githubusercontent.com/sf-wdi-34/angular-routing/master/goats_app.png" width="600px" alt="goat app screenshots">
<hr>
In Rails, the page `<head>` will already be in the application layout. We can move the top menu and the footer into the layout to reduce repetition in the individual pages.
**Layout:**
```html
<!DOCTYPE html>
<head>
<!-- metadata, CSS link, JS link -->
</head>
<body>
<header>
<!-- all header & menu html.erb -->
</header>
<%= yield %>
<footer>
<!-- all footer html.erb -->
</footer>
</body>
```
**Templates:**
```
<!-- app/views/goats/show.html.erb -->
<!-- show page main content -->
<%= image_tag(@goat.image_url) %>
<!-- continue single goat show page html.erb -->
```
```
<!-- app/views/goats/index.html.erb -->
<!-- index page main content -->
<%= @goats.each do |goat| %>
<!-- continue goat list page html.erb -->
```
Remember: `yield` is where the current page content will be rendered.
We can also move the header and/or the footer into a partial. This option would be best when we only use the menu on some pages, and other pages use different content for that portion of the page. For example, the home page might use a hero image in place of the header.
2) What would our layout and view code look like if we split the header/menu section and the hero image into individual partials?
**Layout:**
```
<!DOCTYPE html>
<head>
<!-- metadata, CSS link, JS link -->
</head>
<body>
<%= yield %>
<footer>
<!-- all footer html.erb -->
</footer>
</body>
```
**Templates:**
```
<!-- app/views/wecome/about.html.erb -->
<%= render "shared/header" %>
<!-- continue current page content -->
```
or, on another page,
```
<!-- app/views/welcome/index.html.erb -->
<%= render "shared/hero_image" %>
<!-- continue current page content -->
```
Alternately, if the header is on every page, we could keep the main layout file short by adding a named `yield` and [`content_for`](http://guides.rubyonrails.org/layouts_and_rendering.html#using-the-content-for-method).
**Layout with named `yield` and `content_for`:**
```
<!DOCTYPE html>
<html>
<head>
<%= yield :head %>
</head>
<body>
<%= yield %>
</body>
</html>
```
**Templates**:
```
<% content_for :head do %>
<title>Goat Tracker - About</title>
<% end %>
<%= render "shared/header" %>
<!-- rest of the about page content -->
```
> A very common example of using partials in Rails is moving code for a new/edit form into a partial.
## Views with Controllers
Now that we've gone over how layout templates, view templates, and partial templates come together to create the pages users see, let's dive into how our apps' controllers will trigger rendering these views.
Every route in Rails will execute a method inside a controller. In Rails, the basic logic for rendering an HTML view is straightforward. When the method is executed:
1. Rails looks for a directory inside `views` corresponding to the controller's name (directory `posts` for `PostsController`).
2. Inside that folder, Rails looks for an `.html.erb` file with a name matching the method's name.
For example, if we visit `http://localhost:3000/posts` in the browser, that GET request should be routed to the PostsController#index method (because of RESTful conventions).
By default, controller methods will render views files that match the controller method name. So when Rails executes the code in `index`, it will look for and render a template located in `app/views/posts/index.html.erb` unless we tell it to do something else.
**Check for Understanding:** Which RESTful controller actions in Rails usually render an HTML view? What are their purposes?
<details><summary>click for a list</summary>
* `index` - display a list of all the records for one type of resource
* `show` - display details of one singe record
* `new` - display a form for users to create a new record
* `edit` - display a form for users to update a record
</details>
<br>
And which RESTful controller actions in Rails DO NOT render an HTML view? What are their purposes?
<details><summary>click for a list</summary>
* `create` - work with the database to create a record (based on form input)
* `update` - work with the database to update one record (based on form input)
* `destroy` - work with the database to destroy one record
</details>
### Controller Redirect
Lets take a look at a `create` action:
```ruby
# inside app/controllers/PostsController.rb
def create
# ...
if post.save
redirect_to "/posts/#{post.id}", notice: 'Post was successfully created.'
else
render :new
end
end
```
**Check for Understanding:** What is happening in the code above?
<details><summary>click for explanation</summary>
Based on the result of trying to save the post, the method will execute either the code in the "if" or in the "else".
If the new post correctly saves, the response will be a redirect to that post's show page. If the new post doesn't save correctly, the new post form view is rendered again. Note that neither one of these options renders a <code>create.html.erb</code> file.
</details>
We've seen two ways to do something other than rendering the HTML view that matches our controller action name:
- We can redirect to another action.
- We can use a `render` statement to specify a view to render that doesn't match the action name.
### JSON View Templates
Rails 5 comes bundled with a [`jbuilder`](https://github.com/rails/jbuilder) gem that helps us create JSON views instead of HTML. This gives us the flexibility to easily respond to requests for JSON content.
**Check for Understanding**
An app might have a directory `app/views/products` with the files listed below. Explain in 6 or fewer words what each file is for.
```
_form.html.erb
edit.html.erb
index.html.erb
index.json.jbuilder
new.html.erb
show.html.erb
show.json.jbuilder
```
### Closing Thoughts
- Describe how layouts, view templates, and partials work together.
### Additional Resources
* [Glossary](glossary.md)
* Rails Guides:
* [Action View Overview](http://guides.rubyonrails.org/action_view_overview.html)
* [Layouts and Rendering](http://guides.rubyonrails.org/layouts_and_rendering.html)
* ActionController's [`render`](http://api.rubyonrails.org/classes/ActionController/Base.html#class-ActionController::Base-label-Renders)
* ActionController's [`redirect_to`](http://api.rubyonrails.org/classes/ActionController/Base.html#class-ActionController::Base-label-Redirects)
|
Java
|
UTF-8
| 2,196
| 2.453125
| 2
|
[] |
no_license
|
package yncrea.lab04.web.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import yncrea.lab04.core.entity.Company;
import yncrea.lab04.core.service.CompanyService;
import java.util.List;
@Controller
public class CompanyController {
@Autowired
private CompanyService companyService;
private static final Logger LOGGER = LoggerFactory.getLogger(CompanyController.class);
// public CompanyController(CompanyService companyService) {
// this.companyService = companyService;
// }
// @RequestMapping(path = "/")
// public String welcomePage() {
// return "welcome";
// }
@RequestMapping(path = "/list")
public String getListOfCompanies(ModelMap modelMap) {
final List<Company> companies = companyService.findAllWithProjects();
modelMap.addAttribute("companies", companies);
LOGGER.debug("Get all companies");
LOGGER.info("Displaying all companies");
return "companiesList";
}
@RequestMapping(path = "/form",method = RequestMethod.GET)
public String getForm(ModelMap modelMap) {
Company company = new Company();
modelMap.addAttribute(company);
return "companyForm";
}
@RequestMapping(path = "/form",method = RequestMethod.POST)
public String submitForm(@ModelAttribute("company") Company company) {
companyService.save(company);
LOGGER.info("Company created successfully");
return "redirect:list";
}
@RequestMapping(path = "{id}/delete",method = RequestMethod.GET)
public String deleteCompany(@PathVariable Long id) {
LOGGER.warn("Caution : Please add a null check");
companyService.deleteById(id);
LOGGER.info("Company deleted");
return "redirect:/list";
}
}
|
C
|
UTF-8
| 757
| 3.4375
| 3
|
[] |
no_license
|
//
// Created by PABLO on 08/05/2018.
//
#include <stdio.h>
int get_int(char s[30]);
int main(void){
int x=get_int("Introduzca la altura \n");
for (int i=0;i<=x;i++){
for (int j=x;j>=0;j--){
if (i<j){
printf(" ");
}
else{
printf("#");
}
}
printf(" ");
for(int j=0;j<=x;j++){
if(j<=i){
printf("#");
}
else{
printf(" ");
}
}
printf("\n");
}
}
int get_int(char s[30]){
int x;
printf("%s",s);
scanf_s("%i",&x); // CLion is advicing me to use scanf_s instead of the traditional sacanf cause it deprecates
return x;
}
|
Python
|
UTF-8
| 2,633
| 2.703125
| 3
|
[] |
no_license
|
import pandas as pd
import numpy as np
import chart_studio.plotly as py
import plotly.graph_objs as go
import plotly.express as px
df=pd.read_csv('D:/udemy_kurs_py/PyProj/214.agri.csv')
df.drop('text',axis=1,inplace=True)
df.drop('category',axis=1,inplace=True)
print(df.head())
print(df.columns)
print(df.shape)
print(df.isnull().sum())
df=df.sort_values(by='total exports',ascending=False)
fig=px.bar(df.iloc[:10,:],x='state',y='total exports',
color='state',title='Top 10',
template='plotly_dark')
fig.show()
fig = go.Figure(data=go.Choropleth(
locations=df['code'],
z=df['total exports'].astype(float),
locationmode='USA-states',
colorscale='Greens',
autocolorscale=False,
text=df['state'], # hover text
marker_line_color='white', # line markers between states
colorbar_title="Millions USD"
))
fig.update_layout(
title_text='USA Agriculture Exports by State',
geo = dict(
scope='usa',
projection=go.layout.geo.Projection(type = 'albers usa'),
showlakes=True, # lakes
lakecolor='rgb(0, 0, 255)'),
)
fig.update_geos(
resolution=50,
showcoastlines=True, coastlinecolor="RebeccaPurple",
#showland=True, landcolor="LightGreen",
showocean=True, oceancolor="LightBlue",
#showlakes=True, lakecolor="Blue",
showrivers=True, rivercolor="Blue"
)
fig.show()
df=pd.read_csv('D:/udemy_kurs_py/PyProj/215.gdp.csv')
print(df.head())
print(df.columns)
print(df.shape)
print(df.isnull().sum())
df=df.sort_values(by='GDP (BILLIONS)',ascending=False)
fig=px.bar(df.iloc[:10,:],x='COUNTRY',y='GDP (BILLIONS)',
color='COUNTRY',title='Top 10',
template='plotly_dark')
fig.show()
fig = go.Figure(data=go.Choropleth(
locations=df['CODE'],
z=df['GDP (BILLIONS)'].astype(float),
colorscale='Blues',
autocolorscale=False,
text=df['COUNTRY'], # hover text
marker_line_color='white', # line markers between states
colorbar_title="GDP Billions USD"
))
fig.update_layout(
title_text='World GDP in Billions',
geo = dict(
#projection=go.layout.geo.Projection(type = 'albers usa'),
projection_type='equirectangular',
showlakes=True, # lakes
lakecolor='rgb(0, 0, 255)'),
)
fig.update_geos(
resolution=50,
showcoastlines=True, coastlinecolor="RebeccaPurple",
#showland=True, landcolor="LightGreen",
showocean=True, oceancolor="LightBlue",
#showlakes=True, lakecolor="Blue",
showrivers=True, rivercolor="Blue"
)
fig.show()
|
Java
|
UTF-8
| 9,922
| 2.140625
| 2
|
[] |
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 view.subarea;
import controller.SubareaController;
import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.border.LineBorder;
import model.Subarea;
/**
*
* @author Bruno
*/
public class CadastrarSubarea extends javax.swing.JInternalFrame {
SubareaController subareaController = new SubareaController();
/**
* Creates new form CadastrarAutor
*/
public CadastrarSubarea() {
initComponents();
getRootPane().setDefaultButton(btn_confirmar);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollBar1 = new javax.swing.JScrollBar();
panel_principal = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
panel_dados = new javax.swing.JPanel();
label_nome_subarea = new javax.swing.JLabel();
input_nome_subarea = new javax.swing.JTextField();
label_codigo_subarea = new javax.swing.JLabel();
input_codigo_subarea = new javax.swing.JTextField();
panel_botoes = new javax.swing.JPanel();
btn_confirmar = new javax.swing.JButton();
btn_voltar = new javax.swing.JButton();
setClosable(true);
setMaximizable(true);
setResizable(true);
setTitle("Cadastrar subárea");
setToolTipText("Cadastrar subárea");
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/img/diagram.png"))); // NOI18N
jPanel1.add(jLabel1);
panel_dados.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastrar subárea"));
panel_dados.setToolTipText("Cadastrar subárea");
panel_dados.setLayout(new java.awt.GridLayout(2, 2, 0, 10));
label_nome_subarea.setText("Nome da subárea:");
panel_dados.add(label_nome_subarea);
panel_dados.add(input_nome_subarea);
label_codigo_subarea.setText("Código da subárea:");
panel_dados.add(label_codigo_subarea);
input_codigo_subarea.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
input_codigo_subareaActionPerformed(evt);
}
});
panel_dados.add(input_codigo_subarea);
panel_botoes.setBorder(javax.swing.BorderFactory.createEtchedBorder());
java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(java.awt.FlowLayout.LEADING, 10, 5);
flowLayout1.setAlignOnBaseline(true);
panel_botoes.setLayout(flowLayout1);
btn_confirmar.setText("Confirmar");
btn_confirmar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_confirmarActionPerformed(evt);
}
});
panel_botoes.add(btn_confirmar);
btn_voltar.setText("Voltar");
btn_voltar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_voltarActionPerformed(evt);
}
});
panel_botoes.add(btn_voltar);
javax.swing.GroupLayout panel_principalLayout = new javax.swing.GroupLayout(panel_principal);
panel_principal.setLayout(panel_principalLayout);
panel_principalLayout.setHorizontalGroup(
panel_principalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_principalLayout.createSequentialGroup()
.addContainerGap()
.addGroup(panel_principalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(panel_botoes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(panel_dados, javax.swing.GroupLayout.DEFAULT_SIZE, 610, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(16, 16, 16))
);
panel_principalLayout.setVerticalGroup(
panel_principalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_principalLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panel_dados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(panel_botoes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(panel_principal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel_principal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void input_codigo_subareaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_input_codigo_subareaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_input_codigo_subareaActionPerformed
private void btn_confirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_confirmarActionPerformed
try {
if(this.validarCampos()){
this.validarCodigo();
int opcao = JOptionPane.showConfirmDialog(null, "Deseja salvar nova subárea?", "Confirmação.", JOptionPane.INFORMATION_MESSAGE);
if (opcao == JOptionPane.YES_OPTION){
if(this.salvarSubarea() == true){
JOptionPane.showMessageDialog(null, "Subarea salvo com sucesso!", "Sucesso.", JOptionPane.INFORMATION_MESSAGE);
this.dispose();
}
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro de validação.", JOptionPane.WARNING_MESSAGE);
}
}//GEN-LAST:event_btn_confirmarActionPerformed
private void btn_voltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_voltarActionPerformed
this.dispose();
}//GEN-LAST:event_btn_voltarActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_confirmar;
private javax.swing.JButton btn_voltar;
private javax.swing.JTextField input_codigo_subarea;
private javax.swing.JTextField input_nome_subarea;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollBar jScrollBar1;
private javax.swing.JLabel label_codigo_subarea;
private javax.swing.JLabel label_nome_subarea;
private javax.swing.JPanel panel_botoes;
private javax.swing.JPanel panel_dados;
private javax.swing.JPanel panel_principal;
// End of variables declaration//GEN-END:variables
private boolean validarCampos() throws Exception {
this.validarNome();
//this.validarCodigo();
return true;
}
private boolean validarNome() throws Exception {
if (this.input_nome_subarea.getText().isEmpty() == true){
this.input_nome_subarea.setBorder(new LineBorder(Color.RED));
throw new Exception("Nome da subárea não pode ser vazia.");
}
return true;
}
private void validarCodigo() throws Exception {
String codigo = this.input_codigo_subarea.getText();
if (codigo.isEmpty() == true){
this.input_codigo_subarea.setBorder(new LineBorder(Color.RED));
throw new Exception("Código da subárea não pode ser vazia.");
}
if (subareaController.verificarCodigoExistente(codigo) == true){
throw new Exception("Código já cadastrado na base de dados.");
}
}
private boolean salvarSubarea() {
Subarea subarea = new Subarea(this.input_codigo_subarea.getText(), this.input_nome_subarea.getText());
try {
subareaController.salvarSubarea(subarea);
return true;
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Erro.", JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
|
Java
|
UTF-8
| 3,238
| 2.015625
| 2
|
[] |
no_license
|
package com.nebeek.newsstand.ui.bookmark;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.nebeek.newsstand.R;
import com.nebeek.newsstand.controller.base.BaseBackStackController;
import com.nebeek.newsstand.controller.base.BaseMessageListPresenter;
import com.nebeek.newsstand.data.DataRepository;
import com.nebeek.newsstand.ui.topic.MessageViewAdapter;
import butterknife.BindView;
public class BookmarkController extends BaseBackStackController implements BookmarkContract.View {
@BindView(R.id.progress_bar)
ProgressBar progressBar;
@BindView(R.id.messages)
RecyclerView messages;
@BindView(R.id.empty_list_message)
TextView emptyListMessage;
private LinearLayoutManager layoutManager;
private BookmarkContract.Presenter presenter;
private MessageViewAdapter messageViewAdapter;
public static BookmarkController newInstance() {
return new BookmarkController();
}
@Override
protected View inflateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) {
return inflater.inflate(R.layout.controller_bookmark, container, false);
}
@Override
protected void onViewBound(@NonNull View view) {
super.onViewBound(view);
presenter = new BookmarkPresenter(DataRepository.getInstance(), this);
initView();
setActive(true);
presenter.start();
}
private void initView() {
messageViewAdapter = new MessageViewAdapter(null, null, this::openWebView, null, (BaseMessageListPresenter) presenter, true);
layoutManager = new LinearLayoutManager(getActivity());
messages.setLayoutManager(layoutManager);
messages.setAdapter(messageViewAdapter);
layoutManager.setStackFromEnd(true);
}
@Override
public void showLoading() {
progressBar.setVisibility(View.VISIBLE);
}
@Override
public void hideLoading() {
progressBar.setVisibility(View.INVISIBLE);
}
@Override
public void refreshMessagesList() {
messageViewAdapter.notifyDataSetChanged();
}
@Override
public boolean canHandleBackStack() {
return false;
}
@Override
public void showEmptyListMessage() {
emptyListMessage.setVisibility(View.VISIBLE);
}
@Override
public void hideEmptyListMessage() {
try {
emptyListMessage.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void openTelegramWithSpecificUrl(String url) {
try {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setPackage("org.telegram.messenger");
startActivity(intent);
} catch (Exception e) {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
}
}
|
Java
|
UTF-8
| 1,314
| 3.28125
| 3
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.Collection;
public class Dictionary<T,E> {
private ArrayList<E> keyArrL = new ArrayList<E>();
private ArrayList<T> valueArrL = new ArrayList<T>();
private int size = 0;
public Dictionary(){
}
public void put(E key, T value){
keyArrL.add(key);
valueArrL.add(value);
size++;
}
public T get(E key){
return valueArrL.get(keyArrL.indexOf(key));
}
public T remove(E key){
T storageValue = valueArrL.get(keyArrL.indexOf(key));
keyArrL.remove(key);
valueArrL.remove(storageValue);
size--;
return storageValue;
}
public boolean contains(E key){
int i = keyArrL.indexOf(key);
//System.out.println(i);
//System.out.println(keyArrL.get(i));
return i != -1;
}
public int size(){
return this.size;
}
public Collection<E> keys(){
Collection<E> keys = new ArrayList<E>();
for(int i = 0; i<size; i++){
keys.add(keyArrL.get(i));
}
return keys;
}
public Collection<T> values(){
Collection<T> values = new ArrayList<T>();
for(int i = 0; i<size; i++){
values.add(valueArrL.get(i));
}
return values;
}
}
|
Java
|
UTF-8
| 1,479
| 2.375
| 2
|
[] |
no_license
|
package com.dev.delta.dentic.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="dentic_medicament")
public class Medicament {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String medicine_name;
String company_name;
String group_name;
String description;
public Medicament() {
// TODO Auto-generated constructor stub
}
public Medicament( String medicine_name, String company_name, String group_name, String description) {
super();
this.medicine_name = medicine_name;
this.company_name = company_name;
this.group_name = group_name;
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMedicine_name() {
return medicine_name;
}
public void setMedicine_name(String medicine_name) {
this.medicine_name = medicine_name;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getGroup_name() {
return group_name;
}
public void setGroup_name(String group_name) {
this.group_name = group_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
Python
|
UTF-8
| 3,277
| 2.5625
| 3
|
[] |
no_license
|
import cv2
import json
import numpy as np
import socket
import struct
from playsound import playsound
from collections import defaultdict
##################################################
from yolo_module import Object_Detection
##################################################
class Recycling:
def __init__(self):
with open("./recycle_information.json", 'r', encoding='UTF-8') as file:
self.info = json.load(file)
self.classes = {0: 'PET plastic_bottle with_label', 1: 'PET plastic_bottle without_label', 2: 'PAPER cardboard with_sticker',
3: 'PAPER cardboard without_sticker', 4: 'PAPER coffee_cup with_cap', 5: 'PAPER coffee_cup without_cap',
6: 'PAPER snack_box', 7: 'CAN drink_can'}
self.object_cnt = defaultdict(int)
self.path = "./audio/"
self.is_button_clicked = False
self.reward = 0
self.OD = Object_Detection()
self.connection = None
self.start_socket()
def start_socket(self):
IP = ''
PORT = 1234
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print("waiting for connection")
server_socket.bind((IP, PORT))
server_socket.listen(1)
self.connection, address = server_socket.accept()
def recvall(self, sock, count):
buf = b''
while count:
new_buf = sock.recv(count)
if not new_buf:
return None
buf += new_buf
count -= len(new_buf)
return buf
def start_capturing(self):
while True:
length = self.recvall(self.connection, 16)
string_data = self.recvall(self.connection, int(length))
data = np.frombuffer(string_data, dtype='uint8')
frame = cv2.imdecode(data, cv2.IMREAD_COLOR)
img = self.get_info(frame)
cv2.imshow('img', img)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
def get_info(self, img):
changed_img, object_x, object_y, object_w, object_h, class_id = self.OD.detect_object(img)
if class_id != -1 and (object_x != -1 or object_y != -1 or object_w != -1 or object_h != -1):
cv2.putText(changed_img, self.classes[class_id], (object_x - 10, object_y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6,
(0, 255, 0), 2)
self.object_cnt[class_id] += 1
idx = max(self.object_cnt, key=lambda key: self.object_cnt[key])
if self.object_cnt[idx] > 50:
detected_object = self.classes[idx]
string = detected_object.split(' ')
playsound(self.path + string[1] + ' ' + string[2] + '.mp3')
self.reward += int(self.info[string[0]][string[1]][1])
self.connection.send(struct.pack('f', (idx+1)*1000 + self.reward))
self.object_cnt.clear()
self.connection.send(struct.pack('f', -1))
return changed_img
self.connection.send(struct.pack('f', -1))
return img
if __name__ == '__main__':
recycle = Recycling()
recycle.start_capturing()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.