branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>haohao1010/lexical-analyzer-py<file_sep>/shell.py import basic # 不断接收键盘的输入 while True: text = input("basic >") res, error = basic.run('<stdin>', text) # stdin 来自键盘 if error: print(error.as_string()) else: print(res) <file_sep>/basic.py DIGITS = "0123456789" # Token type => TT TT_INT = "INT" TT_FLOAT = "FLOAT" TT_PLUS = "PLUS" # 加 TT_MINUS = "MINUS" # 减 TT_MUL = "MUL" # 乘 TT_DIV = "DIV" # 除 TT_LPAREN = "LPAREN" # 左括号 TT_RPAREN = "RPAREN" # 右括号 TT_EOF = "EOF" # 终止符 """ 自定义 Error """ class Error(object): def __init__(self, pos_start, pos_end, error_name, details): """ :param pos_start: 错误起始位置 :param pos_end: 错误结束位置 :param error_name: 错误名字 :param details: 错误细节 """ self.pos_start = pos_start self.pos_end = pos_end self.error_name = error_name self.details = details def as_string(self): res = f'{self.error_name}: {self.details}' res += f'File {self.pos_start.fn}, line {self.pos_end.ln + 1}' return res """ 非法字符 """ class IllegalCharError(Error): def __init__(self, pos_start, pos_end, detail): super().__init__(pos_start, pos_end, "Illegal Character", detail) """ 无效语法 """ class InvalidSyntaxError(Error): def __init__(self, pos_start, pos_end, detail=''): super().__init__(pos_start, pos_end, "Invalid Syntax", detail) """ 词法单元 """ class Token(object): # type - value def __init__(self, type_, value=None, pos_start=None, pos_end=None): self.type = type_ self.value = value if pos_start: # Token 单个字符 + -> pos_start == pos_end self.pos_start = pos_start.copy() self.pos_end = pos_start.copy() self.pos_end.advance(self.value) # 传入 current_char 读取下一个 Token if pos_end: # Token 多个字符 123456 self.pos_end = pos_end # 方便调试时,信息的查看 def __repr__(self): if self.value: return f'{self.type}: {self.value}' return f'{self.type}' class Position(object): def __init__(self, idx, ln, col, fn, ftxt): """ :param idx: 索引 :param ln: 行号 :param col: 列号 :param fn: 文件来源 :param ftxt: 文件内容 """ self.idx = idx self.ln = ln self.col = col self.fn = fn self.ftxt = ftxt # 预读 def advance(self, current_char): """ :param current_char: 当前字符 :return: """ self.idx += 1 # 索引 + 1 self.col += 1 # 列号 + 1 if current_char == '\n': self.col = 0 # 列号归 0 self.ln += 1 # 行号 + 1 # 实例化Position def copy(self): return Position(self.idx, self.ln, self.col, self.fn, self.ftxt) """ 词法解析器 """ class Lexer(object): def __init__(self, fn, text): self.fn = fn self.text = text self.pos = Position(-1, 0, -1, fn, text) self.current_char = None # 当前的字符 self.advance() # 预读 def advance(self): self.pos.advance(self.current_char) # 此时已经 self.pos.idx + 1 if self.pos.idx < len(self.text): self.current_char = self.text[self.pos.idx] # text => string, 可以根据索引取下一个位置 else: self.current_char = None # 通过 advance() 遍历 text,并判断遍历的结果是否为关键字 def make_tokens(self): tokens = [] while self.current_char is not None: if self.current_char in (' ', '\t'): # 若为空格或者制表符,词法分析器则自动跳过,不作处理 self.advance() # 往下读取 elif self.current_char in DIGITS: # 数字 tokens.append(self.make_number()) # 通过调用 make_number() 将该数字添加到词法单元里面 elif self.current_char == '+': tokens.append(Token(TT_PLUS, pos_start=self.pos)) self.advance() elif self.current_char == '-': tokens.append(Token(TT_MINUS, pos_start=self.pos)) self.advance() elif self.current_char == '*': tokens.append(Token(TT_MUL, pos_start=self.pos)) self.advance() elif self.current_char == '/': tokens.append(Token(TT_DIV, pos_start=self.pos)) self.advance() elif self.current_char == '(': tokens.append(Token(TT_LPAREN, pos_start=self.pos)) self.advance() elif self.current_char == ')': tokens.append(Token(TT_RPAREN, pos_start=self.pos)) self.advance() else: # 没有匹配到,非法字符错误 # python 引用性调用 错误提示中包含当前位置,所以需要把当前位置 copy 出来 # 若不 copy,则在操作该数据时,原本数据也会遭受影响 pos_start = self.pos.copy() char = self.current_char # 报错的那个字节 self.advance() return [], IllegalCharError(pos_start, self.pos, f"'{char}'") tokens.append(Token(TT_EOF, pos_start=self.pos)) return tokens, None # 整数、小数 => 0.1 (0 小数点 1) def make_number(self): num_str = '' # 最终识别出来的结果 dot_count = 0 # 小数点的个数 while self.current_char is not None and self.current_char in DIGITS + '.': # DIGITS + '.' => "0123456789." if self.current_char == '.': if dot_count == 1: break dot_count += 1 num_str += '.' else: # 当前字符不为小数点时,添加到 num_str 中 num_str += self.current_char self.advance() # 往下读,获取下一个 if dot_count == 0: # 若为整数 return Token(TT_INT, int(num_str)) # 强制转换成 int else: return Token(TT_FLOAT, float(num_str)) # 强制转换成 float """ 数字结点 """ class NumberNode(object): def __init__(self, tok): self.tok = tok def __repr__(self): return f'{self.tok}' """ 二元操作结点 + - * / 1 + 2 left_node:1,op_tok:+,right_node:2 """ class BinOpNode(object): def __init__(self, left_node, op_tok, right_node): self.left_node = left_node self.op_tok = op_tok self.right_node = right_node def __repr__(self): return f'{self.left_node}, {self.op_tok}, {self.right_node}' """ 一元操作结点 -1 op_tok:-,node:1 """ class UnaryOpNode(object): def __init__(self, op_tok, node): self.op_tok = op_tok self.node = node # 将对象转化为供解释器读取的形式 def __repr__(self): return f'{self.op_tok}, {self.node}' """ 语法解析结果类 """ class ParserResult(object): def __init__(self): self.error = None self.node = None # 解析成功 def success(self, node): self.node = node return self # 解析失败 def failure(self, error): self.error = error return self # 存储解析的结果 def register(self, res): if isinstance(res, ParserResult): if res.error: self.error = res.error return res.node return res """ 语法解析器 """ class Parser(object): # 接收词法解析后的结果 Tokens def __init__(self, tokens): self.tokens = tokens self.tok_idx = -1 self.advance() # 往下读取 Token # noinspection PyAttributeOutsideInit def advance(self): self.tok_idx += 1 if self.tok_idx < len(self.tokens): self.current_tok = self.tokens[self.tok_idx] return self.current_tok def parse(self): res = self.expr() if not res.error and self.current_tok.type != TT_EOF: return res.failure(InvalidSyntaxError( self.current_tok.pos_start, self.current_tok.pos_end, "Expected '+' '-' '*' or '/' " )) return res def factor(self): """ factor -> INT | FLOAT -> ( PLUS | MINUS ) factor -> LPAREN expr RPAREN :return: """ res = ParserResult() # 拿到语法解析的结果 tok = self.current_tok # factor -> INT | FLOAT if tok.type in (TT_INT, TT_FLOAT): res.register(self.advance()) return res.success(NumberNode(tok)) # factor -> ( PLUS | MINUS ) factor elif tok.type in (TT_PLUS, TT_MINUS): res.register(self.advance()) factor = res.register(self.factor()) if res.error: return res return res.success(UnaryOpNode(tok, factor)) elif tok.type == TT_LPAREN: res.register(self.advance()) # 获取下一个字符 expr = res.register((self.expr())) if res.error: return res if self.current_tok.type == TT_RPAREN: res.register(self.advance()) return res.success(expr) else: # 报错 return res.failure(InvalidSyntaxError( self.current_tok.pos_start, self.current_tok.pos_end, "Expected ')' " )) return res.failure(InvalidSyntaxError( self.current_tok.pos_start, self.current_tok.pos_end, "Expected int or float " )) # term -> factor (( MUL | DIY ) factor)* def term(self): return self.bin_op(self.factor, (TT_MUL, TT_DIV)) # expr -> term (( PLUS | MINUS ) term)* def expr(self): return self.bin_op(self.term, (TT_PLUS, TT_MINUS)) # 递归调用构建AST def bin_op(self, func, ops): res = ParserResult() left = res.register(func()) while self.current_tok.type in ops: op_tok = self.current_tok res.register((self.advance())) right = res.register(func()) left = BinOpNode(left, op_tok, right) return res.success(left) """ 运行 """ def run(fn, text): # fn:从键盘输入的数据,text的来源,<stdin> lexer = Lexer(fn, text) tokens, error = lexer.make_tokens() print(tokens) # 生成AST parser = Parser(tokens) ast = parser.parse() return ast.node, ast.error <file_sep>/README.md # lexical-analyzer-py A lexical parser based on python language.
70b389559df3cab5b9e43969957f504b8d63e05b
[ "Markdown", "Python" ]
3
Python
haohao1010/lexical-analyzer-py
6162c0af658b32a5723f5dc18bd3bbc82da53bd6
1c80525f54eaa73dbf3cce4ce79d623750f33948
refs/heads/master
<file_sep>const router = require('express').Router(); router.get('/verify', (req,res) => { const token = req.header('auth-token'); if (!token) return res.status(401).send("Access denied"); try { const verified = jwt.verify(token,process.env.TOKEN_SECRET, (error,decoded) => { if(error) return res.status(401).send(error.message); }); req.user = verified; } catch (error) { res.status(400).send(error); } res.json(req.user); }); module.exports = router;<file_sep>const router = require('express').Router(); const jwt = require('jsonwebtoken'); const User = require("../model/User"); router.get('/verify', async (req,res) => { const token = req.header('Authorization').split(' ')[1]; if (!token) return res.status(401).send("Access denied"); try { const verified = await jwt.verify(token,process.env.TOKEN_SECRET); var userId = verified._id; // send user id to mongodb to ge tuser details const userDetails = await User.findById(userId).exec(); res.send(userDetails.toJSON(),200); } catch (error) { res.status(400).send(error.message); } }); module.exports = router;
f41442cd4f6546a40da97a6a6faf65d36dd3a7da
[ "JavaScript" ]
2
JavaScript
ahmed-ali94/JWT-Auth-API
4bd65879c4b3b2f208c8efd7e4e30ee7f2c361dc
2623fd1df4729be7a5f7c82f642062deeed06a10
refs/heads/master
<repo_name>binwensun/DeepCPDP<file_sep>/ASTToken2Vec_train.py # -*- coding: UTF-8 -*- """ CBOW model for Java-AST-Node(Type) Embedding There are 92 types of Java-AST-Node... [1, 92] ID 0 for Blank_Node, 92 + Empty_Node = 93 [0, 92] context_nodes -> target_node input: (parent_id, child1_id, child2_id, ...) predict: target_node context = sum(one_hot(parent_id, child1_id, child2_id, ...)) -> shape(93, ) model: context : shape=(93, ) embedding -> shape=(embedding_dim, ) predict -> shape=(93, ) """ import os import sys import numpy as np from keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint from keras.models import Sequential, load_model from keras.layers import InputLayer, Dense def get_data(data_file): np_samples = np.load(data_file) np.random.shuffle(np_samples) x = contexts = np_samples[:, 0] y = targets = np_samples[:, 1] return x, y def train_model(emb_dim, x, y, log_dir, model_file): # using default initializers input_layer = InputLayer(input_shape=(93,), name='input_layer') embedding_layer = Dense(units=emb_dim, name='embedding_layer', use_bias=False) out_layer = Dense(units=93, name='out_layer', activation='softmax') model = Sequential([input_layer, embedding_layer, out_layer]) # print(model.get_config()) # out: dict # model.summary() # out: table model.compile(optimizer='nadam', loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(x, y, batch_size=1024, epochs=1000, verbose=1, callbacks=callbacks(log_dir, model_file), validation_split=0, validation_data=None, shuffle=True, initial_epoch=0) return history # print(history.history) def callbacks(log_dir, model_file): return [TensorBoard(log_dir=log_dir, # embeddings_freq=1, # embeddings_layer_names='embedding_layer', # embeddings_metadata='metadata.tsv' ), ModelCheckpoint(model_file, monitor='loss', verbose=1, save_best_only=True, save_weights_only=False, mode='min', period=1), EarlyStopping(monitor='loss', min_delta=0, patience=0, verbose=1, mode='min')] def save_embedding_matrix(model_file, embedding_matrix_file_path): """save embedding_matrix as a single file""" embedding_matrix = load_model(model_file).get_layer('embedding_layer').get_weights()[0] embedding_matrix[0] = 0 # id 0 for Empty Node, let it=(0, 0, 0, ..., 0) np.save(embedding_matrix_file_path, embedding_matrix) # ----------------------------------------------------------- emb_dim = int(sys.argv[1]) log_dir = os.path.join('logs', 'cbow', str(emb_dim)) model_file_path = os.path.join(log_dir, 'min_loss_model.hdf5') embedding_matrix_file_path = os.path.join(log_dir, 'embedding_matrix_20.npy') x, y = get_data('emb_samples.npy') train_model(emb_dim, x, y, log_dir, model_file_path) save_embedding_matrix(model_file_path, embedding_matrix_file_path) <file_sep>/Attention.py import os import json import math import random from abc import abstractmethod import numpy as np import datetime import keras import keras.backend as K from keras.models import Model from keras.layers import Input, Layer, Embedding, Dense, Bidirectional, CuDNNLSTM, concatenate from keras.callbacks import Callback, TensorBoard from keras.utils import Sequence from sklearn.metrics import f1_score, roc_curve, auc # ----------------------------------------------- #os.environ['CUDA_VISIBLE_DEVICES'] = '2' def get_train_set(project_name, train_set_id): with open(os.path.join('dp_samples', 'samples.train.{}.json'.format(train_set_id)), 'r') as f: samples = json.load(f) return samples[project_name] def get_test_set(project_name): with open(os.path.join('dp_samples', 'samples.test.json'), 'r') as f: samples = json.load(f) return samples[project_name] def split_train_val(samples, val_percent=0.2): # split train:val= (1-val_percent):val_percent # stratified sampling # random.shuffle(samples) buggy_samples = [s for s in samples if s['label'] == 1] clean_samples = [s for s in samples if s['label'] == 0] p = round(len(samples) / 2 * (1 - val_percent)) train_buggy, val_buggy = buggy_samples[:p], buggy_samples[p:] train_clean, val_clean = clean_samples[:p], clean_samples[p:] train = train_buggy + train_clean val = val_buggy + val_clean random.shuffle(train) random.shuffle(val) return train, val class InputWrapper(Sequence): def __init__(self, samples, batch_size=4): self.samples = samples self.batch_size = batch_size def __len__(self): return math.ceil(len(self.samples) / self.batch_size) def __getitem__(self, idx): batch_samples = self.samples[idx * self.batch_size: (idx + 1) * self.batch_size] batch_x, batch_y = self._batch_to_ndarray(batch_samples) return batch_x, batch_y def on_epoch_end(self): pass @abstractmethod def _batch_to_ndarray(self, batch_sample): raise NotImplementedError class TokenSequenceWrapper(InputWrapper): def _batch_to_ndarray(self, batch_sample): max_len_sequence = max(len(s['token_sequence']) for s in batch_sample) batch_sequence = [s['token_sequence'] + [0] * (max_len_sequence - len(s['token_sequence'])) for s in batch_sample] batch_label = [s['label'] for s in batch_sample] return np.asarray(batch_sequence, dtype=np.int), np.asarray(batch_label, dtype=np.int) class TokenSequenceAndSoftwareMetricsWrapper(InputWrapper): def _batch_to_ndarray(self, batch_sample): max_len_sequence = max(len(s['token_sequence']) for s in batch_sample) batch_sequence = [s['token_sequence'] + [0] * (max_len_sequence - len(s['token_sequence'])) for s in batch_sample] batch_metrics = [s['metrics'] for s in batch_sample] batch_label = [s['label'] for s in batch_sample] return [np.asarray(batch_sequence), np.asarray(batch_metrics)], np.asarray(batch_label) def compute_f1(model, wrapped_samples): y_true = np.asarray([s['label'] for s in wrapped_samples.samples]) y_pred = np.round(model.predict_generator(wrapped_samples, steps=len(wrapped_samples), use_multiprocessing=True)) return f1_score(y_true, y_pred) def compute_auc(model, wrapped_samples): y_true = np.asarray([s['label'] for s in wrapped_samples.samples]) y_pred = np.round(model.predict_generator(wrapped_samples, steps=len(wrapped_samples), use_multiprocessing=True)) return auc(*(roc_curve(y_true, y_pred, pos_label=1)[0:2])) def compute_all_pred(model, wrapped_samples): metrics_label = [(list(s["metrics"]) + [s['label']]) for s in wrapped_samples.samples] pred = model.predict_generator(wrapped_samples, steps=len(wrapped_samples), use_multiprocessing=True) pred_round = list(np.round(pred)) pred = list(pred) res = [] for i in range(len(metrics_label)): res.append(metrics_label[i] + [pred_round[i], pred[i]]) return res class CustomCallback(Callback): def __init__(self, wrapped_train_samples=None, wrapped_val_samples=None, score_calculator=compute_auc, log_dir='temp_logs', patience=10, verbose=0): super(CustomCallback, self).__init__() # self.wrapped_train_samples = wrapped_train_samples self.wrapped_val_samples = wrapped_val_samples assert self.wrapped_val_samples is not None # self.score_calculator = score_calculator self.records = {'train_score': [], 'val_score': []} self.cur_max_val_score = 0 self.best_epoch = 0 # self.max_wait = patience # self.verbose = verbose # self.log_dir = log_dir os.makedirs(self.log_dir, exist_ok=True) self.best_weights_path = os.path.join(self.log_dir, 'weights.max_val_score.hdf5') def on_epoch_begin(self, epoch, logs=None): pass def on_epoch_end(self, epoch, logs=None): train_score = None if self.wrapped_train_samples is not None: train_score = self.score_calculator(self.model, self.wrapped_train_samples) self.records['train_score'].append(train_score) val_score = self.score_calculator(self.model, self.wrapped_val_samples) self.records['val_score'].append(val_score) # if self.verbose == 1: print("Epoch={}\ttrain_score={}\tval_score={}".format(epoch, train_score, val_score)) # ---- early stopping ---- if val_score >= self.cur_max_val_score: # improving self.cur_max_val_score = val_score self.cur_wait = 0 self.best_epoch = epoch self.model.save_weights(self.best_weights_path) else: # not improving self.cur_wait += 1 if self.cur_wait >= self.max_wait: self.model.stop_training = True def on_train_begin(self, logs=None): pass def on_train_end(self, logs=None): self.model.load_weights(self.best_weights_path) # ----------------------------------------------- # embedding_matrix learned by ASTToken2Vec def embedding_layer(trainable=False, rg=None): embedding_matrix_file_path = os.path.join('embedding_matrix_20.npy') embedding_matrix = np.load(embedding_matrix_file_path) return Embedding(input_dim=93, output_dim=20, embeddings_regularizer=rg, trainable=trainable, weights=[embedding_matrix]) class AttentionWeightedAverage(Layer): """ https://github.com/bfelbo/DeepMoji/blob/master/deepmoji/attlayer.py Computes a weighted average of the different channels across timesteps. Uses 1 parameter pr. channel to compute the attention value for a single timestep. """ def __init__(self, return_attention=False, regularizer=None, **kwargs): self.init = keras.initializers.get('uniform') self.supports_masking = True self.return_attention = return_attention self.regularizer = regularizer super(AttentionWeightedAverage, self).__init__(**kwargs) def get_config(self): config = { 'return_attention': self.return_attention, } base_config = super(AttentionWeightedAverage, self).get_config() return dict(list(base_config.items()) + list(config.items())) def build(self, input_shape): self.input_spec = [keras.engine.InputSpec(ndim=3)] assert len(input_shape) == 3 self.W = self.add_weight(shape=(input_shape[2], 1), name='{}_W'.format(self.name), initializer=self.init, regularizer=keras.regularizers.get(self.regularizer)) self.trainable_weights = [self.W] super(AttentionWeightedAverage, self).build(input_shape) def call(self, x, mask=None): # computes a probability distribution over the timesteps # uses 'max trick' for numerical stability # reshape is done to avoid issue with Tensorflow # and 1-dimensional weights logits = K.dot(x, self.W) x_shape = K.shape(x) logits = K.reshape(logits, (x_shape[0], x_shape[1])) ai = K.exp(logits - K.max(logits, axis=-1, keepdims=True)) # masked timesteps have zero weight if mask is not None: mask = K.cast(mask, K.floatx()) ai = ai * mask att_weights = ai / (K.sum(ai, axis=1, keepdims=True) + K.epsilon()) weighted_input = x * K.expand_dims(att_weights) result = K.sum(weighted_input, axis=1) if self.return_attention: return [result, att_weights] return result def get_output_shape_for(self, input_shape): return self.compute_output_shape(input_shape) def compute_output_shape(self, input_shape): output_len = input_shape[2] if self.return_attention: return [(input_shape[0], output_len), (input_shape[0], input_shape[1])] return (input_shape[0], output_len) def compute_mask(self, input, input_mask=None): if isinstance(input_mask, list): return [None] * len(input_mask) else: return None def random_blstm_attention_model(lstm_dim=512, lstm_regularizer='l2', merge_mode='ave', att_regularizer='l2', fc_dim=None, fc_regularizer=None, lg_regularizer='l2'): seq_len = None # no limitation seq_id = Input(shape=[seq_len], dtype='int32', name='token_seq') # seq_vector = Embedding(input_dim=93, output_dim=20, trainable=True)(seq_id) # seq_feature = Bidirectional( CuDNNLSTM(units=lstm_dim, return_sequences=True, kernel_regularizer=lstm_regularizer, recurrent_regularizer=lstm_regularizer), merge_mode=merge_mode)(seq_vector) seq_feature = AttentionWeightedAverage(regularizer=att_regularizer, name='attention')( concatenate([seq_vector, seq_feature])) # seq_feature = AttentionWeightedAverage(regularizer=att_regularizer, name='attention')(seq_feature) if fc_dim is not None: seq_feature = Dense(fc_dim, activation='relu', kernel_regularizer=fc_regularizer)(seq_feature) output = Dense(1, activation='sigmoid', kernel_regularizer=lg_regularizer)(seq_feature) return Model(inputs=seq_id, outputs=output) def asttoken2vec_blstm_attention_model(lstm_dim=512, lstm_regularizer='l2', merge_mode='ave', att_regularizer='l2', fc_dim=None, fc_regularizer=None, lg_regularizer='l2'): seq_len = None # no limitation seq_id = Input(shape=[seq_len], dtype='int32', name='token_seq') # seq_vector = embedding_layer(trainable=False)(seq_id) # id(1) -> one_hot(93) -> 20 # seq_feature = Bidirectional( CuDNNLSTM(units=lstm_dim, return_sequences=True, kernel_regularizer=lstm_regularizer, recurrent_regularizer=lstm_regularizer), merge_mode=merge_mode)(seq_vector) seq_feature = AttentionWeightedAverage(regularizer=att_regularizer, name='attention')( concatenate([seq_vector, seq_feature])) # seq_feature = AttentionWeightedAverage(regularizer=att_regularizer, name='attention')(seq_feature) if fc_dim is not None: seq_feature = Dense(fc_dim, activation='relu', kernel_regularizer=fc_regularizer)(seq_feature) output = Dense(1, activation='sigmoid', kernel_regularizer=lg_regularizer)(seq_feature) return Model(inputs=seq_id, outputs=output) # ------------------------------------------------------------------------------- folder = "asttoken2vec_blstm_attention_model" if not os.path.isdir(folder): os.mkdir(folder) file = open(os.path.join(folder, "output.csv"),"w") file.write("source,target,0,1,2,3,4,5,6,7,8,9,avg\n") model_creator, input_wrapper, score_calculator = [ asttoken2vec_blstm_attention_model, TokenSequenceWrapper, compute_auc ] results = [] batch_size = 64 patience = 10 log_dir = 'logs/test' verbose = 1 source_projects = ['camel', 'poi', 'xalan', 'xerces'] target_projects = ['ant', 'camel', 'jedit', 'log4j', 'lucene', 'poi', 'synapse', 'velocity', 'xalan', 'xerces'] for i in range(10): print(i) file.write("{}\n".format(i)) for source in source_projects: folder2 = os.path.join(folder, str(i)) if not os.path.isdir(folder2): os.mkdir(folder2) time_file = open(os.path.join(folder2, "%s.txt" % source), "w") time_file.write("time1: {}\n".format(datetime.datetime.now())) ### train_samples, val_samples = split_train_val(get_train_set(source, i)) train_samples = input_wrapper(train_samples, batch_size=batch_size) val_samples = input_wrapper(val_samples, batch_size=batch_size) callback = CustomCallback(wrapped_train_samples=None, wrapped_val_samples=val_samples, score_calculator=score_calculator, log_dir=log_dir, patience=patience, verbose=verbose) model = model_creator() time_file.write("time2: {}\n".format(datetime.datetime.now())) ### model.compile(loss='binary_crossentropy', optimizer='adam') time_file.write("time3: {}\n".format(datetime.datetime.now())) ### # if verbose == 1: model.summary() model.fit_generator(generator=train_samples, steps_per_epoch=len(train_samples), shuffle=True, epochs=100, callbacks=[callback], # TensorBoard(log_dir) use_multiprocessing=True, verbose=verbose) time_file.write("time4: {}\n".format(datetime.datetime.now())) ### for target in target_projects: if target == source: continue test_samples = input_wrapper(get_test_set(target), batch_size=batch_size) test_score = score_calculator(model, test_samples) print('{}'.format(test_score)) file.write("{},{},{}\n".format(source, target, test_score)) results.append((source, target, callback.best_epoch, max(callback.records['val_score']), test_score)) with open(os.path.join(folder2, "%s-%s.txt" % (source, target)), "w") as t_v_file: data = compute_all_pred(model, test_samples) for column in data: s = "" for e in column: s += "{},".format(e) t_v_file.write(s[:-1] + "\n") time_file.write("time5: {}\n".format(datetime.datetime.now())) ### time_file.write("done.\n") time_file.close() file.write("done.\n") file.close() # print() # for i in range(len(results)): # r = results[i] # # if i % 36 == 0: print(i / 36) # # print('{}'.format(r[4]))
88977db76291d122072f1589dcd50b5d30be1bad
[ "Python" ]
2
Python
binwensun/DeepCPDP
1fd3de668879b04cd4ff32a7b61758b1bf724472
842af404326b3b7f5b870361fdf4e5fc11bd4919
refs/heads/main
<repo_name>agutenkunst/sainsmart_relay_usb_demo<file_sep>/scripts/run_in_industrial_ci.sh #!/usr/bin/env bash # Needs ROS and industrial_ci sourced bus_id=$(lsusb | grep 0403:6001 | grep -Po '(?<=Bus )\d+') device_id=$(lsusb | grep 0403:6001 | grep -Po '(?<=Device )\d+') # Execute this at the package root! rosrun industrial_ci rerun_ci . DOCKER_RUN_OPTS="--device=/dev/bus/usb/$bus_id/$device_id" ROS_DISTRO="noetic"<file_sep>/readme.md # sainsmart relay usb demo This package demonstrates using https://bitbucket.org/DataspeedInc/sainsmart_relay_usb in rostests. ## Using industrial_ci It is possible to run the tests using `sainsmart_relay_usb` from within a docker container along with industrial_ci. For details see `./scripts/run_in_industrial_ci.sh`.<file_sep>/test/relay_test.cpp #include <gtest/gtest.h> #include <ros/ros.h> #include <std_msgs/Byte.h> class RelayTest : public testing::Test { }; TEST_F(RelayTest, basicTest) { ros::NodeHandle nh; ros::Publisher command_pub = nh.advertise<std_msgs::Byte>("/relay_cmd", 1); ros::Duration(2).sleep(); ros::spinOnce(); for (size_t i = 0; i < 16; i++) { std_msgs::Byte relay_cmd; relay_cmd.data = i; std::cout << i << std::endl; command_pub.publish(relay_cmd); ros::spinOnce(); ros::Duration(0.2).sleep(); } ASSERT_TRUE(true); } int main(int argc, char *argv[]) { ros::init(argc, argv, "relay_test"); ros::NodeHandle nh; ros::AsyncSpinner spinner{1}; spinner.start(); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.0.2) project(sainsmart_relay_usb_demo) find_package(catkin REQUIRED COMPONENTS roscpp std_msgs ) catkin_package( CATKIN_DEPENDS roscpp std_msgs ) ########### ## Build ## ########### include_directories( ${catkin_INCLUDE_DIRS} ) ############# ## Install ## ############# ############# ## Testing ## ############# if(CATKIN_ENABLE_TESTING) find_package(rostest REQUIRED) add_rostest_gtest(relay_test test/relay_test.test test/relay_test.cpp ) target_link_libraries(relay_test ${catkin_LIBRARIES} ) endif()
448a51ad64524f6d0a440a0434ff046f0b7aa5ae
[ "Markdown", "CMake", "C++", "Shell" ]
4
Shell
agutenkunst/sainsmart_relay_usb_demo
bbd48ba8f1eb0de8ef01eb7ef43af77d50511bfe
6518efe22103552e1d0de63d18f87b5edcdeb2fc
refs/heads/master
<file_sep># txtFileManager.py module # Module used to manipulate text files # Coded by Lemur from contextlib import contextmanager # https://docs.python.org/2/library/contextlib.html import os # https://docs.python.org/2/library/os.html def help(): # Visual output of all the functions and brief description print(''' ********* Python Text File Manager Package Functions... ********* \ncreatefile(filename, [directory]) : function creates a file from two arguments, both strings, the file name and the directory. Do not specify directory if you want to write file into current one. Add '..' at start of path if you would like to go up a directory. A custom error message will be outputted if your file path was not found \ndeletefile(filename, [directory]) : function deletes file if found. Otherwise, a custom error message is outputted. Add '..' at start of path if you would like to go up a directory, or leave it blank if want to work in current \nencryptfile(filename, [directory]) : function which encrypts a text file based on _________ algorithm \ndecryptfile(filename, directory, key) : function which decrypts a text file based on __________ algorithm \nwriteline(filename, [directory, text, line_number]) : function which writes a line of text into the file in the specified directory. Line_number will be an integer representing the index of the line we will like to modify, but will be taken as 0 if file is empty. Custom error outputted if IndexError raised \nappendline(filename, [directory, text]) : function which appends a line to a file in specified directory. Similar functionality to 'writeline' \nfindline(filename, [directory, text]) : function that returns all of the line numbers where the specified line of text was found in the file. \ndeleteline(filename, [directory, line_number]) : function which deletes a specified line number in the file. \nfindfile(filename) : function which searches for a specified file in the cwd and returns its full path if it is found (as a string). \nreadline(filename, [directory, line_number]) : \n********************************************************** ''') @contextmanager def createfile(filename, directory=""): ''' Function's purpose is to create a file in a specified directory, overwriting the file if it already exists :param filename: string representing the name of the file to be created :param directory: string representing the directory in which file to be created ''' # Check to see if user requests to go back directory = climb_directory(directory) # Change directory origdirectory = os.getcwd() try: # If no directory specified, just write it into current if directory != "": os.chdir(os.path.expanduser(directory)) with open(filename, "w") as f: f.close() except OSError or WindowsError: print("\nSorry, your directory does not exist, try again") finally: os.chdir(origdirectory) print("\nFinished") @contextmanager def deletefile(filename, directory=""): ''' Function which purpose is to find a file in a specified directory and delete it. If the file is not found, a custom error message is outputted :param filename: string representing the name of the file to be deleted :param directory: string representing the name of the directory in which the file is stored ''' # Check to see if user requests to go back directory = climb_directory(directory) # Change directory origdirectory = os.getcwd() try: # If no directory specified, just take current one if directory != "": os.chdir(os.path.expanduser(directory)) os.remove(filename) except OSError or WindowsError: print("\nSorry, your path was not found, or your file didn't exist") finally: os.chdir(origdirectory) print("\nFinished") def climb_directory(directory): if directory[:2] == "..": climbs = len(directory) string_parameter = "." * climbs if directory[:climbs] == string_parameter: for jumps in range(climbs - 1): os.chdir("..") directory = directory[2:] return directory else: pass def encryptfile(): # FILE LEGNTH LINE # LOOP FOR EACH LINE # ENCRYPT LINE # REWRITE IN TEMP FILE # CHANGE NAME OF OLD FILE TO NEW FILE pass def decryptfile(): pass @contextmanager def writeline(filename, directory="", text="", line_number=0): ''' Function which purpose is to write a line of text into a file in a specific directory. The line number will be specified by the user too, although it will be taken as 0 if the file is originally empty, or will trigger a custom error if it is not found in the file :param filename: string representing the name of the file to be edited :param directory: string representing the name of the directory in which the file is found :param text: string representing the new line of text to be written into file :param line_number: integer representing line number to be edited within the file ''' # Check to see if user requests to go back directory = climb_directory(directory) # Change directory origdirectory = os.getcwd() try: # If directory is not specified, take current one if directory != "": os.chdir(os.path.expanduser(directory)) with open(filename, "r") as f: # Extract data from the file and store in a 1D Array data = f.readlines() f.close() # Change specified line in data (add newline at the end) if len(data) > 0: data[line_number-1] = text + '\n' else: # If no lines in file, just append the new one data.append(text + '\n') # Write new contents to the file with open(filename, "w") as f: f.writelines(data) f.close() except OSError or WindowsError: print("\nPath or file does not exist") except IndexError: print("\nThe line you specified does not exist in the file") finally: os.chdir(origdirectory) print("\nFinished") @contextmanager def appendline(filename, directory="", text=""): ''' Function which purpose is to add a line of text, specified by the user, to the end of a file in a specified directory. :param filename: string representing the name of the file to be edited :param directory: string representing the name of the directory in which file is stored :param text: string representing the new line of text to be added ''' # Check to see if user requests to go back directory = climb_directory(directory) # Change directory origdirectory = os.getcwd() try: # If directory is not specified, take current one if directory != "": os.chdir(os.path.expanduser(directory)) with open(filename, "r") as f: # Read all lines in file and store them in a 1D Array data = f.readlines() f.close() # Append new line of text to the end data.append(text + '\n') with open(filename, "w") as f: # Write all data back in f.writelines(data) f.close() except OSError or WindowsError: print("\nPath or file not found") finally: os.chdir(origdirectory) print("\nFinished") @contextmanager def findline(filename, directory="", text=""): ''' File which purpose is to search for a line specified by the user in a file stored in a certain directory. If the line is found, position where it was found is stored. The function returns a 1D array with all of the positions in which the line was found, as well as providing a visual output. :param filename: string representing the name of the file to be edited :param directory: string representing the name of the directory in which file is stored :param text: string representing the new line of text to be searched for :return: 1D array with all of the line numbers that matched with the query, or custom error message if path/file not found ''' line = None # Check to see if user requests to go back # ¿Any more efficient way you guys can think of doing this? directory = climb_directory(directory) # Change directory origdirectory = os.getcwd() try: # If directory is not specified, take current one if directory != "": os.chdir(os.path.expanduser(directory)) with open(filename, "r") as f: # Read all lines and store in a 1D Array data = f.readlines() f.close() # Search for specific line of text line = [i+1 for i in range(len(data)) if data[i] == text + '\n'] except OSError or WindowsError: print("\nPath or file not found") finally: os.chdir(origdirectory) print("\nFinished") # Output results print("\nYour line of text was found in the following line/s: {}".format(line)) return line @contextmanager def deleteline(filename, directory="", line_number=1): ''' Function which purpose is to delete a specified line in a text file stored in a particular directory, based on the line_number entered by the user. :param filename: string representing the name of the file to be edited :param directory: string representing the name of the directory in which it is stored :param line_number: integer representing the line number to be deleted ''' # Check to see if user requests to go back # ¿Any more efficient way you guys can think of doing this? directory = climb_directory(directory) # Change directory origdirectory = os.getcwd() try: # If directory is not specified, take current one if directory != "": os.chdir(os.path.expanduser(directory)) with open(filename, "r") as f: # Store all of the lines in a 1D array data = f.readlines() f.close() # Delete specified line del data[line_number-1] with open(filename, "w") as f: # Re-write all modified data f.writelines(data) f.close() except OSError or WindowsError: print("\nPath of file not found") except IndexError: print("\nLine does not exist") finally: os.chdir(origdirectory) print("\nFinished") def findfile(filename): ''' Function which purpose is to search for a file in the cwd and return its full path. :param filename: string representing the name of the file to be found :return: full path (string) of the file searched for ''' for root, dirs, files in os.walk(os.getcwd()): if filename in files: return os.path.join(root, filename) help() @contextmanager def readline(filename, directory="", text=0): pass <file_sep># txtfilemanager “.txt file manager” python package The purpose of this packages it to allow the easy manipulation of text files and to ensure security and integrity of it. Functions within “.txt file manager” • help() Description: The help functions prints out all the functions available within the package. Together with a brief description of it and the parameters needed to call each function. • createfile(filename, directory) Description: Creates a file with the given name and in the directory specified. It will overwrite any existent file with the same name in the same directory. • deletefile(filename, directory) Description: Deletes a file with the give name and in the directory specified. It will prompt an error if there is no such file. • encryptfile(filename, directory) Description: It encrypts the given file so it is illegible when opened with a text editor. It will also store the key within the text file so it can be decrypted. If a file is already encrypted it will prompt a suitable message. • decryptfile(filename, directory, key) Description: It decrypts the given file. • writeline(filename, directory, text, line_number) Description: Writes a new line in the given line number of the text file specified. • appendine(filename, directory, text) Description: Writes at the end of the file a new line of the text file specified. • findline(filename, directory, text) Description: It will try to find within the text file the lines that contain the given argument of text. Returning the lines in which it was found. • deleteline(filename, directory, line_number) Description: It will delete the line in the given line number of the text file specified. • findfile(filename) Description: It will try to find the specified file in memory. Returning it’s directory. <file_sep>from setuptools import setup setup( name="txtfilemanager", version="0.0.1", author="Lemurer", author_email="<EMAIL>", description="Allow the easy manipulation of text files.", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Alestiago/txtfilemanager", py_modules=["txtfilemanager"], package_dir={"":"src"}, packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
b6c3fdd8b47c5de62c93797c0638edffdad30a80
[ "Markdown", "Python" ]
3
Python
josflesan/txtfilemanager
32147abac4adc9a69dc7ba3c163017df4952e7a4
cb2896cae99d4b128533d05e90096a5d68c1516a
refs/heads/master
<repo_name>mslends/flashy<file_sep>/services/topicService.js angular.module("flashCards").service("topicService", function() { // topics array below holds the information for every topic in my menu. (Double click on the line below to expand and show data) // var topics = [{ // name: 'git', // state: 'git' // }, // { // name: 'html', // state: 'html' // }, // { // name: 'css', // state: 'css' // }, // { // name: 'css positioning', // state: 'cssPositioning' // }, // { // name: 'advanced html', // state: 'advHtml' // }, // { // name: 'advanced css', // state: 'advCss' // }, // { // name: 'js fundamentals (functions)', // state: 'jsFundamentals' // }, // { // name: 'js objects', // state: 'jsObj' // }, // { // name: '"this" keyword', // state: 'this' // }, // { // name: 'js callbacks', // state: 'callbacks' // }, // { // name: 'js prototypes', // state: 'prototypes' // }, // { // name: 'jquery', // state: 'jquery' // }, // { // name: 'jquery 2', // state: 'jquery2' // }, // { // name: 'angular', // state: 'angular' // }, // { // name: 'angular services', // state: 'angularServices' // }, // { // name: 'angular $http', // state: 'angular$http' // }, // { // name: 'angular $q', // state: 'angular$q' // }, // { // name: 'json p', // state: 'jsonp' // }, // { // name: 'Angular UI-Router', // state: 'angularRouter' // }, // { // name: 'Angular Directives', // state: 'angularDirectives' // }, // { // name: 'firebase', // state: 'firebase' // }, // { // name: 'Node.js', // state: 'node' // }, // { // name: 'express.js', // state: 'express' // }, // { // name: 'MongoDB', // state: 'mongodb' // }, // { // name: 'Mongoose', // state: 'mongoose' // }, // { // name: 'Passport.js (OAuth)', // state: 'passport' // } // ]; // Function below gets the topics from the topics Array(above) returns the name of each topic. this.getTopics = function() { return topics; }; this.addTopics = function(topic) { topics.push(topic); return topics }; }); <file_sep>/js/app.js angular.module("flashCards", ['ui.router', 'firebase']) .constant('firebaseUrl', 'https://flashington.firebaseio.com/') .config(function($urlRouterProvider, $stateProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('home',{ url: '/', templateUrl: 'views/homeTmpl.html' }) .state('topic',{ url: '/topic/:topicId', templateUrl: 'views/topicView/topicTmpl.html', controller:'topicViewCtrl' }) .state('addCardForm',{ url: '/addCardForm', templateUrl: 'views/topicView/addCardForm.html', controller: 'topicViewCtrl' }) }); <file_sep>/js/directives/flashCardDirective.js angular.module("flashCards").directive('flashCardDirective', function() { return { restrict: "E", templateUrl: "views/flashCardTmpl.html", controller: function($scope, $firebaseObject, $firebaseArray, $stateParams, flashCardService) { // Assigned my Firebase location to the mygetFirebaseRef variable var mygetFirebaseRef = new Firebase("https://flashington.firebaseio.com/-KFlALUT2_FKchYLeuOL/"); // Puts my flashcards object on scope $scope.flashCards = $firebaseArray(mygetFirebaseRef.child($stateParams.topicId)); $scope.deleteCard = function(card, index, params) { var params = $stateParams; console.log($stateParams); console.log('index:', index); flashCardService.deleteCard(card, $scope.flashCards); }.bind(this) }, scope: { topics: '=', flashCards: '=', toggle: '=' } } }); <file_sep>/js/services/topicService.js angular.module("flashCards").service("topicService", function() { var topics = [{ name: 'GIT', state: 'git' }, { name: 'HTML', state: 'html' }, { name: 'CSS', state: 'css' }, { name: 'POSITIONING', state: 'cssPositioning' }, { name: 'FUNCTIONS', state: 'jsFundamentals' }, { name: 'OBJECTS', state: 'jsObj' }, { name: 'THIS', state: 'this' }, { name: 'CALLBACKS', state: 'callbacks' }, { name: 'PROTOTYPES', state: 'prototypes' }, { name: 'JQUERY', state: 'jquery' }, { name: 'ANGULAR', state: 'angular' }, { name: 'SERVICES', state: 'angularServices' }, { name: 'HTTP', state: 'angular$http' }, { name: 'Q', state: 'angular$q' }, { name: 'JSONP', state: 'jsonp' }, { name: 'UIROUTER', state: 'angularRouter' }, { name: 'DIRECTIVES', state: 'angularDirectives' }, { name: 'FIREBASE', state: 'firebase' }, { name: 'NODE', state: 'node' }, { name: 'EXPRESS', state: 'express' }, { name: 'MONGODB', state: 'mongodb' }, { name: 'MONGOOSE', state: 'mongoose' }, { name: 'PASSPORT', state: 'passport' } ]; this.getTopics = function() { return topics; }; this.addTopics = function(topic) { topics.push(topic); return topics }; }); <file_sep>/js/services/flashCardService.js angular.module("flashCards").service("flashCardService", function($firebaseObject, $firebaseArray, $stateParams) { // FlashCards object below(double click on this row to expand). Used this data to build my Firebase database. Leaving it here as a "backup" var flashCards = { GIT:[ { question: "What is git?", answer: "Git is a Version Control System (VCS)" }, { question: "How does git work?", answer: "Git thinks of its data more like a set of snapshots of a miniature filesystem. Every time you commit, or save the state of your project in Git, it basically takes a picture of what all your files look like at that moment and stores a reference to that snapshot." }, { question: "What is the difference between git and github?", answer: "GitHub is a website where you can upload a copy of your Git repository. It is a Git repository hosting service, which offers all of the distributed revision control and source code management (SCM) functionality of Git as well as adding its own features." } ], HTML:[ { question: "What is HTML?", answer: "Hypertext Markup Language, a standardized system for tagging text files to achieve font, color, graphic, and hyperlink effects on World Wide Web pages." } ], CSS:[ { question: "What is css?", answer: "CSS stands for Cascading Style Sheets. CSS describes how HTML elements are to be displayed on screen, paper, or in other media" }, { question: "Why use CSS?", answer: "CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes." }, { question: "What big problem did CSS solve?", answer: "HTML was NEVER intended to contain tags for formatting a web page! HTML was created to describe the content of a web page. When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large websites, where fonts and color information were added to every single page, became a long and expensive process." } ], POSITIONING:[ { question: "What is the css position property?", answer: "The position property specifies the type of positioning method used for an element (static, relative, fixed or absolute)." }, { question: "How many positon values are there?", answer: "There are four different position values. Static, fixed, relative, and absolute." }, { question: "How are HTML elements positioned by default?", answer: "HTML elements are positioned static by default." } ], CSS:[ { question: "What is css?", answer: "CSS stands for Cascading Style Sheets. CSS describes how HTML elements are to be displayed on screen, paper, or in other media" }, { question: "Why use CSS?", answer: "CSS is used to define styles for your web pages, including the design, layout and variations in display for different devices and screen sizes." }, { question: "What big problem did CSS solve?", answer: "HTML was NEVER intended to contain tags for formatting a web page! HTML was created to describe the content of a web page. When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large websites, where fonts and color information were added to every single page, became a long and expensive process." } ], FUNCTIONS:[ { question: "What is function", answer: "A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when something invokes it calls it." }, { question: "How do you name a function?", answer: "A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ()." }, { question: "What are the rules of naming a function?", answer: "Function names can contain letters, digits, underscores, and dollar signs (same rules as variables)" } ], OBJECTS:[ { question: "What is a javascript object?", answer: "Objects are variables too. But objects can contain many values." }, { question: "How do you write the values in an object?", answer: "The values are written as name:value pairs (name and value separated by a colon)." }, { question: "Name-value pairs in Javascript objects are called what?", answer: "The name:values pairs (in JavaScript objects) are called properties." } ], THIS:[ { question: "What is the “this” keyword in javascript?", answer: "In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. An onclick property, though, is owned by the HTML element it belongs to." }, { question: "How is the “this” keyword used in Javascript?", answer: "In most cases, the value of this is determined by how a function is called. It can't be set by assignment during execution, and it may be different each time the function is called. " }, { question: "What is The Biggest Gotcha with JavaScript “this” keyword?", answer: "If you understand this one principle of JavaScript’s this, you will understand the “this” keyword with clarity: this is not assigned a value until an object invokes the function where this is defined. Let’s call the function where this is defined the “this Function. Even though it appears this refers to the object where it is defined, it is not until an object invokes the this Function that this is actually assigned a value. And the value it is assigned is based exclusively on the object that invokes the this Function. this has the value of the invoking object in most circumstances. However, there are a few scenarios where this does not have the value of the invoking object." } ], CALLBACKS:[ { question: "What is a callback?", answer: "A function that takes other functions as arguments or returns functions as its result is called a higher-order function, and the function that is passed as an argument is called a callback function. It's named “callback” because at some point in time it is “called back” by the higher-order function." }, { question: "How do callback functions work?", answer: "When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter. In other words, we aren’t passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function. Note that the callback function is not executed immediately. It is “called back” (hence the name) at some specified point inside the containing function’s body." }, { question: "How many callback functions can you pass in as parameters?", answer: "We can pass more than one callback function into the parameter of a function, just like we can pass more than one variable." } ], PROTOTYPES:[ { question: "What is a prototype?", answer: "Every JavaScript object has a prototype. The prototype is also an object. All JavaScript objects inherit their properties and methods from their prototype." }, { question: "Can you add a property to a prototype?", answer: "You cannot add a new property to a prototype the same way as you add a new property to an existing object, because the prototype is not an existing object." }, { question: "Which properties do prototypes have?", answer: "All objects in JavaScript inherit properties and methods from Object.prototype. These inherited properties and methods are constructor, hasOwnProperty (), isPrototypeOf (), propertyIsEnumerable (), toLocaleString (), toString (), and valueOf (). ECMAScript 5 also adds 4 accessor methods to Object.prototype." } ], JQUERY:[ { question: "What is jQuery?", answer: "jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers." }, { question: "How do we call jQuery library functions?", answer: "As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready. If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded." }, { question: "What big problem did CSS solve?", answer: "Encourages separation of JavaScript and HTML: The jQuery library provides simple syntax for adding event handlers to the DOM using JavaScript, rather than adding HTML event attributes to call JavaScript functions. Thus, it encourages developers to completely separate JavaScript code from HTML markup. Brevity and clarity: jQuery promotes brevity and clarity with features like chainable functions and shorthand function names.Eliminates cross-browser incompatibilities: The JavaScript engines of different browsers differ slightly so JavaScript code that works for one browser may not work for another. Like other JavaScript toolkits, jQuery handles all these cross-browser inconsistencies and provides a consistent interface that works across different browsers.Extensible: New events, elements, and methods can be easily added and then reused as a plugin." } ], ANGULAR:[ { question: "What is Angular?", answer: "AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you would otherwise have to write." }, { question: "Why is using Angular important?", answer: "Angular is what HTML would have been, had it been designed for applications." } ], SERVICES:[ { question: "What is an Angular Service?", answer: "Services are the “heavy lifters” in Angular. They are the equivalant of workers on a construction site. Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app." }, { question: "How do you use an Angular Service?", answer: "To use an Angular service, you add it as a dependency for the component (controller, service, filter or directive) that depends on the service. Angular's dependency injection subsystem takes care of the rest." }, { question: "How do you set up an Angular Service?", answer: "angular.module('myApp').service('mainService', function() {})" } ], HTTP:[ { question: "What is $HTTP?", answer: "The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP." }, { question: "What is the general usage for $HTTP?", answer: "The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise." } ], Q:[ { question: "What is $q?", answer: "A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing." } ], JSONP:[ { question: "What is JSONP?", answer: "JSONP, which stands for “JSON with Padding” (and JSON stands for JavaScript Object Notation), is a way to get data from another domain that bypasses CORS (Cross Origin Resource Sharing) rules. CORS is a set of “rules,” about transferring data between sites that have a different domain name from the client" } ], UIROUTER:[ { question: "What is ui-router?", answer: "AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine." } ], DIRECTIVES:[ { question: "What are Angular Directives?", answer: "Put simply, Directives are reusable pieces of code. At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children." } ], FIREBASE:[ { question: "What is Firebase?", answer: "Data in your Firebase database is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our Android, iOS, and JavaScript SDKs, all of your clients share one Firebase database and automatically receive updates with the newest data." } ], NODE:[ { question: "What is node.js?", answer: "Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient." } ], EXPRESS:[ { question: "What is Express.js?", answer: "Express.js is a Node.js web application server framework, designed for building single-page, multi-page, and hybrid web applications.[1] It is the de facto standard server framework for node.js.[2] The original author, <NAME>, described it as a Sinatra-inspired server,[3] meaning that it is relatively minimal with many features available as plugins. Express is the backend part of the MEAN stack, together with MongoDB database and AngularJS frontend framework." } ], MONGODB:[ { question: "What is MongoDB?", answer: "MongoDB is an open source, document-oriented database designed with both scalability and developer agility in mind. Instead of storing your data in tables and rows as you would with a relational database, in MongoDB you store JSON-like documents with dynamic schemas." } ], MONGOOSE:[ { question: "What is Mongoose?", answer: "Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box." } ], PASSPORT:[ { question: "What is Passport?", answer: "Passport is authentication middleware for Node. It is designed to serve a singular purpose: authenticate requests." } ] }; // Firebase url where data is saved var mypostFirebaseRef = new Firebase("https://flashington.firebaseio.com/-KFlALUT2_FKchYLeuOL"); // This function pushes the data from my addCardForm.html to my Firebase. It alerts me when the button is clicked and info is added to the appropriate topic that you select to add to. this.addNewCard = function(obj) { console.log("add new card hit!"); alert('Card Added to the ' + obj.topic + ' topic!'); mypostFirebaseRef.child(obj.topic).push(obj); } // Used the two lines of code below to push the data from the object above to my Firebase (double click on this row to expand) // mypostFirebaseRef.push(flashCards); // flashCards[obj.topic].push(obj); this.addNewTopic = function(topic) { console.log("Reached the service", topic); alert('Topic Added to the menu 1!'); var mypostFirebaseRef2 = new Firebase("https://flashington.firebaseio.com/-KFlALUT2_FKchYLeuOL/"+topic.name); mypostFirebaseRef2.set([{question: "What is "+ topic.name + "?", answer: "Code"}]); } this.deleteTopic = function(topic) { console.log("Reached the service", topic.name); var deleteTopicFirebaseRef = new Firebase("https://flashington.firebaseio.com/-KFlALUT2_FKchYLeuOL/"+topic.name); deleteTopicFirebaseRef.remove(onComplete); var onComplete = function(error) { if (error) { console.log('Synchronization failed'); } else { console.log('Synchronization succeeded'); } }; } this.deleteCard = function(card, collection) { collection.$remove(card) .then(function(res) { console.log('Deleted Card!') }) .catch(function(err) { console.log('Error deleting card!'); console.log(err); }) var onComplete = function(error) { if (error) { console.log('Synchronization failed'); } else { console.log('Synchronization succeeded'); } }; } }); <file_sep>/views/topicView/topicViewCtrl.js angular.module("flashCards").controller('topicViewCtrl', function($scope, $stateParams, flashCardService, $firebaseObject, $firebaseArray){ // Makes it so that whatever topic I choose from the menu, shows up on scope and the data in that topic is repeated over. $scope.currentstate = $stateParams.topicId; // $scope.topic = $stateParams.topicId; // Assigned my Firebase location to the mygetFirebaseRef variable var mygetFirebaseRef = new Firebase("https://flashington.firebaseio.com/-KFlALUT2_FKchYLeuOL/"); // Puts my flashcards object on scope var obj = $firebaseObject(mygetFirebaseRef); $scope.flashCards = obj; console.log($scope.flashCards); var arr = $firebaseArray(mygetFirebaseRef); $scope.topics = arr; // Function below is ran when a user clicks the "Save Card" button (ng-click) on the addCardForm.html(bottom of page). $scope.newCard = function() { flashCardService.addNewCard( { question: $scope.question, answer: $scope.answer, topic: $scope.topic } ); // $scope.flashCards = flashCardService.getFlashCards($scope.topic); } // // jQuery below makes it so that when I click on a topic in the menu, the menu disappears and slides back in. Find other jQuery on navDirective.js(the only other place where I use jQuery on the app. I copied this function from there). $('.topicLinks').on("click", function() { if($('.slideout-menu:visible')) { $('.slideout-menu').animate({right:'-350px'}, 350, function() {}); } }); }); <file_sep>/js/directives/navDirective.js angular.module("flashCards").directive('navDirective', function() { return { restrict: "AE", templateUrl: "views/navTmpl.html", controller: 'navCtrl', scope: { topics: '=', toggle: '=' }, link : function(scope, elements, attributes){ console.log("jquery menu functionality working!"); // jQuery below makes it so that when I click on a topic in the menu, the menu disappears and slides back in. Find other jQuery on navDirective.js(the only other place where I use jQuery on the app. I copied this function from there). // $('.slideout-menu').on("click", function() { // if($('.slideout-menu:visible')) { // $('.slideout-menu').animate({right:'-350px'}, 350, function() {}); // } // }); // Jquery to make the hamburger menu slide out(to open) $('#slideout-open-menu-button').on("click", function() { if($('.slideout-menu:hidden')) { $('.slideout-menu').animate({right:'0'}, 350, function() {}); } }); // Jquery to make the hamburger menu slide in(to close) $('#slideout-closed-menu-button').on("click", function() { if($('.slideout-menu:visible')) { $('.slideout-menu').animate({right:'-350px'}, 350, function() {}); } }); } } });
974450614f8312116b14f0b419d4e88c4e381534
[ "JavaScript" ]
7
JavaScript
mslends/flashy
383f006bef326ff54eee9c2b97c7df44db2922e7
7c3dfa81c24c7aeb917e290e6c630bbc90ad55bd
refs/heads/master
<repo_name>aehparta/maps-cs<file_sep>/quark/setup.sh #!/bin/bash quark_path="$HOME/.wine/drive_c/Program Files (x86)/QuArK 6.6" if [ -d "$quark_path" ]; then ln -s "$PWD/duges.qrk" "$quark_path/duges.qrk" else echo "ERROR: QuArK path not found: $quark_path" fi steam_hl_path="$HOME/.steam/steam/steamapps/common/Half-Life" if [ -d "$steam_hl_path" ]; then if [ ! -e "Half-Life" ]; then ln -s "$steam_hl_path" "Half-Life" fi if [ ! -f "$steam_hl_path/HL.EXE" ]; then touch "$steam_hl_path/HL.EXE" fi if [ ! -e "$steam_hl_path/cstrike/itsItaly.wad" ]; then ln -s "$steam_hl_path/cstrike/itsitaly.wad" "$steam_hl_path/cstrike/itsItaly.wad" fi else echo "ERROR: Half-Life installation not found from path: $steam_hl_path" fi echo "If no errors, now set QuArK Half-Life path to Half-Life under this directory" <file_sep>/raspberry/textures/image-blocks.php <?php if (!isset($_SERVER['argv'][2]) || !is_file($_SERVER['argv'][1])) { echo "usage: <script> <image> <out-prefix>\n"; exit(1); } $img = new Imagick($_SERVER['argv'][1]); if (!$img) { echo "cannot load image\n"; exit(1); } $outfile_prefix = $_SERVER['argv'][2]; $ext = pathinfo($_SERVER['argv'][1], PATHINFO_EXTENSION); $w_div = 5; $h_div = 3; $w = $img->getImageWidth(); $h = $img->getImageHeight(); $wb = $w / $w_div; $hb = $h / $h_div; $wf = 512; $hf = 512; echo "original w: $w, h: $h\n"; echo "blocks in original w: $wb, h: $hb\n"; echo "final blocks w: $wf, h: $hf\n"; for ($y = 0; $y < $h; $y += $hb) { echo ' * y: ' . ($y / $hb) . "\n"; for ($x = 0; $x < $w; $x += $wb) { $bi = clone $img; $bi->cropImage($wb, $hb, $x, $y); $bi->resizeImage($wf, $hf, imagick::FILTER_SINC, 1.0); $outfile = $outfile_prefix . '-' . ($y / $hb) . '-' . ($x / $wb) . '.' . $ext; echo ' - x: ' . ($x / $wb) . ' -> ' . $outfile . "\n"; $bi->writeImage($outfile); } } <file_sep>/README.md # Maps for Counter-Strike 1.6 Self-made Counter-Strike 1.6 map sources and compile scripts/tools for ***linux***. Probably only useful to myself. ## Installation 1. Install QuArK (6.6) 2. Install Steam and Counter-Strike 1.6 3. Init for QuArK (`setup.sh` expects QuArK 6.6) ``` cd quark ./setup.sh ``` 4. Start QuArK * `Edit -> Configuration -> Games/Half-Life` * `Directory of Half-Life` to `quark/Half-Life` under this folder * `Add-ons...` add `duges.qrk` ## Compile ```sh ./compile.sh <map> <fast|final|leak> [run] ``` <file_sep>/quark/update-duges.qrk.sh #!/bin/bash quark_path="/home/aehparta/.wine/drive_c/Program Files (x86)/QuArK 6.6" if [ -f "$quark_path/duges.qrk" ]; then cp -a "$quark_path/duges.qrk" "duges.qrk" fi <file_sep>/compile.sh #!/bin/bash game_run="no" mode="" for arg in ${@:2}; do case $arg in run) game_run="yes" ;; fast) mode="fast" ;; final) mode="final" ;; leaks) mode="leak" ;; esac done # set to custom in $map/attributes.txt ambient_r="0.0" ambient_g="0.0" ambient_b="0.0" threads=4 game_path="$HOME/.steam/steam/steamapps/common/Half-Life" repo_path=`pwd` tools_path="$repo_path/zhlt-vluzacn/bin" map="$1" hlcsg_opt="" hlbsp_opt="" hlvis_opt="" hlrad_opt="" # load custom attributes if [ -f "$map/attributes.txt" ]; then source "$map/attributes.txt" fi if [ "$mode" == "leak" ]; then hlbsp_opt="$hlbsp_opt -leakonly" elif [ "$mode" == "fast" ]; then hlvis_opt="$hlvis_opt -fast" hlrad_opt="$hlrad_opt -fast" else hlvis_opt="$hlvis_opt -full" hlrad_opt="$hlrad_opt -extra" fi map_file="maps/$map.map" bsp_file="maps/$map.bsp" lights_file="$repo_path/$map/lights.rad" if [ ! -f "$lights_file" ]; then lights_file="$repo_path/lights.rad" fi cd "$game_path/tmpQuArK" if [ "$map" == "" ]; then echo "usage: <map> [fast]" exit 1 elif [ ! -f "$map_file" ]; then echo "map_file file not found: $game_path/tmpQuArK/$map_file" exit 1 fi if [ "$mode" != "" ]; then $tools_path/hlcsg -threads $threads -low -nowadtextures $hlcsg_opt "$map_file" if [ "$?" != "0" ]; then echo "ERROR: hlcsg failed" exit 1 fi $tools_path/hlbsp -threads $threads -low $hlbsp_opt "$map_file" if [ "$?" != "0" ]; then echo "ERROR: hlbsp failed" exit 1 fi if [ "$mode" == "leak" ]; then echo "LEAK CHECK OK" exit 0 fi $tools_path/hlvis -threads $threads -low $hlvis_opt "$map_file" if [ "$?" != "0" ]; then echo "ERROR: hlvis failed" exit 1 fi $tools_path/hlrad -threads $threads -low -lights "$lights_file" -ambient "$ambient_r" "$ambient_g" "$ambient_b" $hlrad_opt "$map_file" if [ "$?" != "0" ]; then echo "ERROR: hlrad failed" exit 1 fi echo "COMPILE OK" fi if [ -f "$bsp_file" ]; then cp "$bsp_file" "$repo_path/bsp/$map.bsp" mkdir -p "$game_path/cstrike_downloads/maps" cp "$bsp_file" "$game_path/cstrike_downloads/$bsp_file" if [ "$game_run" == "yes" ]; then steam -applaunch 10 -console +sv_lan 1 +set sv_cheats 1 +map "$map" fi else echo "ERROR: bsp file does not exists: $bsp_file" exit 1 fi exit 0
ed5b326e03c1e48841427bdebe2757b49e5eb8c9
[ "Markdown", "PHP", "Shell" ]
5
Shell
aehparta/maps-cs
7d560461fb1f9967a69e9596e67b5715b827dc2f
49da54c9d061bfd4d026106aad4a3278ce53f2f7
refs/heads/master
<repo_name>griff3n/EmbSys<file_sep>/Blatt_3/sos/sos.ino #define PIN PB_3 #define SPEED_S 300 #define SPEED_O 800 void setup() { // put your setup code here, to run once: pinMode(PIN, OUTPUT); } void character(int speed) { digitalWrite(PIN, HIGH); delay(speed); digitalWrite(PIN, LOW); delay(300); } void loop() { for (int x = 1; x <= 3; x++) { character(SPEED_S); } delay(100); for (int x = 1; x <= 3; x++) { character(SPEED_O); } delay(100); for (int x = 1; x <= 3; x++) { character(SPEED_S); } delay(2000); }
53bf55fe14caa80c74be6820a604fe8ddf11d159
[ "C++" ]
1
C++
griff3n/EmbSys
cf9921b6234fd56361d7398fa2e11ff72bbb45fa
831dbd5c52e188ff335111c39eb409abeae27245
refs/heads/master
<file_sep>import React, {Component} from 'react'; import PropTypes from 'prop-types'; import './metricsCompareView.scss'; import Multiselect from 'react-bootstrap-multiselect'; import {Well, Alert} from 'react-bootstrap'; import Select from 'react-select'; import backend from '../Backend/backend'; import {parseServerError} from '../Helpers/utils'; import {MetricsPlotView} from '../MetricsPlotView/metricsPlotView'; import {ProgressWrapper} from '../Helpers/hoc'; class MetricsCompareView extends Component { static propTypes = { runIds: PropTypes.arrayOf(Number).isRequired, isSelected: PropTypes.bool.isRequired }; runIdOptionsDomNode = null; metricLabelOptions = [{ label: 'Run Id', value: '_id' }, { label: 'Experiment Name', value: 'experiment.name' }]; constructor(props) { super(props); this.state = { isLoadingRuns: false, metrics: [], runIdOptions: [], error: '', metricLabel: '_id' }; } _initializeState = () => { this._loadData(); this._populateRunIdOptions(); }; componentDidMount() { const {isSelected} = this.props; if (isSelected) { // Load data only when the component is being displayed this._initializeState(); } } componentDidUpdate(prevProps, _prevState, _snapshot) { // Populate runId options every time runIds change const {runIds, isSelected} = this.props; if (JSON.stringify(prevProps.runIds) !== JSON.stringify(runIds) && isSelected) { this._initializeState(); } } _populateRunIdOptions = () => { const {runIds} = this.props; const runIdOptions = runIds.map(runId => { return { label: runId, value: runId, selected: true }; }); this.setState({ runIdOptions }); }; _getSelectedRunIds = runIdOptions => runIdOptions.filter(option => option.selected === true) .map(option => Number(option.value)); _handleRunIdsChange = _e => { const runIds = this.runIdOptionsDomNode.$multiselect.val(); this.setState(({runIdOptions}) => ({ runIdOptions: runIdOptions.map(option => { option.selected = runIds.includes(String(option.value)); return option; }) })); }; _loadData = () => { const {runIds} = this.props; if (runIds.length >= 2) { this.setState({ isLoadingRuns: true, error: '' }); const queryString = JSON.stringify({ run_id: { $in: runIds } }); backend.get('api/v1/Metrics', { params: { query: queryString, populate: 'run' } }).then(response => { this.setState({ metrics: response.data, isLoadingRuns: false }); }).catch(error => { const message = parseServerError(error); this.setState({ isLoadingRuns: false, error: message }); }); } else { this.setState({ error: 'At-least two runs should be selected for comparison' }); } }; _handleMetricLabelChange = ({value}) => { this.setState({ metricLabel: value }); }; render() { const {metrics, isLoadingRuns, runIdOptions, error, metricLabel} = this.state; const selectedRunIds = this._getSelectedRunIds(runIdOptions); const metricsResponseForPlot = metrics.filter(metric => selectedRunIds.includes(metric.run_id)); const errorAlert = error ? <Alert bsStyle='danger'>{error}</Alert> : ''; const getOption = value => { return this.metricLabelOptions.find(option => option.value === value); }; return ( <div className='metrics-compare-view'> <ProgressWrapper id='metrics-compare-progress-wrapper' loading={isLoadingRuns}> <div> {errorAlert} <Well bsSize='small' className='run-id-filter-well'> <h5>Runs: </h5> <div className='run-id-options-wrapper'> <Multiselect ref={el => this.runIdOptionsDomNode = el} includeSelectAllOption multiple enableHTML buttonText={(options, _select) => { if (options.length === 0) { return 'None selected'; } return `${options.length} selected`; }} selectedClass='run-id-selected' id='run_ids' maxHeight={300} data={runIdOptions} onSelectAll={this._handleRunIdsChange} onChange={this._handleRunIdsChange} onDeselectAll={this._handleRunIdsChange} /> </div> <h5>Metric Label: </h5> <div className='metric-label-options-wrapper'> <Select className='select-metric-label' test-attr='select-metric-label' options={this.metricLabelOptions} placeholder='Metric Label' value={getOption(metricLabel)} onChange={this._handleMetricLabelChange} /> </div> </Well> <MetricsPlotView metricsResponse={metricsResponseForPlot} runId='' metricLabel={metricLabel}/> </div> </ProgressWrapper> </div> ); } } export {MetricsCompareView};
2875f582ecc9dbf8c6044310b0bd83205ad6dabe
[ "JavaScript" ]
1
JavaScript
abigailshchur/omniboard
ec8741001def022495a8aeac082ad4cae81912ce
5663d27fb2e4283ef66f29d4a57a4a6a6a820e1d
refs/heads/master
<repo_name>zhenggaoming/take-your-time-cake<file_sep>/src/main/java/com/bdqn/tytcake/TytcakeApplication.java package com.bdqn.tytcake; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class TytcakeApplication { public static void main(String[] args) { SpringApplication.run(TytcakeApplication.class, args); } }
28ec82b5084eb2c52e398932c94f0c6625acf516
[ "Java" ]
1
Java
zhenggaoming/take-your-time-cake
f502dc4c0725f8e7187baeb92b9f1974e703b16e
80a3db8b6181f4a98bcbb80b60822a4dbad41cb4
refs/heads/master
<repo_name>xyzlat/herbie<file_sep>/herbieapp/services/message_publisher.py import json import logging from django.core.serializers.json import DjangoJSONEncoder from django.utils.functional import cached_property from kafka import KafkaProducer from herbie import settings from herbieapp.models import AbstractBusinessEntity from herbieapp.services.utils import BusinessEntityUtils class EntityUpdateMessage: def __init__(self, _type, key, version, payload, created, modified, tags): self.tags = tags self.action = 'update' self.type = _type self.key = key self.version = version self.payload = payload self.created = created self.modified = modified class EntityDeleteMessage: def __init__(self, _type, key, version=None): self.action = 'delete' self.type = _type self.key = key self.version = version class MessagePublisher: _logger = logging.getLogger(__name__) def send_entity_update_message(self, entity: AbstractBusinessEntity, tags=None): if tags is None: tags = [] self._send_message(EntityUpdateMessage( BusinessEntityUtils.get_entity_type_name(entity), entity.key, entity.version, entity.data, entity.created, entity.modified, tags )) def send_entity_delete_message(self, entity: AbstractBusinessEntity): self._send_message(EntityDeleteMessage( BusinessEntityUtils.get_entity_type_name(entity), entity.key, entity.version )) def _send_message(self, message): self._producer.send(message.type, value=message, key=message.key)\ .add_callback(self._on_send_success)\ .add_errback(self._on_send_error) @cached_property def _producer(self) -> KafkaProducer: self._logger.info('initializing kafka address: {} timeout: {} ' .format(settings.KAFKA.get('SERVERS'), settings.KAFKA.get('TIMEOUT'))) # lazy init of the kafka producer, because kafka may not be available yet when starting the app with docker return KafkaProducer(bootstrap_servers=settings.KAFKA.get('SERVERS'), request_timeout_ms=settings.KAFKA.get('TIMEOUT'), key_serializer=str.encode, value_serializer=lambda v: json.dumps(v.__dict__, cls=DjangoJSONEncoder).encode('utf-8')) def _on_send_success(self, record_metadata): self._logger.debug('Message delivered to {} [{}]'.format(record_metadata.topic, record_metadata.partition)) def _on_send_error(self, excp): self._logger.error('Message delivery failed: {}'.format(excp), exc_info=excp) def shutdown(self): self._logger.info('flushing kafka producer') self._producer.flush() <file_sep>/requirements.txt kafka-python==1.4.7 Django==3.0 psycopg2==2.8.4 django-model-utils==4.0.0 djangorestframework==3.11.0 pytz==2019.3 sqlparse==0.3.0 git+https://github.com/project-a/herbie-json-schema.git jsonschema==3.2.0 django-environ==0.4.5 social-auth-app-django==3.1.0 social-auth-core==3.2.0 pytest==5.3.1 pytest-django==3.5.1<file_sep>/README.md # Herbie [![Build Status](https://travis-ci.org/project-a/herbie.svg?branch=master)](https://travis-ci.org/project-a/herbie) ## Overview Two Problems that can often be observed in a distributed service architecture are: A. **Too many dependencies** between services. B. No common **platform-wide definition** of a data object or business entity. Herbie approaches those problems with the idea of a _schema registry combined with a central data store_ for business entities. It is built with Django and comes with a simple API to create business entities. The integration of _json-schema_ allows to define custom schema definitions, that will be used to validate the entities. A service that needs updates of a certain entity-type is also able to subscribe to _event-streams_, the default technology for that is Kafka. The philosophy behind Herbie is to avoid behavior that appears to a developers as "magic" and instead is built in very straightforward way, following Django best practices. It is also meant to be extendable and easy to adapt. **Further reading:** - [Core Concepts of Herbie](docs/core_concepts.md) ## Quickstart In order to set up the local environment quickly, you first need to install [docker](https://docs.docker.com/install/#server) and [docker-compose](https://docs.docker.com/compose/install/). Afterwards go to the root-folder of the _herbie-project_ and run: `$ docker-compose up -d` and then `$ docker logs herbie-app -f` to watch the progress. After the boot-process is finished switch to your browser and check: [http://localhost:8000](http://localhost:8000) _Note:_ Please make sure that port 8000 is not blocked by another service on your host-machine. # How to setup herbie for your project? ### 1 Clone/Fork In order to setup a Herbie-Project from scratch you can either fork or clone the repository. We suggest you to fork the project, because like that you have a separate repository so you can make custom modifications (e.g. change the messaging provider) and at the same time receive changes from the official repository in an easy manner ### 2 Add Business Entities Schemas Package Next step is to define your schemas for your business entities and integrate them with Herbie. There are 2 choices, having a different repository for your schemas and load them to herbie as a python package with pip, or adding them directly to the Herbie as a python package ##### Business Entities Schemas package folders structure ``` ---business_entities_schemas init.py ------ business_entity1 ------- business_entity1_v1.json ------- business_entity1_v2.json ------ business_entity2 ``` ##### example ``` ---herbie-json-schema init.py ------ customer ------- customer_v1.json ------- customer_v2.json ------ product ------- product_v1.json ``` https://github.com/project-a/herbie-json-schema ##### Different Github Repository - Create a github repository - In requirements.txt file append your schemas repository url in order for pip to collect your package. (e.g. git+https://github.com/project-a/herbie-json-schema.git) - In setting.py file of Herbie project assign your package name to the 'SCHEMA_REGISTRY_PACKAGE' variable (Keep in mind that in case of a private repository, it also needs to provide a private ssh key to the docker container and pull the project with ssh in order for Herbie to have access on the repository. For the developing process you can directly provide you personal private ssh key but for production you need to create a new one for Herbie) ##### Add them directly to the Project - Add/Create your package to the root folder of Herbie Project. - In setting.py file of Herbie project assign your package name to the 'SCHEMA_REGISTRY_PACKAGE' variable # Run Herbie on Docker - Clone the project(from your forked or the official repository) - Build and run Herbie ``` docker-compose up -d --build ``` - Connect to herbie-app container ``` docker exec -it herbie-app bash ``` - Generate business object model classes from your schemas package ``` python manage.py generatemodels ``` - Create and execute migration files to initialize your database ``` python manage.py makemigrations python manage.py migrate ``` ## How to generate business object model classes Model classes can be generated based on the JSON schema definitions by running this command: `$ python manage.py generatemodels` ## Import business json schemas Run the command to import json schemas into db `python manage.py import_json_schemas` ## API Authentication - [How to add an Auth Token for a Service?](docs/add_service_client.md) ## Admin Panel - [How to add social login?](docs/social_login.md) ## How to change the messaging system? The default Herbie setup uses Kafka (mainly because it's very popular) for distributing the business entity messages in a JSON format. But it should be easy to use any other messaging system: The messaging is implemented in [herbieapp/services/message_publisher.py](herbieapp/services/message_publisher.py). To replace the Kafka client with any other client, you just have to change the implementation of the internal `_send_message` method of the `MessagePublisher` class. Then you can also remove or replace the Kafka connection settings in [herbie/settings.py](herbie/settings.py), and also remove or replace the Kafka and Zookeeper images in the [docker-compose.yml](docker-compose.yml). ## Herbie - Development - [PyCharm Configuration](docs/pycharm_config.md) <file_sep>/examples/consumer/consumer.md # Example consumer for business entity messages A basic example script for reading messages of a business entity. It will continuously read the messages and print them to sys.stdout. To start the consumer script locally, build and run the docker image: ``` cd examples/consumer/ docker build -t "exampleconsumer" . docker run --net herbie_herbie-network exampleconsumer ``` (The herbie container should also be running, so that the consumer can connect to the herbie-kafka)
d4ea346cc6c24b3a73a79edf1023e682c3fb1375
[ "Markdown", "Python", "Text" ]
4
Python
xyzlat/herbie
b5b2e2d4d401f09e3ed2de06ca97599e7d8d7af6
75bd16693477fd2353ed19fc20f78011b3620ab8
refs/heads/master
<file_sep>/* * * MIT License * * Copyright (c) 2020 TerraForged * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.dags.noise.selector; import me.dags.noise.Module; import me.dags.noise.func.Interpolation; /** * @author dags <<EMAIL>> */ public class Blend extends Selector { protected final Module source0; protected final Module source1; protected final float midpoint; protected final float blendLower; protected final float blendUpper; protected final float blendRange; public Blend(Module selector, Module source0, Module source1, float midPoint, float blendRange, Interpolation interpolation) { super(selector, new Module[]{source0, source1}, interpolation); float mid = selector.minValue() + ((selector.maxValue() - selector.minValue()) * midPoint); this.source0 = source0; this.source1 = source1; this.midpoint = midPoint; this.blendLower = Math.max(selector.minValue(), mid - (blendRange / 2F)); this.blendUpper = Math.min(selector.maxValue(), mid + (blendRange / 2F)); this.blendRange = blendUpper - blendLower; } @Override public float selectValue(float x, float y, float select) { if (select < blendLower) { return source0.getValue(x, y); } if (select > blendUpper) { return source1.getValue(x, y); } float alpha = (select - blendLower) / blendRange; return blendValues(source0.getValue(x, y), source1.getValue(x, y), alpha); } } <file_sep>/* * * MIT License * * Copyright (c) 2020 TerraForged * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.dags.noise.source; import me.dags.noise.Module; import me.dags.noise.util.NoiseUtil; public class Line implements Module { private final float x1; private final float y1; private final float x2; private final float y2; private final float dx; private final float dy; private final float orthX1; private final float orthY1; private final float orthX2; private final float orthY2; private final float length2; private final float featherBias; private final float featherScale; private final Module fadeIn; private final Module fadeOut; private final Module radius; public Line(float x1, float y1, float x2, float y2, Module radius2, Module fadeIn, Module fadeOut, float feather) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.orthX1 = x1 + (y2 - y1); this.orthY1 = y1 + (x1 - x2); this.orthX2 = x2 + (y2 - y1); this.orthY2 = y2 + (x1 - x2); this.dx = x2 - x1; this.dy = y2 - y1; this.fadeIn = fadeIn; this.fadeOut = fadeOut; this.radius = radius2; this.featherScale = feather; this.featherBias = 1 - feather; this.length2 = dx * dx + dy * dy; } @Override public float getValue(float x, float y) { float widthMod = getWidthModifier(x, y); return getValue(x, y, widthMod); } public float getValue(float x, float y, float widthModifier) { float dist2 = getDistance2(x, y); float radius2 = radius.getValue(x, y) * widthModifier; if (dist2 > radius2) { return 0; } float value = dist2 / radius2; if (featherScale == 0) { return 1 - value; } float feather = featherBias + (widthModifier * featherScale); return (1 - value) * feather; } /** * Check if the position x,y is 'before' the start of this line */ public boolean clipStart(float x, float y) { return sign(x, y, x1, y1, orthX1, orthY1) > 0; } /** * Check if the position x,y is past the end of this line */ public boolean clipEnd(float x, float y) { return sign(x, y, x2, y2, orthX2, orthY2) < 0; } public float getWidthModifier(float x, float y) { float d1 = dist2(x, y, x1, y1); if (d1 == 0) { return 0; } float d2 = dist2(x, y, x2, y2); if (d2 == 0) { return 0; } float fade = 1F; float in = fadeIn.getValue(x, y); float out = fadeOut.getValue(x, y); if (in > 0) { float dist = in * length2; if (d1 < dist) { fade *= (d1 / dist); } } if (out > 0) { float dist = out * length2; if (d2 < dist) { fade *= (d2 / dist); } } return fade; } private float getDistance2(float x, float y) { float t = ((x - x1) * dx) + ((y - y1) * dy); float s = NoiseUtil.clamp(t / length2, 0, 1); float ix = x1 + s * dx; float iy = y1 + s * dy; return dist2(x, y, ix, iy); } public static float dist2(float x1, float y1, float x2, float y2) { float dx = x2 - x1; float dy = y2 - y1; return dx * dx + dy * dy; } public static int sign(float x, float y, float x1, float y1, float x2, float y2) { float value = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1); if (value == 0) { return 0; } if (value < 0) { return -1; } return 1; } } <file_sep>/* * * MIT License * * Copyright (c) 2020 TerraForged * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.dags.noise.util; /** * https://github.com/Auburns/FastNoise_Java */ public class NoiseUtil { public static final int X_PRIME = 1619; public static final int Y_PRIME = 31337; public static final float CUBIC_2D_BOUNDING = 1 / (float) (1.5 * 1.5); public static final float PI2 = (float) (Math.PI * 2.0); public static final float SQRT2 = (float) Math.sqrt(2); private static final int SIN_BITS, SIN_MASK, SIN_COUNT; private static final float radFull, radToIndex; private static final float degFull, degToIndex; public static final Vec2f[] GRAD_2D = { new Vec2f(-1, -1), new Vec2f(1, -1), new Vec2f(-1, 1), new Vec2f(1, 1), new Vec2f(0, -1), new Vec2f(-1, 0), new Vec2f(0, 1), new Vec2f(1, 0), }; public static final Vec2f[] GRAD_2D_24 = { new Vec2f( 0.130526192220052f, 0.99144486137381f), new Vec2f( 0.38268343236509f, 0.923879532511287f), new Vec2f( 0.608761429008721f, 0.793353340291235f), new Vec2f( 0.608761429008721f, 0.793353340291235f), // Repeat due to selector math new Vec2f( 0.793353340291235f, 0.608761429008721f), new Vec2f( 0.923879532511287f, 0.38268343236509f), new Vec2f( 0.99144486137381f, 0.130526192220051f), new Vec2f( 0.99144486137381f, 0.130526192220051f), // Repeat new Vec2f( 0.99144486137381f, -0.130526192220051f), new Vec2f( 0.923879532511287f,-0.38268343236509f), new Vec2f( 0.793353340291235f,-0.60876142900872f), new Vec2f( 0.793353340291235f,-0.60876142900872f), // Repeat new Vec2f( 0.608761429008721f,-0.793353340291235f), new Vec2f( 0.38268343236509f, -0.923879532511287f), new Vec2f( 0.130526192220052f,-0.99144486137381f), new Vec2f( 0.130526192220052f,-0.99144486137381f), // Repeat new Vec2f(-0.130526192220052f,-0.99144486137381f), new Vec2f(-0.38268343236509f, -0.923879532511287f), new Vec2f(-0.608761429008721f,-0.793353340291235f), new Vec2f(-0.608761429008721f,-0.793353340291235f), // Repeat new Vec2f(-0.793353340291235f,-0.608761429008721f), new Vec2f(-0.923879532511287f,-0.38268343236509f), new Vec2f(-0.99144486137381f, -0.130526192220052f), new Vec2f(-0.99144486137381f, -0.130526192220052f), // Repeat new Vec2f(-0.99144486137381f, 0.130526192220051f), new Vec2f(-0.923879532511287f, 0.38268343236509f), new Vec2f(-0.793353340291235f, 0.608761429008721f), new Vec2f(-0.793353340291235f, 0.608761429008721f), // Repeat new Vec2f(-0.608761429008721f, 0.793353340291235f), new Vec2f(-0.38268343236509f, 0.923879532511287f), new Vec2f(-0.130526192220052f, 0.99144486137381f), new Vec2f(-0.130526192220052f, 0.99144486137381f) // Repeat }; public static final Vec2f[] CELL_2D = { new Vec2f(-0.4313539279f, 0.1281943404f), new Vec2f(-0.1733316799f, 0.415278375f), new Vec2f(-0.2821957395f, -0.3505218461f), new Vec2f(-0.2806473808f, 0.3517627718f), new Vec2f(0.3125508975f, -0.3237467165f), new Vec2f(0.3383018443f, -0.2967353402f), new Vec2f(-0.4393982022f, -0.09710417025f), new Vec2f(-0.4460443703f, -0.05953502905f), new Vec2f(-0.302223039f, 0.3334085102f), new Vec2f(-0.212681052f, -0.3965687458f), new Vec2f(-0.2991156529f, 0.3361990872f), new Vec2f(0.2293323691f, 0.3871778202f), new Vec2f(0.4475439151f, -0.04695150755f), new Vec2f(0.1777518f, 0.41340573f), new Vec2f(0.1688522499f, -0.4171197882f), new Vec2f(-0.0976597166f, 0.4392750616f), new Vec2f(0.08450188373f, 0.4419948321f), new Vec2f(-0.4098760448f, -0.1857461384f), new Vec2f(0.3476585782f, -0.2857157906f), new Vec2f(-0.3350670039f, -0.30038326f), new Vec2f(0.2298190031f, -0.3868891648f), new Vec2f(-0.01069924099f, 0.449872789f), new Vec2f(-0.4460141246f, -0.05976119672f), new Vec2f(0.3650293864f, 0.2631606867f), new Vec2f(-0.349479423f, 0.2834856838f), new Vec2f(-0.4122720642f, 0.1803655873f), new Vec2f(-0.267327811f, 0.3619887311f), new Vec2f(0.322124041f, -0.3142230135f), new Vec2f(0.2880445931f, -0.3457315612f), new Vec2f(0.3892170926f, -0.2258540565f), new Vec2f(0.4492085018f, -0.02667811596f), new Vec2f(-0.4497724772f, 0.01430799601f), new Vec2f(0.1278175387f, -0.4314657307f), new Vec2f(-0.03572100503f, 0.4485799926f), new Vec2f(-0.4297407068f, -0.1335025276f), new Vec2f(-0.3217817723f, 0.3145735065f), new Vec2f(-0.3057158873f, 0.3302087162f), new Vec2f(-0.414503978f, 0.1751754899f), new Vec2f(-0.3738139881f, 0.2505256519f), new Vec2f(0.2236891408f, -0.3904653228f), new Vec2f(0.002967775577f, -0.4499902136f), new Vec2f(0.1747128327f, -0.4146991995f), new Vec2f(-0.4423772489f, -0.08247647938f), new Vec2f(-0.2763960987f, -0.355112935f), new Vec2f(-0.4019385906f, -0.2023496216f), new Vec2f(0.3871414161f, -0.2293938184f), new Vec2f(-0.430008727f, 0.1326367019f), new Vec2f(-0.03037574274f, -0.4489736231f), new Vec2f(-0.3486181573f, 0.2845441624f), new Vec2f(0.04553517144f, -0.4476902368f), new Vec2f(-0.0375802926f, 0.4484280562f), new Vec2f(0.3266408905f, 0.3095250049f), new Vec2f(0.06540017593f, -0.4452222108f), new Vec2f(0.03409025829f, 0.448706869f), new Vec2f(-0.4449193635f, 0.06742966669f), new Vec2f(-0.4255936157f, -0.1461850686f), new Vec2f(0.449917292f, 0.008627302568f), new Vec2f(0.05242606404f, 0.4469356864f), new Vec2f(-0.4495305179f, -0.02055026661f), new Vec2f(-0.1204775703f, 0.4335725488f), new Vec2f(-0.341986385f, -0.2924813028f), new Vec2f(0.3865320182f, 0.2304191809f), new Vec2f(0.04506097811f, -0.447738214f), new Vec2f(-0.06283465979f, 0.4455915232f), new Vec2f(0.3932600341f, -0.2187385324f), new Vec2f(0.4472261803f, -0.04988730975f), new Vec2f(0.3753571011f, -0.2482076684f), new Vec2f(-0.273662295f, 0.357223947f), new Vec2f(0.1700461538f, 0.4166344988f), new Vec2f(0.4102692229f, 0.1848760794f), new Vec2f(0.323227187f, -0.3130881435f), new Vec2f(-0.2882310238f, -0.3455761521f), new Vec2f(0.2050972664f, 0.4005435199f), new Vec2f(0.4414085979f, -0.08751256895f), new Vec2f(-0.1684700334f, 0.4172743077f), new Vec2f(-0.003978032396f, 0.4499824166f), new Vec2f(-0.2055133639f, 0.4003301853f), new Vec2f(-0.006095674897f, -0.4499587123f), new Vec2f(-0.1196228124f, -0.4338091548f), new Vec2f(0.3901528491f, -0.2242337048f), new Vec2f(0.01723531752f, 0.4496698165f), new Vec2f(-0.3015070339f, 0.3340561458f), new Vec2f(-0.01514262423f, -0.4497451511f), new Vec2f(-0.4142574071f, -0.1757577897f), new Vec2f(-0.1916377265f, -0.4071547394f), new Vec2f(0.3749248747f, 0.2488600778f), new Vec2f(-0.2237774255f, 0.3904147331f), new Vec2f(-0.4166343106f, -0.1700466149f), new Vec2f(0.3619171625f, 0.267424695f), new Vec2f(0.1891126846f, -0.4083336779f), new Vec2f(-0.3127425077f, 0.323561623f), new Vec2f(-0.3281807787f, 0.307891826f), new Vec2f(-0.2294806661f, 0.3870899429f), new Vec2f(-0.3445266136f, 0.2894847362f), new Vec2f(-0.4167095422f, -0.1698621719f), new Vec2f(-0.257890321f, -0.3687717212f), new Vec2f(-0.3612037825f, 0.2683874578f), new Vec2f(0.2267996491f, 0.3886668486f), new Vec2f(0.207157062f, 0.3994821043f), new Vec2f(0.08355176718f, -0.4421754202f), new Vec2f(-0.4312233307f, 0.1286329626f), new Vec2f(0.3257055497f, 0.3105090899f), new Vec2f(0.177701095f, -0.4134275279f), new Vec2f(-0.445182522f, 0.06566979625f), new Vec2f(0.3955143435f, 0.2146355146f), new Vec2f(-0.4264613988f, 0.1436338239f), new Vec2f(-0.3793799665f, -0.2420141339f), new Vec2f(0.04617599081f, -0.4476245948f), new Vec2f(-0.371405428f, -0.2540826796f), new Vec2f(0.2563570295f, -0.3698392535f), new Vec2f(0.03476646309f, 0.4486549822f), new Vec2f(-0.3065454405f, 0.3294387544f), new Vec2f(-0.2256979823f, 0.3893076172f), new Vec2f(0.4116448463f, -0.1817925206f), new Vec2f(-0.2907745828f, -0.3434387019f), new Vec2f(0.2842278468f, -0.348876097f), new Vec2f(0.3114589359f, -0.3247973695f), new Vec2f(0.4464155859f, -0.0566844308f), new Vec2f(-0.3037334033f, -0.3320331606f), new Vec2f(0.4079607166f, 0.1899159123f), new Vec2f(-0.3486948919f, -0.2844501228f), new Vec2f(0.3264821436f, 0.3096924441f), new Vec2f(0.3211142406f, 0.3152548881f), new Vec2f(0.01183382662f, 0.4498443737f), new Vec2f(0.4333844092f, 0.1211526057f), new Vec2f(0.3118668416f, 0.324405723f), new Vec2f(-0.272753471f, 0.3579183483f), new Vec2f(-0.422228622f, -0.1556373694f), new Vec2f(-0.1009700099f, -0.4385260051f), new Vec2f(-0.2741171231f, -0.3568750521f), new Vec2f(-0.1465125133f, 0.4254810025f), new Vec2f(0.2302279044f, -0.3866459777f), new Vec2f(-0.3699435608f, 0.2562064828f), new Vec2f(0.105700352f, -0.4374099171f), new Vec2f(-0.2646713633f, 0.3639355292f), new Vec2f(0.3521828122f, 0.2801200935f), new Vec2f(-0.1864187807f, -0.4095705534f), new Vec2f(0.1994492955f, -0.4033856449f), new Vec2f(0.3937065066f, 0.2179339044f), new Vec2f(-0.3226158377f, 0.3137180602f), new Vec2f(0.3796235338f, 0.2416318948f), new Vec2f(0.1482921929f, 0.4248640083f), new Vec2f(-0.407400394f, 0.1911149365f), new Vec2f(0.4212853031f, 0.1581729856f), new Vec2f(-0.2621297173f, 0.3657704353f), new Vec2f(-0.2536986953f, -0.3716678248f), new Vec2f(-0.2100236383f, 0.3979825013f), new Vec2f(0.3624152444f, 0.2667493029f), new Vec2f(-0.3645038479f, -0.2638881295f), new Vec2f(0.2318486784f, 0.3856762766f), new Vec2f(-0.3260457004f, 0.3101519002f), new Vec2f(-0.2130045332f, -0.3963950918f), new Vec2f(0.3814998766f, -0.2386584257f), new Vec2f(-0.342977305f, 0.2913186713f), new Vec2f(-0.4355865605f, 0.1129794154f), new Vec2f(-0.2104679605f, 0.3977477059f), new Vec2f(0.3348364681f, -0.3006402163f), new Vec2f(0.3430468811f, 0.2912367377f), new Vec2f(-0.2291836801f, -0.3872658529f), new Vec2f(0.2547707298f, -0.3709337882f), new Vec2f(0.4236174945f, -0.151816397f), new Vec2f(-0.15387742f, 0.4228731957f), new Vec2f(-0.4407449312f, 0.09079595574f), new Vec2f(-0.06805276192f, -0.444824484f), new Vec2f(0.4453517192f, -0.06451237284f), new Vec2f(0.2562464609f, -0.3699158705f), new Vec2f(0.3278198355f, -0.3082761026f), new Vec2f(-0.4122774207f, -0.1803533432f), new Vec2f(0.3354090914f, -0.3000012356f), new Vec2f(0.446632869f, -0.05494615882f), new Vec2f(-0.1608953296f, 0.4202531296f), new Vec2f(-0.09463954939f, 0.4399356268f), new Vec2f(-0.02637688324f, -0.4492262904f), new Vec2f(0.447102804f, -0.05098119915f), new Vec2f(-0.4365670908f, 0.1091291678f), new Vec2f(-0.3959858651f, 0.2137643437f), new Vec2f(-0.4240048207f, -0.1507312575f), new Vec2f(-0.3882794568f, 0.2274622243f), new Vec2f(-0.4283652566f, -0.1378521198f), new Vec2f(0.3303888091f, 0.305521251f), new Vec2f(0.3321434919f, -0.3036127481f), new Vec2f(-0.413021046f, -0.1786438231f), new Vec2f(0.08403060337f, -0.4420846725f), new Vec2f(-0.3822882919f, 0.2373934748f), new Vec2f(-0.3712395594f, -0.2543249683f), new Vec2f(0.4472363971f, -0.04979563372f), new Vec2f(-0.4466591209f, 0.05473234629f), new Vec2f(0.0486272539f, -0.4473649407f), new Vec2f(-0.4203101295f, -0.1607463688f), new Vec2f(0.2205360833f, 0.39225481f), new Vec2f(-0.3624900666f, 0.2666476169f), new Vec2f(-0.4036086833f, -0.1989975647f), new Vec2f(0.2152727807f, 0.3951678503f), new Vec2f(-0.4359392962f, -0.1116106179f), new Vec2f(0.4178354266f, 0.1670735057f), new Vec2f(0.2007630161f, 0.4027334247f), new Vec2f(-0.07278067175f, -0.4440754146f), new Vec2f(0.3644748615f, -0.2639281632f), new Vec2f(-0.4317451775f, 0.126870413f), new Vec2f(-0.297436456f, 0.3376855855f), new Vec2f(-0.2998672222f, 0.3355289094f), new Vec2f(-0.2673674124f, 0.3619594822f), new Vec2f(0.2808423357f, 0.3516071423f), new Vec2f(0.3498946567f, 0.2829730186f), new Vec2f(-0.2229685561f, 0.390877248f), new Vec2f(0.3305823267f, 0.3053118493f), new Vec2f(-0.2436681211f, -0.3783197679f), new Vec2f(-0.03402776529f, 0.4487116125f), new Vec2f(-0.319358823f, 0.3170330301f), new Vec2f(0.4454633477f, -0.06373700535f), new Vec2f(0.4483504221f, 0.03849544189f), new Vec2f(-0.4427358436f, -0.08052932871f), new Vec2f(0.05452298565f, 0.4466847255f), new Vec2f(-0.2812560807f, 0.3512762688f), new Vec2f(0.1266696921f, 0.4318041097f), new Vec2f(-0.3735981243f, 0.2508474468f), new Vec2f(0.2959708351f, -0.3389708908f), new Vec2f(-0.3714377181f, 0.254035473f), new Vec2f(-0.404467102f, -0.1972469604f), new Vec2f(0.1636165687f, -0.419201167f), new Vec2f(0.3289185495f, -0.3071035458f), new Vec2f(-0.2494824991f, -0.3745109914f), new Vec2f(0.03283133272f, 0.4488007393f), new Vec2f(-0.166306057f, -0.4181414777f), new Vec2f(-0.106833179f, 0.4371346153f), new Vec2f(0.06440260376f, -0.4453676062f), new Vec2f(-0.4483230967f, 0.03881238203f), new Vec2f(-0.421377757f, -0.1579265206f), new Vec2f(0.05097920662f, -0.4471030312f), new Vec2f(0.2050584153f, -0.4005634111f), new Vec2f(0.4178098529f, -0.167137449f), new Vec2f(-0.3565189504f, -0.2745801121f), new Vec2f(0.4478398129f, 0.04403977727f), new Vec2f(-0.3399999602f, -0.2947881053f), new Vec2f(0.3767121994f, 0.2461461331f), new Vec2f(-0.3138934434f, 0.3224451987f), new Vec2f(-0.1462001792f, -0.4255884251f), new Vec2f(0.3970290489f, -0.2118205239f), new Vec2f(0.4459149305f, -0.06049689889f), new Vec2f(-0.4104889426f, -0.1843877112f), new Vec2f(0.1475103971f, -0.4251360756f), new Vec2f(0.09258030352f, 0.4403735771f), new Vec2f(-0.1589664637f, -0.4209865359f), new Vec2f(0.2482445008f, 0.3753327428f), new Vec2f(0.4383624232f, -0.1016778537f), new Vec2f(0.06242802956f, 0.4456486745f), new Vec2f(0.2846591015f, -0.3485243118f), new Vec2f(-0.344202744f, -0.2898697484f), new Vec2f(0.1198188883f, -0.4337550392f), new Vec2f(-0.243590703f, 0.3783696201f), new Vec2f(0.2958191174f, -0.3391033025f), new Vec2f(-0.1164007991f, 0.4346847754f), new Vec2f(0.1274037151f, -0.4315881062f), new Vec2f(0.368047306f, 0.2589231171f), new Vec2f(0.2451436949f, 0.3773652989f), new Vec2f(-0.4314509715f, 0.12786735f), }; private static final float[] SIN; public static float map(float value, float min, float max, float range) { float dif = clamp(value, min, max) - min; if (dif > range) { return 1F; } return dif / range; } public static float clamp(float value, float min, float max) { if (value < min) { return min; } if (value > max) { return max; } return value; } public static float dot(float x0, float y0, float x1, float y1) { return x0 * x1 + y0 * y1; } public static float div(int num, int denom) { return (float) num / denom; } public static int floor(float f) { return (f >= 0 ? (int) f : (int) f - 1); } public static int toInt(float f) { int i = Float.floatToRawIntBits(f); return i ^ (i >> 16); } public static int round(float f) { return (f >= 0) ? (int) (f + (float) 0.5) : (int) (f - (float) 0.5); } public static float lerp(float a, float b, float alpha) { return a + alpha * (b - a); } public static float interpHermite(float t) { return t * t * (3 - 2 * t); } public static float interpQuintic(float t) { return t * t * t * (t * (t * 6 - 15) + 10); } public static float curve(float t, float steepness) { return curve(t, 0.5F, steepness); } public static float curve(float t, float mid, float steepness) { return 1F / (1F + NoiseUtil.exp(-steepness * (t - mid))); } public static float cubicLerp(float a, float b, float c, float d, float t) { float p = (d - c) - (a - b); return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b; } public static float exp(float x) { x = 1F + x / 256F; x *= x; x *= x; x *= x; x *= x; x *= x; x *= x; x *= x; x *= x; return x; } public static int hash(int x, int y) { int hash = x; hash ^= Y_PRIME * y; hash = hash * hash * hash * 60493; hash = (hash >> 13) ^ hash; return hash; } public static int hash2D(int seed, int x, int y) { int hash = seed; hash ^= X_PRIME * x; hash ^= Y_PRIME * y; hash = hash * hash * hash * 60493; hash = (hash >> 13) ^ hash; return hash; } public static float valCoord2D(int seed, int x, int y) { int n = seed; n ^= X_PRIME * x; n ^= Y_PRIME * y; // (n * n * n * 60493) / 2147483648.0F; return (n * n * n * 60493) / 2147483648.0F; } public static Vec2f coord2D(int seed, int x, int y) { int hash = seed; hash ^= X_PRIME * x; hash ^= Y_PRIME * y; hash = hash * hash * hash * 60493; hash = (hash >> 13) ^ hash; return GRAD_2D[hash & 7]; } public static Vec2f coord2D_24(int seed, int x, int y) { int hash = seed; hash ^= X_PRIME * x; hash ^= Y_PRIME * y; hash = hash * hash * hash * 60493; hash = (hash >> 13) ^ hash; // Fairly selects 24 gradients if you repeat every third one. int selector24 = (int)((hash & 0x3FFFFF) * 1.3333333333333333f) & 31; return GRAD_2D_24[selector24]; } public static float gradCoord2D(int seed, int x, int y, float xd, float yd) { Vec2f g = coord2D(seed, x, y); return xd * g.x + yd * g.y; } public static float gradCoord2D_24(int seed, int x, int y, float xd, float yd) { Vec2f g = coord2D_24(seed, x, y); return xd * g.x + yd * g.y; } public static float pow(float value, float power) { return (float) FastMath.pow(value, power); } public static float sin(float r) { int index = (int) (r * radToIndex) & SIN_MASK; return SIN[index]; } public static float cos(float r) { return sin(r + 1.5708F); } public static long seed(int x, int z) { return (long) x & 4294967295L | ((long) z & 4294967295L) << 32; } static { SIN_BITS = 12; SIN_MASK = ~(-1 << SIN_BITS); SIN_COUNT = SIN_MASK + 1; radFull = (float) (Math.PI * 2.0); degFull = (float) (360.0); radToIndex = SIN_COUNT / radFull; degToIndex = SIN_COUNT / degFull; SIN = new float[SIN_COUNT]; for (int i = 0; i < SIN_COUNT; i++) { SIN[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull); } // Four cardinal directions (credits: Nate) for (int i = 0; i < 360; i += 90) { SIN[(int) (i * degToIndex) & SIN_MASK] = (float) Math.sin(i * Math.PI / 180.0); } } } <file_sep>/* * * MIT License * * Copyright (c) 2020 TerraForged * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.dags.noise.selector; import me.dags.noise.Module; import me.dags.noise.func.Interpolation; import me.dags.noise.util.NoiseUtil; /** * @Author <<EMAIL>> */ public class MultiBlend extends Selector { private final Node[] nodes; private final int maxIndex; private final float blend; private final float blendRange; public MultiBlend(float blend, Interpolation interpolation, Module control, Module... sources) { super(control, sources, interpolation); float spacing = 1F / (sources.length); float radius = spacing / 2F; float blendRange = radius * blend; float cellRadius = (radius - blendRange) / 2; this.blend = blend; this.nodes = new Node[sources.length]; this.maxIndex = sources.length - 1; this.blendRange = blendRange; for (int i = 0; i < sources.length; i++) { float pos = i * spacing + radius; float min = i == 0 ? 0 : pos - cellRadius; float max = i == maxIndex ? 1 : pos + cellRadius; nodes[i] = new Node(sources[i], min, max); } } @Override public float selectValue(float x, float y, float selector) { int index = NoiseUtil.round(selector * maxIndex); Node min = nodes[index]; Node max = min; if (blendRange == 0) { return min.source.getValue(x, y); } if (selector > min.max) { max = nodes[index + 1]; } else if (selector < min.min) { min = nodes[index - 1]; } else { return min.source.getValue(x ,y); } float alpha = (selector - min.max) / blendRange; alpha = NoiseUtil.clamp(alpha, 0, 1); return blendValues(min.source.getValue(x, y), max.source.getValue(x, y), alpha); } private static class Node { private final Module source; private final float min; private final float max; private Node(Module source, float min, float max) { this.source = source; this.min = Math.max(0, min); this.max = Math.min(1, max); } @Override public String toString() { return "Slot{" + "min=" + min + ", max=" + max + '}'; } } } <file_sep>/* * * MIT License * * Copyright (c) 2020 TerraForged * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.dags.noise.domain; import me.dags.noise.Module; import me.dags.noise.util.NoiseUtil; public class DirectionWarp implements Domain { private final Module direction; private final Module strength; private float x = Float.MAX_VALUE; private float y = Float.MAX_VALUE; private float ox = 0; private float oy = 0; public DirectionWarp(Module direction, Module strength) { this.direction = direction; this.strength = strength; } @Override public float getOffsetX(float x, float y) { return update(x, y).ox; } @Override public float getOffsetY(float x, float y) { return update(x, y).oy; } private DirectionWarp update(float x, float y) { if (this.x != x || this.y != y) { this.x = x; this.y = y; float angle = direction.getValue(x, y) * 2 * NoiseUtil.PI2; ox = NoiseUtil.sin(angle) * strength.getValue(x, y); oy = NoiseUtil.cos(angle) * strength.getValue(x, y); } return this; } } <file_sep># Noise2D A modular noise library borrowing design from flow-noise (libnoise by extension) and algorithms from FastNoise_Java. #### Refs: https://github.com/flow/noise https://github.com/Auburns/FastNoise_Java
06e6259d3e56e348334d55bee1c3567fc898f383
[ "Markdown", "Java" ]
6
Java
KdotJPG/Noise2D
bcb25cadcb5050101c97be057699691623b02e8e
a2d15fc071d24ad9da2b19f60f586574e4f274b9
refs/heads/master
<file_sep>require 'rubygems' require 'bundler' Bundler.require set :database, {adapter: "sqlite3", database: "comments.sqlite3"} class Comment < ActiveRecord::Base validates_presence_of :name validates_presence_of :text end get '/' do @title = "BBS" @comment = Comment.new @comments = Comment.all erb :index end post '/creates' do @comments = Comment.all name = params[:name] text = params[:text] @comment = Comment.new({name: name, text: text}) if @comment.save { redirect '/' } else erb :index end end delete '/destroy' do @comment = Comment.find(params[:id]) @comment.destroy redirect '/' end
bf0047e81715910d0238c3108cbc185d648a4c3a
[ "Ruby" ]
1
Ruby
kakitaku00/SinatraApp
7002d9ab775faa9ff9dbaec4000eda91ac76865e
54a6e34a085d41bf0ce42b974a1499ef0b4f515c
refs/heads/master
<file_sep>package br.com.mezzavilla.gmail; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; public class ReadGmail { public static void read(String name, String password, String url) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver"); ChromeOptions options = new ChromeOptions(); //options.addArguments("--headless"); ChromeDriver driver = new ChromeDriver(options); WebDriverWait wait = new WebDriverWait(driver, 20); driver.get(url); Thread.sleep(1000); driver.findElement(By.id("identifierId")).sendKeys(name); Thread.sleep(1000); driver.findElement(By.cssSelector(".RveJvd")).click(); Thread.sleep(1000); WebElement pass = driver.findElement(By.xpath("//div[@id='password']//input[@type='password']")); Thread.sleep(1000); pass.sendKeys(<PASSWORD>); Thread.sleep(1000); driver.findElement(By.cssSelector(".RveJvd")).click(); Thread.sleep(7000); List<WebElement> rows = driver.findElements(By.xpath("//div[@class='Cp']//table/tbody/tr")); System.out.println("--------------------------------------------------------------------"); for (WebElement e : rows) { System.out.println("--------------------------------------------------------------------"); System.out.println("Enviado: " + e.getText()); } /* Abrir cada email individualmente */ for (WebElement e : rows) { System.out.println("********************************************************************"); System.out.println(" Abrindo cada email individualmente "); System.out.println("********************************************************************"); System.out.println("--------------------------------------------------------------------"); System.out.println("Enviado: " + e.getText()); e.findElement(By.xpath(".//div[@class='yW']/*")).click(); Thread.sleep(3000); System.out.println(e.findElement(By.xpath("//div[2]/div/a/span")).getText()); driver.navigate().back(); Thread.sleep(1000); } driver.quit(); } } <file_sep>package br.com.mezzavilla.gmail; public class Main { public static void main(String[] args) throws InterruptedException { /* Dados */ String name = "<EMAIL>"; String password = "<PASSWORD>"; String url = "https://www.gmail.com"; ReadGmail.read(name, password, url); } } <file_sep>let partidos = { "PMDB": {"cor_forte": "ff6801", "cor_fraca": "ffad71", "cor_media": "f3954f"}, "PT": {"cor_forte": "e02128", "cor_fraca": "f6898c", "cor_media": "dd6364"}, "PSB": {"cor_forte": "ffa90e", "cor_fraca": "ffd89d", "cor_media": "efbf60"}, "PSDB": {"cor_forte": "005c97", "cor_fraca": "87a8c7", "cor_media": "2a79be"}, "DEM": {"cor_forte": "007f94", "cor_fraca": "83b3c1", "cor_media": "40aab4"}, "PTB": {"cor_forte": "02a0e1", "cor_fraca": "88c6ed", "cor_media": "5fb7e7"}, "PDT": {"cor_forte": "9a8276", "cor_fraca": "c5b4ad", "cor_media": "a59997"}, "PP": {"cor_forte": "c6ba6e", "cor_fraca": "ddd6a8", "cor_media": "d8ca78"}, "PPS": {"cor_forte": "8b71b0", "cor_fraca": "bbabd0", "cor_media": "a997c8"}, "PV": {"cor_forte": "69962d", "cor_fraca": "a8c086", "cor_media": "9ab75b"}, "PR": {"cor_forte": "d4a055", "cor_fraca": "e6c69d", "cor_media": "dfb384"}, "PCdoB": {"cor_forte": "af455b", "cor_fraca": "d492a0", "cor_media": "cd667f"}, "PSC": {"cor_forte": "5b8194", "cor_fraca": "d1dae1", "cor_media": "95b1c1"}, "PRB": {"cor_forte": "82a884", "cor_fraca": "c0d9c2", "cor_media": "a7c8a9"}, "PSOL": {"cor_forte": "ffe025", "cor_fraca": "fff395", "cor_media": "f9e86f"}, "PSTU": {"cor_forte": "f67a7a", "cor_fraca": "ffc6c5", "cor_media": "f4a9aa"}, "PTC": {"cor_forte": "dcd4ad", "cor_fraca": "ebe7ce", "cor_media": "dddace"}, "PMN": {"cor_forte": "00e9e5", "cor_fraca": "a6f6f5", "cor_media": "90d0da"}, "PRP": {"cor_forte": "d0ff01", "cor_fraca": "e9ff83", "cor_media": "d7d463"}, "PTdoB": {"cor_forte": "730b00", "cor_fraca": "b27266", "cor_media": "995348"}, "PCB": {"cor_forte": "ae492b", "cor_fraca": "dba599", "cor_media": "d07361"}, "PRTB": {"cor_forte": "b583e6", "cor_fraca": "d3b4f0", "cor_media": "bc9fc9"}, "PHS": {"cor_forte": "94ae91", "cor_fraca": "c9d7c8", "cor_media": "b6c6b0"}, "PSDC": {"cor_forte": "19541", "cor_fraca": "52c08f", "cor_media": "5ca57f"}, "PCO": {"cor_forte": "505050", "cor_fraca": "878787", "cor_media": "707070"}, "PTN": {"cor_forte": "7a376d", "cor_fraca": "b38aaa", "cor_media": "936a90"}, "PSL": {"cor_forte": "dfda86", "cor_fraca": "f2efbc", "cor_media": "e1dea8"}, "PSD": {"cor_forte": "3a5dff", "cor_fraca": "97a8ff", "cor_media": "7e8cc5"}, "PPL": {"cor_forte": "b6b6b6", "cor_fraca": "d3d3d3", "cor_media": "c2c4c4"}, "PEN": {"cor_forte": "9d7400", "cor_fraca": "c5ac6c", "cor_media": "b79d68"}, "PROS": {"cor_forte": "e9518c", "cor_fraca": "f698bc", "cor_media": "db75a6"}, "SD": {"cor_forte": "ae4f87", "cor_fraca": "d296b8", "cor_media": "ba77a2"} };<file_sep>package br.com.mezzavilla.files; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFSlide; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ReadPptFile { public static void read(String a, String path) throws IOException { /* Nome do arquivo */ System.out.println(""); System.out.println("************************************************************************************************************************************************"); System.out.println("************************************************************************************************************************************************"); System.out.println("Nome do arquivo: " + a.substring(path.length() + 1)); System.out.println(""); File myFile = new File(a); FileInputStream fis = new FileInputStream(myFile); XMLSlideShow ppt = new XMLSlideShow(fis); fis.close(); for (XSLFSlide s : ppt.getSlides()) { if (s.getTitle() != null) { System.out.println("1: " + s.getTitle()); } } } }
ef9359b82225e8bec2223eb7e9b884ff042854f4
[ "JavaScript", "Java" ]
4
Java
dmezzavilla/codex
7881f7b9ae2f9f763c16390451d0f9241248fe9d
185e8a4e8a182bb59e29e1a00edb5586a769988d
refs/heads/master
<file_sep>/*var myName = 'Aleksey', role = 'Web Developer'; var awesomeThoughts = "I am Aleksey and I am AWESOME!"; var funThoughts = awesomeThoughts.replace('AWESOME', 'FUN'); console.log(funThoughts); var formattedName = HTMLheaderName.replace('%data%', myName); var formattedRole = HTMLheaderRole.replace('%data%', role); $('#header').prepend(formattedRole); $('#header').prepend(formattedName); */ // var skills = ["css", "html", "javascript", "programming", "CMS"] var bio = { "name" : "Aleksey", "role" : "Web Developer", "contacts" : { "mobile" : "+380963974481", "email" : "<EMAIL>", "location" : "Dnepr" }, "pic" : "/images/197x148.gif", "welcomeMessage" : "Welcome to my test file", "skills" : [ "css", "html", "javascript", "programming", "CMS" ] }; // Работа с объектами var work = { "jobs" : [ { "position" : "freelance", "employer" : "proverstka", "years" : 10, "title" : "general work" }, { "position" : "developer", "employer" : "promarmatura", "years" : 4, "title" : "secondary work" } ] }; var projects = { "projects" : [ { "title" : "Project1", "dates" : "2010", "description" : "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium." } ] } var education = { "school" : [ { "name" : "College", "city" : "Dnepr", "majors" : ["CS"], "minors" : "rea", "years" : "1996-2000" }, { "name" : "Academy", "city" : "Dnepr", "majors" : ["HT"], "minors" : "metal", "years" : "2000-2008" } ], "onlineCourses" : [ { "title" : "JS Courses", "school" : "Udacity", "dates" : 2016 } ] } // $('#main').append(work.jobs[0].position).append(education.school[0].name); if (bio.skills.length > 0){ $('#header').append(HTMLskillsStart); // console.log(HTMLskillsStart); var formattedSkill = HTMLskills.replace("%data%", bio.skills[0]); $('#skills').append(formattedSkill); var formattedSkill = HTMLskills.replace("%data%", bio.skills[1]); $('#skills').append(formattedSkill); var formattedSkill = HTMLskills.replace("%data%", bio.skills[2]); $('#skills').append(formattedSkill); var formattedSkill = HTMLskills.replace("%data%", bio.skills[3]); $('#skills').append(formattedSkill); } // jobs for (job in work.jobs){ // HTMLworkStart.append(key); $('#workExperience').append(HTMLworkStart); var formattedEmployer = HTMLworkEmployer.replace('%data%', work.jobs[job].employer); var formattedTitle = HTMLworkTitle.replace('%data%', work.jobs[job].title); var formattedEmployerTitle = formattedEmployer + formattedTitle; $('.work-entry:last').append(formattedEmployerTitle); }
79edd6645c3b5ac3fcc54754aabf418c5b38d2db
[ "JavaScript" ]
1
JavaScript
x404/frontend-nanodegree-resume
afbad0e72bfa8853c207e25789b2b1d3a7e38f5b
286c7495d9fac4133bfdd34af81ed2d16a7bff56
refs/heads/main
<file_sep>java -Xmx768M -cp .:./ToolManCoinAirDropServer-1.0.jar tmc.server.AirDropServer <file_sep>package tmc.server; import java.net.*; import java.util.*; import java.lang.ClassNotFoundException; import java.io.*; import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger; import tmc.server.ServerGlobal; /** * TCP/IP Client Server Framework, * Using for writing your own server processor. * @author <NAME> */ abstract public class ServerProcessor implements Cloneable { private static final Logger _log = Logger.getLogger(ServerProcessor.class.getName()); private static int iSeed = 0; protected int iOID = -1; protected static List pool = Collections.synchronizedList(new LinkedList()); protected static HashMap<String ,ClientInfo> AllClientInfo = new HashMap<String ,ClientInfo>(); protected Socket connection = null; protected OutputStreamWriter out = null; protected InputStreamReader in = null; protected ClientInfo aClientInfo = null; public static String sInputEncode = null; public static String sOutputEncode = null; public static final String SEND_CLOSE = "server_close"; public static final String SEND_TO = "server_to"; public static final String SEND_TO_CLOSE = "server_to_close"; public static final String SEND_BACK = "server_back"; public static final String SEND_ALL = "server_all"; public static final String SEND_BACK_CLOSE = "server_back_close"; public static final String SEND_ALL_CLOSE = "server_all_close"; /** * default input encode and output encode is UTF-8 */ public ServerProcessor(){ this(ServerGlobal.FILE_ENCODE,ServerGlobal.FILE_ENCODE ); } public ClientInfo getClientInfo() { return this.aClientInfo; } /** * customize input and output encode * @param sInputEncode input encode * @param sOutputEncode output encode */ public ServerProcessor(String sInputEncode,String sOutputEncode){ this.sInputEncode = sInputEncode; this.sOutputEncode = sOutputEncode; } public Socket getConnection(){ return connection; } public void setConnection(Socket aConnection){ connection = aConnection; } /** * initial object id to this object */ synchronized public void setOID(){ iSeed ++; iOID = iSeed; } /** * return object id */ public int getOID(){ return iOID; } /** * this class implemnet clone method, and override protected method "clone" to public * it will call method "init" first. */ public Object clone() throws CloneNotSupportedException{ Object obj = super.clone(); _log.info("new Clone"); ((ServerProcessor)obj).init(); ((ServerProcessor)obj).setOID(); return obj; }; /** * @return HashMap * <pre> * Key=Cmd, vales will be SEND_ALL,SEND_BACK.... * Key=Data, data * [optional] if key=SEND_TO, one key="OID" must be HashMap , value will be object id * </pre> */ public abstract HashMap parseCmd(int iCmd); /** * initial this object data , called when clone be involke */ public abstract void init(); /** * close all resource in object */ public void destory(){ // try{ deleteConnection(); //connection.close(); connection = null; out = null; in = null; _log.info("Object ServerProcessor destory"); // }catch(IOException ex){ // _log.warning("socket connection close fail"); // } } /** * add socket connect to pool */ public boolean addConnection(Socket connection){ synchronized (pool) { pool.add(pool.size(), this); setConnection(connection); pool.notifyAll(); _log.info("Get connection,pool size="+pool.size()); return true; } } /** * this socket connection in this object */ public boolean deleteConnection(){ synchronized(pool){ pool.remove(this); pool.notifyAll(); _log.info("delete connection,pool size="+pool.size()); } try{ connection.close(); }catch(Exception ex){ ex.printStackTrace(); _log.warning("socket sonnection error"); } return true; } /** * run. */ public void run(){ HashMap aReturnHash = null; String sCmd = null; String sData = null; Socket aTmpConn = null; OutputStreamWriter aTmpOSW = null; if(true){ try { if( connection.getKeepAlive()==false) { System.out.println("Socket keep alive = false , try to set enable"); connection.setKeepAlive(true); connection.setTcpNoDelay(true); // connection.setSoLinger(true, 1); // connection.setSoTimeout( Integer.parseInt(ServerGlobal.PERIOD_TIME.trim()) + 30000); } out = new OutputStreamWriter(connection.getOutputStream(),sOutputEncode); in = new InputStreamReader(connection.getInputStream(),sInputEncode); int c; //System.out.println("output encode = " + out.getEncoding() ); //System.out.println("input encode = " + in.getEncoding() ); while (true) { c = in.read(); if(c==-1){ _log.info("Connection has broken"); if( aReturnHash!=null) aReturnHash.clear(); destory(); return; } aReturnHash = parseCmd(c); if( aReturnHash!=null ){ sCmd = (String) aReturnHash.get("Cmd"); sData = (String) aReturnHash.get("Data"); if( sCmd.equals( SEND_BACK ) ){ out.write(sData); out.flush(); }else if( sCmd.equals( SEND_BACK_CLOSE ) ){ out.write(sData); out.flush(); if( aReturnHash!=null) aReturnHash.clear(); destory(); return; }else if( sCmd.equals( SEND_ALL ) ){ for(int i=0;i<pool.size();i++){ aTmpConn = ((ServerProcessor)pool.get(i)).getConnection(); aTmpOSW = new OutputStreamWriter(aTmpConn.getOutputStream(),sOutputEncode); aTmpOSW.write(sData); aTmpOSW.flush(); } }else if( sCmd.equals( SEND_ALL_CLOSE ) ){ for(int i=0;i<pool.size();i++){ aTmpConn = ((ServerProcessor)pool.get(i)).getConnection(); aTmpOSW = new OutputStreamWriter(aTmpConn.getOutputStream(),sOutputEncode); aTmpOSW.write(sData); aTmpOSW.flush(); } if( aReturnHash!=null) aReturnHash.clear(); destory(); return; }else if( sCmd.equals( SEND_TO ) ){ int iTmpOID = Integer.parseInt( (String)aReturnHash.get("OID") ); for(int i=0;i<pool.size();i++){ if( iTmpOID == ((ServerProcessor)pool.get(i)).getOID() ){ aTmpConn = ((ServerProcessor)pool.get(i)).getConnection(); aTmpOSW = new OutputStreamWriter(aTmpConn.getOutputStream(),sOutputEncode); aTmpOSW.write(sData); aTmpOSW.flush(); break; } } }else if( sCmd.equals( SEND_TO_CLOSE ) ){ int iTmpOID = Integer.parseInt( (String)aReturnHash.get("OID") ); for(int i=0;i<pool.size();i++){ if( iTmpOID == ((ServerProcessor)pool.get(i)).getOID() ){ aTmpConn = ((ServerProcessor)pool.get(i)).getConnection(); aTmpOSW = new OutputStreamWriter(aTmpConn.getOutputStream(),sOutputEncode); aTmpOSW.write(sData); aTmpOSW.flush(); break; } } if( aReturnHash!=null) aReturnHash.clear(); destory(); return; }else if( sCmd.equals( SEND_CLOSE ) ){ out.flush(); if( aReturnHash!=null) aReturnHash.clear(); destory(); return; } } } } catch (Exception e) { destory(); e.printStackTrace(); _log.warning("connection broken , "+e.getMessage()); } }// end of while } }<file_sep>### How To Compile 1. j2se version 8 or above 2. gradle 2.7 or above gradle jar => generate jar file ### StartUp 1. Modify server.properties "PROP_SENDER_WALLET_PASSPHRASE" your pass phrase "PROP_GAIN_PERIOD" gain 1 dollar period "PROP_TRANSFER_COIN_NUMBER" minimum number transfer to client wallet 2. Execute java -Xmx768M -cp .;./ToolManCoinAirDropServer-1.0b1.jar tmc.server.AirDropServer #### PS 1. client unpaid coin will gone and can not roll back after server stop
4ae925b6d4e50bab6f20cfcaa0ef2904e4b91b82
[ "Markdown", "Java", "Shell" ]
3
Shell
WilliamFromTW/ToolManCoinAirDropServer
8b74a80a7c3ab95a643f2c5f6adc5577fecefae9
aba9cb1bb29742675d884bcb4d63a47d2496c4bb
refs/heads/master
<repo_name>gerdablum/shared-clipboard<file_sep>/app/app/src/main/java/de/alina/clipboard/app/service/CancelServiceReceiver.kt package de.alina.clipboard.app.service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import de.alina.clipboard.app.manager.BackgroundServiceManager class CancelServiceReceiver(): BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val serviceManager = BackgroundServiceManager() if (context == null) { Log.e("CancelServiceReceiver", "Failed to stop foreground service") } else { serviceManager.stopCopyListenService(context) } } }<file_sep>/server/src/main/java/de/alina/clipboard/model/UserFileData.java package de.alina.clipboard.model; import java.util.UUID; public class UserFileData extends User { public String base64; public String mimeType; public String originalFileName; public UserFileData(UUID id) { super(id); } }<file_sep>/app/app/src/test/java/de/alina/clipboard/app/TestAppController.kt package de.alina.clipboard.app import android.app.Activity import android.content.Intent import android.graphics.Bitmap import de.alina.clipboard.app.client.* import de.alina.clipboard.app.controller.AppController import de.alina.clipboard.app.manager.* import de.alina.clipboard.app.model.User import de.alina.clipboard.app.view.BaseView import org.junit.Test import org.mockito.Mockito.* import java.util.* class TestAppController { private val ackController = mock(AcknowledgeController::class.java) private val logoutController = mock(LogoutController::class.java) private val connectController = mock(CheckConnectionController::class.java) private val uploadController = mock(UploadDataController::class.java) private val sendDataController = mock(SendDataController::class.java) private val authManager = mock(AuthManager::class.java) private val serviceManager = mock(BackgroundServiceManager::class.java) private val qrManager = mock(QRManager::class.java) private val notifManager = mock(ClipboardNotificationManager::class.java) private val fileManager = mock(FileManager::class.java) private val context = mock(Activity::class.java) private val baseView = mock(BaseView::class.java) private val controller = spy(AppController(context, baseView, ackController, logoutController, connectController, uploadController, sendDataController, authManager, serviceManager, qrManager, notifManager, fileManager)) @Test fun testOnResume_VerifyIsConnected() { val user = User(UUID.randomUUID()) doReturn(user).`when`(authManager).getUserKey(context) doReturn(true).`when`(controller).hasInternetConnection() controller.onResume() verify(connectController).isConnected(user.id!!) } @Test fun testOnResume_VerifyShowNoInternetConnection() { val user = User(UUID.randomUUID()) doReturn(user).`when`(authManager).getUserKey(context) doReturn(false).`when`(controller).hasInternetConnection() controller.onResume() verify(baseView).showNoInternetConnection() } @Test fun testOnResume_VerifyShowLogoutSuccessful() { val user = null doReturn(user).`when`(authManager).getUserKey(context) doReturn(true).`when`(controller).hasInternetConnection() controller.onResume() verify(baseView).showLogoutSuccessful() } @Test fun testLogoutUser_VerifyLogout() { val user = User(UUID.randomUUID()) controller.user = user controller.logoutUser() verify(logoutController).logout(user.id!!) } @Test fun testProcessImage_VerifyAcknowledge() { val data = mock(Intent::class.java) val bitmap = mock(Bitmap::class.java) val id = UUID.randomUUID().toString() doReturn(bitmap).`when`(data).extras?.get("data") doAnswer { val callback = it.arguments[1] as QRInterface callback.onQRScanFinished(id) }.`when`(qrManager.scanQRCode(bitmap, any(QRInterface::class.java))) controller.processImage(data) verify(baseView).showLoginFailure() } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/GetDataController.kt package de.alina.clipboard.app.client import android.os.Bundle import android.util.Log import de.alina.clipboard.app.client.APIManagerCallback.Companion.CALLBACK_KEY_USER import de.alina.clipboard.app.model.User import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* class GetDataController: BaseApiController() { fun getData(id: UUID, callback: Callback<User?>) { val call = apiJSON.getData("clipboard.id=" + id.toString()) call.enqueue(callback) Log.d(this.toString(), "Requesting " + call.request().url()) } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/manager/ClipboardNotificationManager.kt package de.alina.clipboard.app.manager import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import androidx.core.app.NotificationCompat import androidx.core.app.TaskStackBuilder import de.alina.clipboard.app.R import de.alina.clipboard.app.view.MainActivity import java.util.* open class ClipboardNotificationManager { fun createNotificationChannel(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create the NotificationChannel val name = context.getString(R.string.channel_name) val descriptionText = context.getString(R.string.channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val mChannel = NotificationChannel(MainActivity.CHANNEL_ID, name, importance) mChannel.description = descriptionText // Register the channel with the system; you can't change the importance // or other notification behaviors after this val notificationManager = context.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(mChannel) } } fun buildNotification(id: UUID, context: Context, cancelIntent: Intent): Notification { cancelIntent.putExtra( DISCONNECT_REQUESTED_KEY, true) val pendingIntent = TaskStackBuilder.create(context).run { // Add the intent, which inflates the back stack addNextIntentWithParentStack(cancelIntent) // Get the PendingIntent containing the entire back stack getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) } return NotificationCompat.Builder(context, MainActivity.CHANNEL_ID) .setSmallIcon(R.drawable.ic_content_copy_black_24dp) .setContentTitle("SharedClipboard") .setContentText("Connected to computer") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .addAction(R.drawable.ic_content_copy_black_24dp, context.getString(R.string.cancel_service), pendingIntent) .build() } companion object { const val DISCONNECT_REQUESTED_KEY = "de.alina.clipboard.app.disconnectRequested" } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/controller/AppController.kt package de.alina.clipboard.app.controller import android.app.Activity import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.net.ConnectivityManager import android.net.NetworkInfo import android.net.Uri import android.os.Bundle import android.os.Parcelable import android.provider.MediaStore import android.service.autofill.UserData import android.util.Log import de.alina.clipboard.app.client.* import de.alina.clipboard.app.manager.* import de.alina.clipboard.app.model.User import de.alina.clipboard.app.model.UserFileData import de.alina.clipboard.app.view.BaseView import okhttp3.MediaType class AppController(private val context: Activity, private val view: BaseView, private val apiController: APIManager, private val authManager: AuthManager, private val serviceManager: BackgroundServiceManager, private val qrManager: QRManager, private val notifManager: ClipboardNotificationManager, private val fileManager: FileManager, private val serverManager: ServerAddressManager) : APIManagerCallback, LifecycleObserver { var user: User? = null var hasInternetConnection = true var textData: UserData? = null var fileDate: UserFileData? = null @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate() { notifManager.createNotificationChannel(context) apiController.subscribe(this) } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onResume() { if (!hasInternetConnection()) { view.showNoInternetConnection() } val user = authManager.getActiveUser(context) // user is already logged out if (user == null) { view.showLogoutSuccessful() } // user requested logout but it failed else if (authManager.logoutRequested(context)) { logoutUser() } // user is logged in successfully else { user.id?.let { apiController.isConnected(it) } view.showLoggedInSuccessful() } } fun logoutUser() { val user = authManager.getActiveUser(context) authManager.logoutUser(context) if (user != null) { user.id?.let { apiController.logout(it) } serviceManager.stopCopyListenService(context) view.showLogoutSuccessful() } } fun uploadBytes(fileUri: Uri, mimeType: MediaType) { val user = authManager.getActiveUser(context) val inputStream = context.contentResolver.openInputStream(fileUri) val byteArray = fileManager.getBytes(inputStream) val filename = fileManager.getFilename(context, fileUri) user?.id?.let { apiController.sendFileData(it, byteArray, mimeType, filename ?: "unknown-file") } } fun hasInternetConnection(): Boolean { val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork: NetworkInfo? = cm.activeNetworkInfo return activeNetwork?.isConnected ?: false } fun captureImage() { Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent -> takePictureIntent.resolveActivity(context.packageManager)?.also { context.startActivityForResult(takePictureIntent, CAPTURE_PICTURE_REQUEST) } } } fun processImage(data: Intent?) { data?.let { val imageBitmap = data.extras?.get("data") as Bitmap qrManager.scanQRCode(imageBitmap, (object : QRInterface { override fun onQRScanFinished(id: String?) { val uuid = authManager.isUUIDValid(id); if (uuid != null) { apiController.acknowledge(uuid) } else { view.showLoginFailure() } } })) } } override fun onSuccess(data: Bundle, type: APIManagerCallback.CallType) { when (type) { APIManagerCallback.CallType.ACKNOWLEDGE -> onAckSuccessful(data) APIManagerCallback.CallType.SEND_DATA -> onSendDataSuccessful() APIManagerCallback.CallType.SEND_FILE_DATA -> view.showSendDataSuccessful() APIManagerCallback.CallType.GET_DATA -> view.showGetDataSuccessful() APIManagerCallback.CallType.LOGOUT -> onLogoutSuccessful() APIManagerCallback.CallType.CONNECTION -> { authManager.getActiveUser(context)?.let { serviceManager.startCopyListenService(context, it) } } } } private fun onLogoutSuccessful() { authManager.deleteUserData(context) Log.d(AppController::class.java.name, "User logged out successful") } private fun onSendDataSuccessful() { Log.d(AppController::class.java.name, "copied data from background") view.showSendDataSuccessful() } private fun onAckSuccessful(data: Bundle) { data.getString(APIManagerCallback.CALLBACK_ID_KEY)?.let { authManager.storeUser(it, context) serviceManager.startCopyListenService(context, authManager.getActiveUser(context)) view.showLoggedInSuccessful() } } override fun onFailure(data: Bundle, type: APIManagerCallback.CallType, t: Throwable?) { t?.printStackTrace() when (type) { APIManagerCallback.CallType.ACKNOWLEDGE -> view.showLoginFailure() APIManagerCallback.CallType.SEND_DATA -> { Log.d(AppController::class.java.name, "failed to copy data from background") view.showSendDataFailure() } APIManagerCallback.CallType.SEND_FILE_DATA -> view.showSendDataFailure() APIManagerCallback.CallType.GET_DATA -> view.showGetDataFailure() APIManagerCallback.CallType.LOGOUT -> view.showLogoutFailure() APIManagerCallback.CallType.CONNECTION -> { authManager.getActiveUser(context)?.let { logoutUser() } view.showLogoutSuccessful() } } } fun handleShareImageEvent(intent: Intent) { if (intent.type == null) { return } (intent.getParcelableExtra<Parcelable>(Intent.EXTRA_STREAM) as? Uri)?.let { uploadBytes(it, MediaType.parse(intent.type)!!) Log.d("MainActivity", "image shared") } } fun getCurrentServerAddress(): String { val url = serverManager.getAddress(context) if (url != null && url != ClipboardServerAPI.BASE_URL && Regex("http://.*").matches(url)) { ClipboardServerAPI.BASE_URL = url apiController.reload() } return ClipboardServerAPI.BASE_URL } fun setCurrentServerAddress(url: String) { if (!Regex("http://.*").matches(url)) { view.serverUrlIncorrect() return } ClipboardServerAPI.BASE_URL = url apiController.reload() serverManager.saveAddress(url, context) } companion object { const val CAPTURE_PICTURE_REQUEST = 1 } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/manager/QRInterface.kt package de.alina.clipboard.app.manager interface QRInterface { fun onQRScanFinished(id: String?) = Unit }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/model/User.kt package de.alina.clipboard.app.model import java.io.Serializable import java.util.* open class User( var id: UUID?): Serializable { var stringData: String? = null var fileUrl: String? = null var type: DataType? = null companion object { const val USER_KEY = "de.alina.clipboard.app.userKey" } }<file_sep>/README.md # Shared Clipboard Share your clipboard between your Android smartphone and any computer. ## Project structure This project consists of two applications: 1. **server** web client and backend 2. **app** android app as smartphone client ## Requirements: - java11 - redis 3.2+ (key value in memory database) - Android SDK API 29 ## Setup 1. start redis via command line `redis-server` 2. in server project folder start the spring boot application by typing `./gradlew bootRun`into the command line 3. Deploy the app to your smarthpone via Android Studio ## How it works The server provides a web interface with a QR code. With the smartphone app you can scan the QR code to connect with your computer (or any device from which you are accessing the website). Once connected you can copy text in your smartpho and the clipboard is displayed in the web interface. The website will copy it to your computers clipboard automatically. 1. open `localhost:8090` 2. open smartphone app 3. in the app click on the capture button (right lower corner) 4. Take a picture of the QR code and click ok 5. The website redirects you to your clipboard page. You can now start copying on your smartphone 6. Once you copied a text, you can see it on the webpage inside the box. 7. To copy images, use the share function on your smartphone. The image will appear for download on the webpage. <file_sep>/server/build.gradle buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:2.2.5.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' bootJar { baseName = 'gs-spring-boot' version = '0.1.0' } repositories { mavenCentral() maven { url "https://jitpack.io" } } sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation 'com.github.kenglxn.QRGen:javase:2.5.0' implementation group: 'org.springframework.data', name: 'spring-data-redis', version: '2.2.5.RELEASE' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.2.5.RELEASE' implementation group: 'redis.clients', name: 'jedis', version: '3.2.0' implementation group: 'org.springframework.boot', name: 'spring-boot-starter-websocket', version: '2.2.5.RELEASE' implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2' implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2' implementation("org.webjars:webjars-locator-core") implementation("org.webjars:sockjs-client:1.0.2") implementation("org.webjars:stomp-websocket:2.3.3") implementation("org.webjars:bootstrap:4.4.1") implementation( 'com.google.code.gson:gson:2.8.6') testImplementation("junit:junit:4.12") testImplementation('org.springframework.boot:spring-boot-starter-test') testImplementation('org.junit.jupiter:junit-jupiter:5.4.0') implementation 'org.testng:testng:7.1.0' implementation 'junit:junit:4.12' implementation 'junit:junit:4.12' } <file_sep>/server/src/main/resources/application.properties server.port=8080 spring.servlet.multipart.max-file-size=128MB<file_sep>/app/app/src/main/java/de/alina/clipboard/app/manager/AuthManager.kt package de.alina.clipboard.app.manager import android.content.Context import de.alina.clipboard.app.R import de.alina.clipboard.app.client.APIManager import de.alina.clipboard.app.model.User import java.lang.Exception import java.util.* open class AuthManager() { private var user: User? = null fun logoutUser(context: Context) { user = null val editor = context.getSharedPreferences( context.getString(R.string.preference_file_key), Context.MODE_PRIVATE).edit() editor.putBoolean(context.getString(R.string.user_auth_request_logout_key), true) editor.apply() } fun isUUIDValid(id: String?): UUID? { try { val uuid = UUID.fromString(id) return uuid } catch (e: Exception) { return null } } // user zurückgeben wenn logout requested??? fun getActiveUser(context: Context): User? { if (user != null) return user; val sharedPref = context.getSharedPreferences( context.getString(R.string.preference_file_key), Context.MODE_PRIVATE) val userID = sharedPref.getString(context.getString(R.string.user_auth_id_key), "") ?: "" if (userID != "") { user = User(UUID.fromString(userID)) return user } else { return null } } fun logoutRequested(context: Context): Boolean { val sharedPref = context.getSharedPreferences( context.getString(R.string.preference_file_key), Context.MODE_PRIVATE) return sharedPref.getBoolean(context.getString(R.string.user_auth_request_logout_key), false) } fun deleteUserData(context: Context) { val editor = context.getSharedPreferences( context.getString(R.string.preference_file_key), Context.MODE_PRIVATE).edit() editor.putString(context.getString(R.string.user_auth_id_key), "") editor.apply() } fun storeUser(id: String, context: Context) { val editor = context.getSharedPreferences( context.getString(R.string.preference_file_key), Context.MODE_PRIVATE).edit() editor.putString(context.getString(R.string.user_auth_id_key), id) editor.putBoolean(context.getString(R.string.user_auth_request_logout_key), false) editor.apply() user = User(UUID.fromString(id)) } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/view/BaseView.kt package de.alina.clipboard.app.view interface BaseView { fun showLoggedInSuccessful() fun showLogoutSuccessful() fun showLoginFailure() fun showLogoutFailure() fun showNoInternetConnection() fun showSendDataSuccessful() fun showSendDataFailure() fun showGetDataSuccessful() fun showGetDataFailure() fun showFailure() fun serverUrlIncorrect() }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/service/CopyEventService.kt package de.alina.clipboard.app.service import android.app.Service import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.os.Bundle import android.os.IBinder import android.util.Log import de.alina.clipboard.app.client.APIManager import de.alina.clipboard.app.client.APIManagerCallback import de.alina.clipboard.app.client.APIManagerImpl import de.alina.clipboard.app.client.SendDataController import de.alina.clipboard.app.manager.ClipboardNotificationManager import de.alina.clipboard.app.model.User.Companion.USER_KEY import de.alina.clipboard.app.view.MainActivity import java.util.* class CopyEventService: Service(), APIManagerCallback{ lateinit var notifManager: ClipboardNotificationManager override fun onBind(intent: Intent?): IBinder? { return null } override fun onCreate() { notifManager = ClipboardNotificationManager() isRunning = false super.onCreate() } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { val idString = intent.getStringExtra(USER_KEY) val id = UUID.fromString(idString) listenToCopyEvents(id) isRunning = true val cancelIntent = Intent(this, MainActivity::class.java) startForeground(FOREGROUND_SERVICE_ID, notifManager.buildNotification(id, this, cancelIntent)) Log.d("CopyEventService", "service created.") return Service.START_NOT_STICKY } private fun listenToCopyEvents(id: UUID) { val apiManager = APIManagerImpl() apiManager.subscribe(this) val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboard.addPrimaryClipChangedListener { clipboard.primaryClip?.let { val content = it.getItemAt(0) if (content.text != null) { apiManager.sendStringData(id, content.text.toString()) } } } } override fun onDestroy() { Log.d("CopyEventService", "service destroyed.") isRunning = false super.onDestroy() } override fun onTaskRemoved(rootIntent: Intent?) { Log.d("CopyEventService", "service removed.") super.onTaskRemoved(rootIntent) } override fun onSuccess(data: Bundle, type: APIManagerCallback.CallType) { Log.d("CopyEventService", "copied data from background") } override fun onFailure(data: Bundle, type: APIManagerCallback.CallType, t: Throwable?) { t?.printStackTrace() Log.d("CopyEventService", "failed to copy data from background") } companion object { const val FOREGROUND_SERVICE_ID = 42 var isRunning = false } }<file_sep>/server/src/main/resources/static/index.js var id = null; var hosturl = location.protocol + '//' + location.host; var socket = null; function loadIdAndQRCode() { $.ajax({ url: hosturl + '/get-id' }).then(function(data) { var url = hosturl + '/qr-image.png?id=' + data.id; var i = new Image(); i.src = url; i.alt = 'QR Code zum scannen'; $('#image-container').append(i); $('#text').append(data.id); id = data.id; connect(); }); } function lookupCookies() { //Only show the button when automatic clipboard copying failed. $('#button').hide(); var cookieid = Cookies.get('clipboard.id'); id = cookieid; if (cookieid === undefined) { window.location.href = hosturl + '/index.html' } else { showData(cookieid); connect(); } } function showData(cookieid) { $.ajax({ url: hosturl + '/get-data', //?id=' + cookieid, withCredentials: true, error: function(xhr, status) { window.location.href = hosturl } }).then(function(data) { // data is of type string if (data.type === 'STRING') { $('#content-container').html(data.stringData); var btn = $('#button'); btn.removeAttr('download'); btn.removeAttr('href'); btn.text('Copy to your clipboard'); //copyAndAskForPermission(data.stringData); // data is of type file } else if (data.type === 'FILE') { $('#content-container').text(''); displayFileData(data); } }); } function copyAndAskForPermission(text) { try { navigator.permissions.query({ name: 'clipboard-write' }).then(function(permissionStatus) { // Will be 'granted', 'denied' or 'prompt': console.log(permissionStatus.state); copy(permissionStatus.state, text); permissionStatus.onchange = copy(permissionStatus.state, text); }); } catch(err) { console.log("asking for permission failed"); fallbackCopy(); } } function copy(state, text) { if (state === 'granted') { navigator.clipboard.writeText(text).then(function () { console.log('copying successful'); }).catch(function (err){ console.log("copying failed "); fallbackCopy(); }); } else if (state === 'denied'){ fallbackCopy(); } } function fallbackCopy() { var btn = $('#button'); btn.show(); btn.click(function() { var $temp = $("<input>"); $("body").append($temp); $temp.val($('#content-container').text()).select(); document.execCommand("copy"); $temp.remove(); }); } function connect() { socket = new SockJS('/clipboard-websocket'); var stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { console.log('Connected: ' + frame); if (id === null) return; stompClient.subscribe('/topic/data-received/' + id, function (data) { console.log("subscription is called" + data); showData(id); }); stompClient.subscribe('/topic/acknowledge/' + id, function (data) { if(data.body == 'logout') { document.cookie = "clipboard.id= " + id + "; expires=Thu, 01 Jan 1970 00:00:01 GMT;"; window.location.href = hosturl; } else { console.log("acknowledge complete, redirecting to content page."); var now = new Date(); var inTenMinutes = new Date(now.getTime() + 30* 60000); document.cookie = "clipboard.id= " + id +"; expires=" + inTenMinutes.toUTCString(); window.location.href = hosturl + '/display-data.html'; } }) }); } function disconnect() { if (socket != null) { socket.close(); } } function logout() { $.ajax({ url: hosturl + '/logout', type: 'get', withCredentials: true }) } function displayFileData(data) { var mimeType = data.mimeType; var btn = $('#button'); btn.text('Click to download'); btn.show(); if (mimeType.includes('image')) { var image = new Image(); image.src = "data:" + mimeType + ";base64," + data.base64; image.alt = "Your clipboard content."; image.width = 100; $('#content-container').append(image); } else { //TODO: Escape filename in server!!!!! $('#content-container').html(data.originalFileName); } btn.attr('download', data.originalFileName); btn.attr('href', "data:" + mimeType + ";base64," + data.base64); }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/manager/ServerAddressManager.kt package de.alina.clipboard.app.manager import android.content.Context import de.alina.clipboard.app.R class ServerAddressManager { fun saveAddress(address: String, context: Context) { val editor = context.getSharedPreferences( context.getString(R.string.preference_file_key), Context.MODE_PRIVATE).edit() editor.putString(context.getString(R.string.server_url_key), address) editor.apply() } fun getAddress(context: Context): String? { val sharedPref = context.getSharedPreferences( context.getString(R.string.preference_file_key), Context.MODE_PRIVATE) return sharedPref.getString(context.getString(R.string.server_url_key), "") } companion object { } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/SendDataController.kt package de.alina.clipboard.app.client import android.os.Bundle import android.text.Html import android.util.Log import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* class SendDataController: BaseApiController(){ fun sendStringData(id: UUID, stringData: String, callback: Callback<String?>) { val call = apiJSON.sendData("clipboard.id=" + id.toString(), Html.escapeHtml(stringData)) call.enqueue(callback) Log.d(this.toString(), "Requesting " + call.request().url()) } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/BaseApiController.kt package de.alina.clipboard.app.client import com.google.gson.GsonBuilder import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory open class BaseApiController { private lateinit var retrofitString: Retrofit private lateinit var retrofitJson: Retrofit open val apiJSON: ClipboardServerAPI by lazy { retrofitJson.create(ClipboardServerAPI::class.java) } open val apiString: ClipboardServerAPI by lazy { retrofitString.create(ClipboardServerAPI::class.java) } init { retrofitString = Retrofit.Builder().baseUrl(ClipboardServerAPI.BASE_URL) .addConverterFactory(ScalarsConverterFactory.create()) .build() val gson = GsonBuilder().setLenient().create() retrofitJson = Retrofit.Builder().baseUrl(ClipboardServerAPI.BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .build() } }<file_sep>/server/src/main/java/de/alina/clipboard/exception/WebSocketException.java package de.alina.clipboard.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason="Acknowledge failed. Cannot reach client") public class WebSocketException extends RuntimeException { } <file_sep>/app/app/build.gradle apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'com.google.gms.google-services' android { compileSdkVersion 30 defaultConfig { applicationId "de.alina.clipboard.app" minSdkVersion 26 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" multiDexEnabled true } buildFeatures { viewBinding true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } debug { minifyEnabled false } } packagingOptions { exclude 'META-INF/proguard/androidx-annotations.pro' } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'androidx.media:media:1.4.2' implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'com.google.android.material:material:1.4.0' // QR code reading //implementation 'com.google.firebase:firebase-ml-vision-image-label-model:20.0.1' //implementation "com.google.firebase:firebase-ml-model-interpreter:22.0.3" implementation 'com.google.firebase:firebase-ml-vision:17.0.0' implementation 'com.google.firebase:firebase-core:16.0.3' //implementation 'com.google.firebase:firebase-core:17.4.1' // retrofit implementation 'com.squareup.retrofit2:retrofit:2.8.1' implementation 'com.squareup.retrofit2:converter-gson:2.8.1' implementation 'com.squareup.retrofit2:converter-scalars:2.5.0' // kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1' implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0" implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0" testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-core:3.6.28' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.1' implementation 'androidx.constraintlayout:constraintlayout:2.1.1' //multidex implementation 'androidx.multidex:multidex:2.0.1' } repositories { mavenCentral() } <file_sep>/server/src/test/java/de/alina/clipboard/repo/DataManagerTest.java package de.alina.clipboard.repo; import de.alina.clipboard.model.DataType; import de.alina.clipboard.model.User; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import java.io.File; import java.io.IOException; import java.util.UUID; import java.util.concurrent.TimeUnit; import static de.alina.clipboard.repo.IDataManager.*; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class DataManagerTest { private DataManager sut; @Mock private RedisTemplate<String, Object> redisTemplateMock; @Mock private ValueOperations<String, Object> opsValueMock; @Before public void setUp() throws Exception { when(redisTemplateMock.opsForValue()).thenReturn(opsValueMock); sut = new DataManager(redisTemplateMock); } @Test public void getData_returnsUserWithStringData() { UUID id = UUID.randomUUID(); User expectedUser = defaultUser(id); when(redisTemplateMock.hasKey(any())).thenReturn(true); when(opsValueMock.get(USER_ID + id)).thenReturn(expectedUser.stringData); when(opsValueMock.get(TYPE + id)).thenReturn(expectedUser.type); User actualUser = sut.getData(id); assertEquals(expectedUser.stringData, actualUser.stringData); assertEquals(expectedUser.type, actualUser.type); } @Test public void getData_returnsUserWithFileData() { UUID id = UUID.randomUUID(); User expectedUser = defaultUserWithFileData(id); when(redisTemplateMock.hasKey(any())).thenReturn(true); when(opsValueMock.get(USER_ID + id)).thenReturn(expectedUser.fileUrl); when(opsValueMock.get(TYPE + id)).thenReturn(expectedUser.type); User actualUser = sut.getData(id); assertEquals(expectedUser.fileUrl, actualUser.fileUrl); assertEquals(expectedUser.type, actualUser.type); } @Test public void saveData_savesUserWithExpiration() { UUID id = UUID.randomUUID(); User expectedUser = defaultUser(id); when(redisTemplateMock.hasKey(any())).thenReturn(true); when(redisTemplateMock.getExpire(any())).thenReturn(1L); sut.saveData(expectedUser); verify(opsValueMock).set(USER_ID + id, expectedUser.stringData); verify(redisTemplateMock).expire(USER_ID + id, 1L, TimeUnit.SECONDS); } @Test public void deleteUser_deletesKeys() { UUID id = UUID.randomUUID(); when(redisTemplateMock.hasKey(any())).thenReturn(true); boolean successful = sut.deleteUser(id); verify(redisTemplateMock).delete(USER_ID + id); verify(redisTemplateMock).delete(TYPE + id); assertTrue(successful); } @Test public void deleteUser_deletesStoredFiles() throws IOException { File testfile = new File(UPLOADED_FOLDER + "test"); testfile.createNewFile(); UUID id = UUID.randomUUID(); when(redisTemplateMock.hasKey(any())).thenReturn(true); boolean successful = sut.deleteUser(id); verify(redisTemplateMock).delete(USER_ID + id); verify(redisTemplateMock).delete(TYPE + id); assertFalse(testfile.exists()); assertTrue(successful); } @Test public void createUser_returnsUserAndPersist() { } @Test public void storeFile_savesFileWithCorrectPathname() { } @Test public void getStoredFileData_returnsFileDataWithCorrectPathname() { } @Test public void deleteFilesWithUserNonExisting_deletesCorrectFiles() { } private User defaultUser(UUID id) { User user = new User(); user.id = id; user.stringData = "someString"; user.type = DataType.STRING; return user; } private User defaultUserWithFileData(UUID id) { User user = new User(id); user.fileUrl = "fileUrl"; user.type = DataType.FILE; return user; } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/manager/FileManager.kt package de.alina.clipboard.app.manager import android.content.Context import android.database.Cursor import android.net.Uri import android.provider.OpenableColumns import java.io.ByteArrayOutputStream import java.io.InputStream class FileManager { fun getBytes(inputStream: InputStream?): ByteArray { var byteBuffer = ByteArrayOutputStream() val bufferSize = 1024; var buffer = ByteArray(bufferSize); var len = inputStream?.read(buffer) ?: -1 while (len != -1) { byteBuffer.write(buffer, 0, len); len = inputStream?.read(buffer) ?: -1 } inputStream?.close() return byteBuffer.toByteArray(); } fun getFilename(context: Context, fileUri: Uri): String? { val cursor: Cursor? = context.contentResolver.query( fileUri, null, null, null, null, null) val filename = cursor?.use { // moveToFirst() returns false if the cursor has 0 rows. Very handy for // "if there's anything to look at, look at it" conditionals. if (it.moveToFirst()) { // Note it's called "Display Name". This is // provider-specific, and might not necessarily be the file name. it.getString(it.getColumnIndex(OpenableColumns.DISPLAY_NAME)) } else { "Unknown" } } return filename } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/service/ServiceCallback.kt package de.alina.clipboard.app.service import java.util.* interface ServiceCallback { fun performLogout(uuid: UUID) fun onCopyEvent(uuid: UUID, text: String) }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/UploadDataController.kt package de.alina.clipboard.app.client import android.os.Bundle import android.util.Log import okhttp3.MediaType import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* class UploadDataController(): BaseApiController() { fun sendFileData(id: UUID, bytes: ByteArray, mimeType: MediaType, filename: String, callback: Callback<String?>) { val file = RequestBody.create(mimeType, bytes) val part = MultipartBody.Part.createFormData("file", filename, file) val call = apiJSON.uploadData("clipboard.id=" + id.toString(), part) call.enqueue(callback) Log.d(this.toString(), "Requesting " + call.request().url()) } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/APIManager.kt package de.alina.clipboard.app.client import de.alina.clipboard.app.controller.AppController import okhttp3.MediaType import java.util.* interface APIManager { fun acknowledge(id: UUID) fun isConnected(id: UUID) fun getData(id: UUID) fun logout(id: UUID) fun sendStringData(id: UUID, stringData: String) fun sendFileData(id: UUID, bytes: ByteArray, mimeType: MediaType, filename: String) fun reload() companion object { const val CALLBACK_ID_KEY = "de.alina.clipboard.app.callbackId" const val CALLBACK_KEY_ERROR_CODE = "de.alina.clipboard.app.callbackErrorCode" const val CALLBACK_KEY_USER= "de.alina.clipboard.app.callbackUser" } fun subscribe(observer: APIManagerCallback) }<file_sep>/server/src/main/java/de/alina/clipboard/repo/DataManager.java package de.alina.clipboard.repo; import de.alina.clipboard.model.DataType; import de.alina.clipboard.model.User; import de.alina.clipboard.model.UserFileData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Repository; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Base64; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; @Repository public class DataManager implements IDataManager { /** * to save user stringData as object */ private RedisTemplate<String, Object> redisTemplate; /** * to save stringData in String format */ @Autowired public DataManager(RedisTemplate<String, Object> redisTemplate, StringRedisTemplate stringRedisTemplate) { this.redisTemplate = redisTemplate; } @Override public User getData(UUID userID) { String key = USER_ID + userID; String typeKey = TYPE + userID; User user = new User(userID); if (redisTemplate.hasKey(key) && redisTemplate.hasKey(typeKey)) { Object data = redisTemplate.opsForValue().get(key); DataType type = (DataType) redisTemplate.opsForValue().get(typeKey); user.type = type; if (type == DataType.STRING) { user.stringData = (String) data; } else if (type == DataType.FILE) { user.fileUrl = (String) data; } } return user; } @Override public void saveData(User user) { String userKey = USER_ID + user.id; String typeKey = TYPE + user.id; if (redisTemplate.hasKey(userKey) && redisTemplate.hasKey(typeKey)) { if (user.stringData != null) { storeAndUpdateExpiration(userKey, user.stringData); } else if (user.fileUrl != null) { storeAndUpdateExpiration(userKey, user.fileUrl); } else { storeAndUpdateExpiration(userKey, ""); //TODO what to do when no data? } storeAndUpdateExpiration(typeKey, user.type); } } @Override public boolean deleteUser(UUID userID) { if (redisTemplate.hasKey(USER_ID + userID) && redisTemplate.hasKey(TYPE + userID)) { redisTemplate.delete(USER_ID + userID); redisTemplate.delete(TYPE + userID); deleteAllFiles(userID); return true; } return false; } @Override public boolean isUserExisting(UUID userID) { return redisTemplate.hasKey(USER_ID + userID); } @Override public void createUser(UUID userID) { String key = USER_ID + userID; String typeKey = TYPE + userID; redisTemplate.opsForValue().set(key, userID.toString()); redisTemplate.opsForValue().set(typeKey, DataType.UNKNOWN); redisTemplate.expire(key, SESSION_TIMEOUT, TimeUnit.MINUTES); redisTemplate.expire(typeKey, SESSION_TIMEOUT, TimeUnit.MINUTES); } @Override public void storeFile(MultipartFile file, UUID userID) throws IOException{ byte[] bytes = file.getBytes(); // delete previously shared files from server deleteAllFiles(userID); String filename = UPLOADED_FOLDER + userID.toString() + file.getOriginalFilename(); if (filename.contains("../")) { throw new IllegalArgumentException("Cannot store file outside directory"); } Path path = Paths.get(filename); Files.write(path, bytes); User u = new User(userID); u.type = DataType.FILE; u.fileUrl = filename; saveData(u); deleteFileAfterDelay(path); } @Override public UserFileData getStoredFileData(User user) throws IOException{ String fileUrl = user.fileUrl; byte[] fileContent = Files.readAllBytes(Paths.get(fileUrl)); byte[] base64Encoded = Base64.getEncoder().encode(fileContent); String base64String = new String(base64Encoded); File file = new File(fileUrl); UserFileData fileUser = new UserFileData(user.id); fileUser.type = DataType.FILE; fileUser.base64 = base64String; // give back the original file name to the user (without its id and path) fileUrl = fileUrl.replace(UPLOADED_FOLDER, ""); fileUrl = fileUrl.replace(user.id.toString(), ""); fileUser.originalFileName = fileUrl; // delete the internal path to the url before returning to the user fileUser.fileUrl = ""; try { fileUser.mimeType = URLConnection.guessContentTypeFromName(file.getName()); } catch (Exception e) { fileUser.mimeType = ""; } return fileUser; } private void storeAndUpdateExpiration(String key, Object value) { long expire = redisTemplate.getExpire(key); redisTemplate.opsForValue().set(key, value); redisTemplate.expire(key, expire, TimeUnit.SECONDS); } private void deleteAllFiles(UUID userID) { File folder = new File(UPLOADED_FOLDER); if (folder.listFiles() == null) { return; } List<File> listOfFiles = Arrays.asList(folder.listFiles()); listOfFiles.forEach(file -> { if (file.getName().contains(userID.toString())) { file.delete(); } }); } // TODO this is not a very clean solution private void deleteFileAfterDelay(Path path) { new Thread( new Runnable() { public void run() { try { Thread.sleep(TimeUnit.MINUTES.toMillis(SESSION_TIMEOUT) ); } catch (InterruptedException ie) { ie.printStackTrace(); } try { Files.delete(path); } catch (IOException e) { e.printStackTrace(); } } } ).start(); } } <file_sep>/app/app/src/main/java/de/alina/clipboard/app/view/MainActivity.kt package de.alina.clipboard.app.view import android.app.Activity import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity; import android.util.Log import android.view.View import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.widget.Toast import de.alina.clipboard.app.R import de.alina.clipboard.app.client.* import de.alina.clipboard.app.controller.AppController import de.alina.clipboard.app.controller.AppController.Companion.CAPTURE_PICTURE_REQUEST import de.alina.clipboard.app.databinding.ActivityMainBinding import de.alina.clipboard.app.databinding.ContentMainBinding import de.alina.clipboard.app.databinding.ServerAdressMainBinding import de.alina.clipboard.app.manager.* class MainActivity : AppCompatActivity(), BaseView { private lateinit var activityBinding: ActivityMainBinding private lateinit var mainContentBinding: ContentMainBinding private lateinit var serverBinding: ServerAdressMainBinding private val controller = AppController(this, this, APIManagerImpl(), AuthManager(), BackgroundServiceManager(), QRManager(), ClipboardNotificationManager(), FileManager(), ServerAddressManager()) init { lifecycle.addObserver(controller) } override fun onCreate(savedInstanceState: Bundle?) { activityBinding = ActivityMainBinding.inflate(layoutInflater) mainContentBinding = ContentMainBinding.inflate(layoutInflater) serverBinding = ServerAdressMainBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) activityBinding = ActivityMainBinding.inflate(layoutInflater) val view = activityBinding.root setContentView(view) setSupportActionBar(activityBinding.toolbar) mainContentBinding.alertImage.visibility = View.INVISIBLE mainContentBinding.alertText.visibility = View.INVISIBLE mainContentBinding.buttonLogout.visibility = View.INVISIBLE serverBinding.serverAdressInputText.setText( controller.getCurrentServerAddress() ?: "") serverBinding.serverAdressInputText.setOnEditorActionListener { v, actionId, _ -> if(actionId == EditorInfo.IME_ACTION_DONE){ controller.setCurrentServerAddress(v.text.toString()) hideKeyboard(v) v.clearFocus() true } else { false } } activityBinding.fab.setOnClickListener { controller.captureImage() } mainContentBinding.buttonLogout.setOnClickListener { controller.logoutUser() } val disconnectClicked = intent.getBooleanExtra( ClipboardNotificationManager.DISCONNECT_REQUESTED_KEY,false) if (intent?.action == Intent.ACTION_SEND) { controller.handleShareImageEvent(intent) } if (disconnectClicked) { controller.logoutUser() } else Log.d("MainActivity", "do nothing") } override fun showLoginFailure() { showFailure() } override fun showNoInternetConnection() { activityBinding.fab.hide() mainContentBinding.signedInText.text = getString(R.string.no_internet_info) } override fun showSendDataSuccessful() { Toast.makeText(this, getString(R.string.send_Data_successful), Toast.LENGTH_LONG).show() } override fun showGetDataSuccessful() { // TODO: wait for server implementation and copy to local clipboard } override fun showLogoutFailure() { // TODO showLogoutSuccessful() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == CAPTURE_PICTURE_REQUEST && resultCode == RESULT_OK) { controller.processImage(data) } super.onActivityResult(requestCode, resultCode, data) } override fun showLoggedInSuccessful() { mainContentBinding.alertImage.visibility = View.INVISIBLE mainContentBinding.alertText.visibility = View.INVISIBLE activityBinding.fab.hide() mainContentBinding.buttonLogout.visibility = View.VISIBLE mainContentBinding.signedInText.text = getString(R.string.signed_in_info) } override fun showLogoutSuccessful() { activityBinding.fab.show() mainContentBinding.buttonLogout.visibility = View.INVISIBLE mainContentBinding.signedInText.text = getString(R.string.not_signed_in_info) } override fun showFailure() { mainContentBinding.alertImage.visibility = View.VISIBLE mainContentBinding.alertText.visibility = View.VISIBLE } override fun serverUrlIncorrect() { // TODO: show feedback } override fun showSendDataFailure() { Toast.makeText(this, (R.string.send_data_failed), Toast.LENGTH_LONG).show() } override fun showGetDataFailure() { mainContentBinding.alertImage.visibility = View.VISIBLE mainContentBinding.alertText.text = getString(R.string.get_data_failed) mainContentBinding.alertText.visibility = View.VISIBLE } fun hideKeyboard(editText: View) { val inputManager = this.getSystemService(Activity.INPUT_METHOD_SERVICE) if (inputManager is InputMethodManager) { inputManager.hideSoftInputFromWindow(editText.windowToken, 0) } } companion object { const val CHANNEL_ID = "de.alina.clipboard.app.notificationChannel" } } <file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/AcknowledgeController.kt package de.alina.clipboard.app.client import android.util.Log import de.alina.clipboard.app.client.APIManagerCallback.Companion.CALLBACK_ID_KEY import de.alina.clipboard.app.client.APIManagerCallback.Companion.CALLBACK_KEY_ERROR_CODE import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* class AcknowledgeController(): BaseApiController() { var id: UUID? = null fun acknowledge(id: UUID, callback: Callback<String?>) { this.id = id val call = apiString.acknowledge("clipboard.id=" + id.toString()) call.enqueue(callback) Log.d(this.toString(), call.request().headers().toString()) Log.d(this.toString(), "Requesting " + call.request().url()) } }<file_sep>/app/app/src/test/java/de/alina/clipboard/app/TestAuthManager.kt package de.alina.clipboard.app import android.content.Context import android.content.SharedPreferences import de.alina.clipboard.app.manager.AuthManager import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertNull import org.junit.Test import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import java.util.* class TestAuthManager { @Test fun testGetUserKey_ReturnNull() { val context = mock(Context::class.java) val sp = mock(SharedPreferences::class.java) `when`(context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE)) .thenReturn(sp) `when`(sp.getString(context.getString(R.string.user_auth_id_key), "")).thenReturn("") val authManager = AuthManager() val user = authManager.getUserKey(context) assertNull(user) } @Test fun testGetUserKey_ReturnValidUser() { val id = UUID.randomUUID() val context = mock(Context::class.java) val sp = mock(SharedPreferences::class.java) `when`(context.getSharedPreferences(context.getString(R.string.preference_file_key), Context.MODE_PRIVATE)) .thenReturn(sp) `when`(sp.getString(context.getString(R.string.user_auth_id_key), "")).thenReturn(id.toString()) val authManager = AuthManager() val user = authManager.getUserKey(context) assertEquals(user?.id, id) } @Test fun testIsUUIDValid_ReturnNull() { val authManager = AuthManager() val uuid = authManager.isUUIDValid("Kuchen") assertNull(uuid) } @Test fun testIsUUIDValid_ReturnValue() { val uuid = UUID.randomUUID().toString() val authManager = AuthManager() val testUUID = authManager.isUUIDValid(uuid) assertEquals(uuid, testUUID.toString()) } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/ClipboardServerAPI.kt package de.alina.clipboard.app.client import de.alina.clipboard.app.model.User import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Call import retrofit2.http.* import java.io.File interface ClipboardServerAPI { @GET("/acknowledge") @Headers("Accept: text/plain") fun acknowledge(@Header("Cookie") id: String): Call<String?> @GET("/logout") @Headers("Accept: text/plain, application/json") fun logout(@Header("Cookie") id: String): Call<String?> @GET("/connected") @Headers("Accept: text/plain") fun testConnection(@Header("Cookie") id: String): Call<String?> @GET("/get-data") @Headers("Accept: application/json") fun getData(@Header("Cookie")id: String): Call<User?> @POST("/send-data") @Headers("Accept: text/plain") fun sendData(@Header("Cookie")id: String, @Header("data") stringData: String): Call<String?> @Multipart @POST("upload-data") @Headers("Accept: text/plain, application/json") fun uploadData(@Header("Cookie")id: String, @Part file: MultipartBody.Part): Call<String?> companion object { // const val BASE_URL = "http://192.168.127.12:8080" var BASE_URL: String = "http://192.168.127.12:8080" //const val BASE_URL = "http://172.27.176.59:8090/" } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/manager/QRManager.kt package de.alina.clipboard.app.manager import android.graphics.Bitmap import android.util.Log import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions import com.google.firebase.ml.vision.common.FirebaseVisionImage open class QRManager { fun scanQRCode(bitmap: Bitmap, callback: QRInterface) { val options = FirebaseVisionBarcodeDetectorOptions.Builder() .setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE) .build() val detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options); val image = FirebaseVisionImage.fromBitmap(bitmap) detector.detectInImage(image).addOnSuccessListener { if (it.isEmpty()) { callback.onQRScanFinished(null) return@addOnSuccessListener } for (firebaseBarcode in it) { val a = it[0].rawValue ?: "" callback.onQRScanFinished(a) Log.d("QRScanner", "successful") } }.addOnFailureListener { it.printStackTrace() callback.onQRScanFinished(null) Log.d("QRScanner", "failed") } } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/CheckConnectionController.kt package de.alina.clipboard.app.client import android.os.Bundle import android.util.Log import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* open class CheckConnectionController(): BaseApiController() { fun isConnected(id: UUID, callback: Callback<String?>) { val call = apiString.testConnection("clipboard.id=" + id.toString()) call.enqueue(callback) Log.d(this.toString(), "Requesting " + call.request().url()) } }<file_sep>/server/src/main/java/de/alina/clipboard/config/RedisConfiguration.java package de.alina.clipboard.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfiguration { @Bean public JedisConnectionFactory getConnectionFactory() { JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); // jedisConnectionFactory.setHostName("localhost"); // jedisConnectionFactory.setPort(6379); return jedisConnectionFactory; } @Bean(name = "redisTemplate") public RedisTemplate<String, Object> getRedisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setConnectionFactory(getConnectionFactory()); return redisTemplate; } @Bean(name = "stringRedisTemplate") public StringRedisTemplate getStringRedisTemplate() { StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(getConnectionFactory()); stringRedisTemplate.setKeySerializer(new StringRedisSerializer()); stringRedisTemplate.setHashValueSerializer(new StringRedisSerializer()); stringRedisTemplate.setValueSerializer(new StringRedisSerializer()); return stringRedisTemplate; } } <file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/APIManagerImpl.kt package de.alina.clipboard.app.client import android.os.Bundle import android.util.Log import de.alina.clipboard.app.client.APIManager.Companion.CALLBACK_ID_KEY import de.alina.clipboard.app.client.APIManager.Companion.CALLBACK_KEY_ERROR_CODE import de.alina.clipboard.app.client.APIManager.Companion.CALLBACK_KEY_USER import de.alina.clipboard.app.model.User import okhttp3.MediaType import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* class APIManagerImpl: APIManager { private var ackController = AcknowledgeController() private var connectionController = CheckConnectionController() private var getDataController = GetDataController() private var logoutController = LogoutController() private var sendDataController = SendDataController() private var uploadDataController = UploadDataController(); val observers: MutableList<APIManagerCallback> = mutableListOf() override fun subscribe(observer: APIManagerCallback) { observers.add(observer) } override fun acknowledge(id: UUID) { ackController.acknowledge(id, object: Callback<String?> { override fun onFailure(call: Call<String?>, t: Throwable) { for (observer in observers) { observer.onFailure(Bundle(), APIManagerCallback.CallType.ACKNOWLEDGE, t) } } override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { val data = Bundle() data.putString(CALLBACK_ID_KEY, id.toString()) for (observer in observers) { observer.onSuccess(data, APIManagerCallback.CallType.ACKNOWLEDGE) } } else { respondToError(response.code(), "AcknowledgeController", APIManagerCallback.CallType.ACKNOWLEDGE) } } }) } override fun isConnected(id: UUID) { connectionController.isConnected(id, object :Callback<String?> { override fun onFailure(call: Call<String?>, t: Throwable) { observers.forEach() { it.onFailure(Bundle(), APIManagerCallback.CallType.CONNECTION, t) } } override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { if (response.body() == "true") { observers.forEach() { it.onSuccess(Bundle(), APIManagerCallback.CallType.CONNECTION) } } else { Log.d("TestConnectionControlle", "Connection not longer alive.") observers.forEach() { it.onFailure(Bundle(), APIManagerCallback.CallType.CONNECTION, null) } } } else { respondToError(response.code(), "CheckConnectionControlle", APIManagerCallback.CallType.CONNECTION) } } }) } override fun getData(id: UUID) { getDataController.getData(id, object: Callback<User?> { override fun onFailure(call: Call<User?>, t: Throwable) { observers.forEach() { it.onFailure(Bundle(), APIManagerCallback.CallType.GET_DATA, t) } } override fun onResponse(call: Call<User?>, response: Response<User?>) { if (response.isSuccessful) { val user = response.body() val data = Bundle() data.putSerializable(CALLBACK_KEY_USER, user) observers.forEach { it.onSuccess(data, APIManagerCallback.CallType.GET_DATA) } } else { respondToError(response.code(), "GetDataController", APIManagerCallback.CallType.GET_DATA) } } }) } override fun logout(id: UUID) { logoutController.logout(id, object : Callback<String?> { override fun onFailure(call: Call<String?>, t: Throwable) { handleOnFailure(APIManagerCallback.CallType.LOGOUT, t) } override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { observers.forEach { it.onSuccess(Bundle(), APIManagerCallback.CallType.LOGOUT) } } else { respondToError(response.code(), "LogoutController", APIManagerCallback.CallType.LOGOUT) } } }) } override fun sendStringData(id: UUID, stringData: String) { sendDataController.sendStringData(id, stringData, object : Callback<String?> { override fun onFailure(call: Call<String?>, t: Throwable) { handleOnFailure(APIManagerCallback.CallType.SEND_DATA, t) } override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { observers.forEach { it.onSuccess(Bundle(), APIManagerCallback.CallType.SEND_DATA) } } else { respondToError(response.code(), "SendDataController", APIManagerCallback.CallType.SEND_DATA) } } }) } override fun sendFileData(id: UUID, bytes: ByteArray, mimeType: MediaType, filename: String) { uploadDataController.sendFileData(id, bytes, mimeType, filename, object : Callback<String?> { override fun onFailure(call: Call<String?>, t: Throwable) { handleOnFailure(APIManagerCallback.CallType.SEND_FILE_DATA, t) } override fun onResponse(call: Call<String?>, response: Response<String?>) { if (response.isSuccessful) { observers.forEach { it.onSuccess(Bundle(), APIManagerCallback.CallType.SEND_DATA) } } else { respondToError(response.code(), "SendFileDataController", APIManagerCallback.CallType.SEND_FILE_DATA) } } }) } override fun reload() { ackController = AcknowledgeController() connectionController = CheckConnectionController() getDataController = GetDataController() logoutController = LogoutController() sendDataController = SendDataController() uploadDataController = UploadDataController(); } private fun respondToError(responseCode: Int, className: String, type: APIManagerCallback.CallType) { Log.e(className, "Server responded with response code " + responseCode) val data = Bundle() data.putInt(CALLBACK_KEY_ERROR_CODE, responseCode) handleOnFailure(type, null) } private fun handleOnFailure(type: APIManagerCallback.CallType, t: Throwable?) { observers.forEach { it.onFailure(Bundle(), type, t) } } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/model/DataType.kt package de.alina.clipboard.app.model enum class DataType { }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/model/UserFileData.kt package de.alina.clipboard.app.model import java.util.* class UserFileData(id: UUID): User(id) { var base64: String? = null var mimeType: String? = null var originalFilename: String? = null }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/client/APIManagerCallback.kt package de.alina.clipboard.app.client import android.os.Bundle interface APIManagerCallback { enum class CallType { ACKNOWLEDGE, SEND_DATA, SEND_FILE_DATA, GET_DATA, LOGOUT, CONNECTION } fun onSuccess(data: Bundle, type: CallType) fun onFailure(data: Bundle, type: CallType, t: Throwable?) companion object { const val CALLBACK_ID_KEY = "de.alina.clipboard.app.callbackId" const val CALLBACK_KEY_ERROR_CODE = "de.alina.clipboard.app.callbackErrorCode" const val CALLBACK_KEY_USER= "de.alina.clipboard.app.callbackUser" } }<file_sep>/app/app/src/main/java/de/alina/clipboard/app/manager/BackgroundServiceManager.kt package de.alina.clipboard.app.manager import android.content.Context import android.content.Intent import android.os.Build import com.google.android.material.behavior.HideBottomViewOnScrollBehavior import de.alina.clipboard.app.model.User import de.alina.clipboard.app.service.CopyEventService open class BackgroundServiceManager { fun startCopyListenService(context: Context, user: User?) { if (CopyEventService.isRunning) { return } val intent = Intent(context, CopyEventService::class.java) intent.putExtra(User.USER_KEY, user?.id.toString()) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intent) } else { context.startService(intent) } } fun stopCopyListenService(context: Context, user: User?) { val intent = Intent(context, CopyEventService::class.java) intent.putExtra(User.USER_KEY, user?.id.toString()) context.stopService(intent) } fun stopCopyListenService(context: Context) { val intent = Intent(context, CopyEventService::class.java) context.stopService(intent) } }
111e8bec815eb524cc657f485d9b02c8094282a2
[ "Markdown", "JavaScript", "INI", "Gradle", "Java", "Kotlin" ]
38
Kotlin
gerdablum/shared-clipboard
e70c8b9922a1fe4f2eb84a1b4d02d95e0b0d3d56
9339d4a5d26994ab9d1a4a75837abcdec4ae6b3a
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-05-22 23:43 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_date', models.DateTimeField()), ('updated_date', models.DateTimeField()), ('composite_id', models.CharField(max_length=255)), ('is_deleted', models.NullBooleanField()), ('title', models.CharField(blank=True, max_length=255, null=True)), ('author', models.CharField(blank=True, max_length=255, null=True)), ('description', models.TextField(blank=True, null=True)), ('url', models.URLField(blank=True, max_length=1000, null=True)), ('score', models.FloatField(blank=True, null=True)), ('published_at', models.DateTimeField(blank=True, null=True)), ], options={ 'ordering': ['id'], 'abstract': False, }, ), ] <file_sep>from copy import deepcopy from django.conf import settings from django.conf.urls import url, include from .v1_0 import api as v1_0_api v_latest = deepcopy(v1_0_api.api_resources) v_latest.api_name = 'latest' urlpatterns = [ url(r'^', include(v_latest.urls)), url(r'^', include(v1_0_api.api_resources.urls)), ]<file_sep>from django.conf import settings from django.db import models from core.models import SuperModel class Article(SuperModel): title = models.CharField(max_length=255, null=True, blank=True) author = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) url = models.URLField(max_length=1000, null=True, blank=True) score = models.FloatField(null=True, blank=True) published_at = models.DateTimeField(null=True, blank=True) def __unicode__(self): return self.title<file_sep>import urlparse from tastypie.api import Api from tastypie.resources import ModelResource from tastypie.serializers import Serializer from tastypie.cache import SimpleCache from tastypie.throttle import BaseThrottle from goodnews import models as gn_models class urlencodeSerializer(Serializer): formats = ['json', 'jsonp', 'xml', 'yaml', 'html', 'plist', 'urlencode', 'multipart'] content_types = { 'json': 'application/json', 'jsonp': 'text/javascript', 'xml': 'application/xml', 'yaml': 'text/yaml', 'html': 'text/html', 'plist': 'application/x-plist', 'urlencode': 'application/x-www-form-urlencoded', 'multipart': 'multipart/form-data' } def from_urlencode(self, data,options=None): """ handles basic formencoded url posts """ qs = dict((k, v if len(v)>1 else v[0] ) for k, v in urlparse.parse_qs(data).iteritems()) return qs def to_urlencode(self,content): pass class DummyPaginator(object): def __init__(self, request_data, objects, resource_uri=None, limit=None, offset=0, max_limit=1000, collection_name='objects'): self.objects = objects self.collection_name = collection_name def page(self): return { self.collection_name: self.objects } class BaseModelResource(ModelResource): class Meta: allowed_methods = ['get'] ordering = ['created_date','updated_date'] exclude_fields = ['created_date','updated_date','is_deleted'] always_return_data = True serializer = urlencodeSerializer() cache = SimpleCache(timeout=10) throttle = BaseThrottle() paginator_class = DummyPaginator def determine_format(self, request): if (hasattr(request, 'format') and request.format in self._meta.serializer.formats): return self._meta.serializer.get_mime_for_format(request.format) return 'application/json' def obj_create(self, bundle, **kwargs): # override here return super(BaseModelResource, self).obj_create(bundle, **kwargs) def obj_update(self, bundle, **kwargs): # override here return super(BaseModelResource, self).obj_update(bundle, **kwargs) def dehydrate(self, bundle): # Pass in system_fields=1 if you are admin user to show the excluded fields system_fields = bundle.request.GET.get('system_fields','') if not(system_fields and bundle.request.user.is_staff == True): bundle.data = { key : value for key, value in bundle.data.copy().iteritems() if \ key not in self.Meta.exclude_fields } return bundle class ArticleResource(BaseModelResource): class Meta(BaseModelResource.Meta): queryset = gn_models.Article.objects.all() resource_name = 'article' api_resources = Api(api_name='v1.0') api_resources.register(ArticleResource()) <file_sep>Setup Local Environment ============= 1. Install requirements - `pip install -r requirements.txt` to install python dependencies 2. Run migrations - use `ENV=local` for development environment - `./manage.py makemigrations <module_name>` - `./manage.py migrate <module_name>` 3. Start all processes at once using `forego` (auto asset recompile, local server, etc.) - Install `forego` - `forego start -f Procfile.dev`<file_sep>from django.test import TestCase from django.core.urlresolvers import reverse from goodnews.models import Article class ArticleAPITest(TestCase): @classmethod def setUpTestData(cls): Article.objects.create(url='http://www.google.com', title='Google') def test_view_url_exists_at_desired_location(self): resp = self.client.get('/api/v1.0/article/') self.assertEqual(resp.status_code, 200) <file_sep># ==Framework== Django==1.9.8 # ==Webserver== gunicorn==19.6.0 # ==DB== psycopg2==2.6.2 django-redis==4.6.0 # ==Scheduled Jobs== rq==0.6.0 rq-scheduler==0.7.0 # ==API== django-tastypie==0.13.3 # ==Admin== django-grappelli==2.8.1 # ==Utils== django-model-utils==2.6 textblob==0.12.0 newspaper==0.0.9.8 # ==DEV TOOLS== coverage==4.4.1 django-extensions==1.7.1 werkzeug==0.11.10 ipython # ==HEROKU== dj-database-url==0.2.1 whitenoise==3.2.2 <file_sep>import os env = os.getenv("ENV") if env == "production": DEBUG = False else: DEBUG = True ALLOWED_HOSTS = ['*'] PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) SECRET_KEY = os.getenv("SECRET_KEY") or '---------------------------------------------------------------' SCORE_THRESHOLD = 0.1 # HEROKU specific if env == "production": import dj_database_url DATABASES = {} DATABASES['default'] = dj_database_url.config() DATABASES['default']['CONN_MAX_AGE'] = 500 # SECURE_SSL_REDIRECT = True # SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') else: DATABASES = os.getenv("DATABASES") or \ { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(PROJECT_ROOT, 'db.sqlite3'), } } CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.getenv("REDIS_URL") or 'redis://localhost:6379/0', "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } TASTYPIE_DEFAULT_FORMATS = ['json', 'jsonp', 'xml'] BROKER_URL = os.getenv("BROKER_URL") or 'redis://localhost:6379/1' BROKER_POOL_LIMIT = 8 # site APPEND_SLASH = True SITE_ID = 1 SITE_DOMAIN = os.getenv("SITE_DOMAIN") or '127.0.0.1:8000' if env == "production": SITE_DOMAIN = 'www.goodnews123.com' SITE_NAME = 'GoodNews' GRAPPELLI_ADMIN_TITLE = SITE_NAME + ' Admin Panel' TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True USE_ETAGS = True USE_TZ = True # third-party creds NEWS_API_KEY = os.getenv("NEWS_API_KEY") SOURCES_ENDPOINT = 'https://newsapi.org/v1/sources' ARTICLES_ENDPOINT = 'https://newsapi.org/v1/articles' AUTH_USER_MODEL = 'auth.User' ROOT_URLCONF = 'core.urls' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', ] STATIC_URL = '/static/' if env == "production": STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') # '/var/www/example.com/static/' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'compressor.finders.CompressorFinder' ] STATICFILES_DIRS = (os.path.join(PROJECT_ROOT, 'static')) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.join(PROJECT_ROOT, 'frontend'), 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.template.context_processors.static', ], } }, ] MIDDLEWARE_CLASSES = [ # if upgrading to django 1.10 look into `MIDDLEWARE` setting # 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # 'django.middleware.cache.FetchFromCacheMiddleware', ] INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'grappelli', 'django.contrib.admin', 'django.contrib.staticfiles', 'tastypie', 'core', 'goodnews' ] WSGI_APPLICATION = 'wsgi.application' if env == "local": from .local import * <file_sep>from django.conf import settings from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from django.contrib import messages def my_404_view(request): messages.error(request, 'PAGE NOT FOUND', extra_tags='safe') return redirect(reverse('home')) def my_500_view(request): messages.error(request, 'AN ERROR OCCURRED', extra_tags='safe') return redirect(reverse('home')) <file_sep>### load settings and apps ### import django ## django.setup() ## ############################## import os import redis from rq import Worker, Queue, Connection conn = redis.from_url(os.getenv('BROKER_URL')) listen = ['default'] if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work()<file_sep>from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from . import views admin.autodiscover() handler404 = views.my_404_view handler500 = views.my_500_view urlpatterns = [ url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('core.api.urls')), url(r'^', include('goodnews.urls')) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)<file_sep>import urllib import json from dateutil import parser from django.conf import settings from django.utils import timezone from textblob import TextBlob from newspaper import Article from goodnews import models as gn_models def run_article_scores(): sources_json = json.loads(urllib.urlopen(settings.SOURCES_ENDPOINT + '?apiKey=%s&language=en&country=us' % settings.NEWS_API_KEY).read()) for source in sources_json['sources']: if source ['category'] == 'sports': continue source_articles_endpoint = settings.ARTICLES_ENDPOINT + '?apiKey=%s&source=%s&sortBy=%s' % (settings.NEWS_API_KEY, source['id'], source['sortBysAvailable'][0]) articles_json = json.loads(urllib.urlopen(source_articles_endpoint).read()) for article in articles_json['articles']: try: content = Article(article['url']) content.download() content.parse() words = TextBlob(content.text) words.sentiment new_article, created = gn_models.Article.objects.get_or_create(url=article['url']) new_article.title = article['title'] new_article.author = article['author'] new_article.description = article['description'] new_article.score = (words.polarity)*(1-words.subjectivity) new_article.published_at = parser.parse(article['publishedAt']) new_article.save() except: continue <file_sep>from datetime import datetime, timedelta from django.conf import settings from django.shortcuts import render, redirect from django.utils import timezone from . import models def home(request): articles = models.Article.objects.filter( published_at__gt=timezone.now() - timedelta(days=2), score__gt=settings.SCORE_THRESHOLD ) return render(request, 'home.html', {'articles': articles}) <file_sep>### load settings and apps ### import django ## django.setup() ## ############################## import os import redis from rq_scheduler import Scheduler from scheduled_jobs import master_jobs conn = redis.from_url(os.getenv('BROKER_URL')) if __name__ == '__main__': scheduler = Scheduler(connection=conn) # remove existing master scheduler job for job in scheduler.get_jobs(): if job.description == 'master': scheduler.cancel(job) ###### add cron jobs here ####### # scheduler.cron( # # cron_string, #=> A cron string (e.g. "0 0 * * 0") # func=func, #=> Function to be queued # args=[arg1, arg2], #=> Arguments passed into function when executed # kwargs={'foo': 'bar'}, #=> Keyword arguments passed into function when executed # repeat=10 #=> Repeat this number of times (None means repeat forever) # queue_name=queue_name #=> In which queue the job should be put in # ) # ################################# scheduler.cron( "0 */2 * * *", func=master_jobs.run_article_scores, queue_name='default', description='master' ) scheduler.run() <file_sep>import hashlib from django.conf import settings from django.utils import timezone from django.db import models from django.core.exceptions import FieldError from django.db.models.fields.related import ManyToManyField from model_utils import FieldTracker class DeletedManager(models.Manager): def get_queryset(self): return super(DeletedManager, self).get_queryset().exclude(is_deleted=True) class BaseMeta(): ordering = ['id'] class AbstractFieldTracker(FieldTracker): def finalize_class(self, sender, name, **kwargs): self.name = name self.attname = '_%s' % name if not hasattr(sender, name): super(AbstractFieldTracker, self).finalize_class(sender, **kwargs) class SuperModel(models.Model): created_date = models.DateTimeField() updated_date = models.DateTimeField() composite_id = models.CharField(max_length=255) is_deleted = models.NullBooleanField() objects = DeletedManager() def __init__(self, *args, **kwargs): AbstractFieldTracker().finalize_class(self.__class__, 'tracker') # e.g. self.tracker.previous('< fieldname >') super(SuperModel, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): curr_time = timezone.now() if not self.id: self.created_date = curr_time self.composite_id = hashlib.sha256(str(self._meta.db_table) + str(curr_time)).hexdigest() self.updated_date = curr_time super(SuperModel, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.is_deleted = True super(SuperModel, self).save(*args, **kwargs) def to_dict(self): opts = self._meta data = {} for f in opts.concrete_fields + opts.many_to_many: if isinstance(f, ManyToManyField): if self.pk is None: data[f.name] = [] else: data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True)) else: data[f.name] = f.value_from_object(self) return data @classmethod def get_fields(cls): return {str(field.column): str(field.get_internal_type())\ for field in cls._meta.fields} class Meta(BaseMeta): abstract = True <file_sep>from django.core.management import call_command from django.core.management.base import BaseCommand, CommandError from scheduled_jobs import master_jobs class Command(BaseCommand): help = 'Runs article scoring via CLI' def handle(self, *args, **options): master_jobs.run_article_scores() <file_sep>from django.test import TestCase from goodnews.models import Article class ArticleModelTest(TestCase): @classmethod def setUpTestData(cls): Article.objects.create(url='http://www.google.com', title='Google') def test_title_label(self): article = Article.objects.get(id=1) field_label = article._meta.get_field('title').verbose_name self.assertEquals(field_label,'title')
c38de55d3cbb85a838c28caeef5a6a4a7d0a8e49
[ "Markdown", "Python", "Text" ]
17
Python
jpwagner/goodnews
311b57882beb96121432593467012b428f547411
a5252fcd56041c034a0e114d5ae38d06cebc30fe
refs/heads/master
<file_sep># Docker Kibana Development [![](https://images.microbadger.com/badges/image/rigon/kibana-dev.svg)](https://microbadger.com/images/rigon/kibana-dev "Get your own image badge on microbadger.com") [![](https://images.microbadger.com/badges/version/rigon/kibana-dev.svg)](https://microbadger.com/images/rigon/kibana-dev "Get your own version badge on microbadger.com") Docker image with Kibana for plugin developement ## Image variants The `rigon/kibana-dev` images come in many flavors, each designed for a specific use case. They are from [node](https://hub.docker.com/_/node/) image: - `rigon/kibana-dev:<version>`: the defacto image. If you are unsure, you probably want to use this one. - `rigon/kibana-dev:<version>-alpine`: based on the popular Alpine Linux project. Much smaller image. - `rigon/kibana-dev:<version>-slim`: do not contain the common packages as in the default tag and only contains the minimal packages needed to run node. ## How to run This image requires an [elasticsearch](https://hub.docker.com/_/elasticsearch/) up and running with the same version of Kibana: $ docker run --name some-elasticsearch -p 9200:9200 -d docker.elastic.co/elasticsearch/elasticsearch:[version] This image includes EXPOSE 5601 (default port). If you'd like to be able to access the instance from the host without the container's IP, standard port mappings can be used: $ docker run --name some-kibana --link some-elasticsearch:elasticsearch -p 5601:5601 -t rigon/kibana-dev If you are developing plugins for Kibana, you might want to mount your plugins folder in Kibana through a volume: $ docker run --name some-kibana -v your_plugins_folder:/kibana/plugins:rw --link some-elasticsearch:elasticsearch -p 5601:5601 -t rigon/kibana-dev Or if you are only developing one plugin, you might want to mount the plugin folder directly into Kibana: $ docker run --name some-kibana -v your_plugin_path:/kibana/plugins/your_plugin_name:rw --link some-elasticsearch:elasticsearch -p 5601:5601 -t rigon/kibana-dev ## How to build The script `build.sh` automatically creates tags for every version of Kibana, just run it and follow the instructions! <file_sep>#!/bin/sh RED="\033[0;31m" BLUE="\033[0;34m" GREEN="\033[0;32m" YELLOW="\033[1;33m" NC="\033[0m" # No Color if [ ! -e Dockerfile ]; then echo -e "${RED}Dockerfile not found!${NC}" exit 1 fi echo "A clone of Kibana repository in /tmp is required to proceed!" read -r -p "Do you want clone it (YES/No)? " ans if [ "$ans" != "n" ]; then pushd . cd /tmp echo -e "${YELLOW}Cloning Kibana...${NC}" rm -rf kibana git clone https://github.com/elastic/kibana.git popd fi # Get list of tags from Kibana repository pushd . cd /tmp/kibana # Get and filter only final versions versions=$(git tag | grep -o -e '^v[[:digit:]]\{1,\}\.[[:digit:]]\{1,\}\.[[:digit:]]\{1,\}$' | cut -dv -f2-) popd echo -e "${RED}CAUTION: THIS ACTION IS IRREVERSIBLE!!${NC}" echo "This will delete all tags in the local repository!" read -r -p "Do you want delete all tags in local reposiroty (yes/NO)? " ans if [ "$ans" = "yes" ]; then git tag --delete $(git tag) fi create_version() { kibana=$1 node=$2 tagname=$3 if [ "$ans" != "a" ]; then ans="n" fi while [ "$ans" = "n" ]; do echo -e "${YELLOW}Check if this is correct:${NC}" echo " Node version: $node" echo " Kibana version: $kibana" read -r -p "This is correct (YES/No/Skip/All)? " ans if [ "$ans" = "n" ]; then read -r -p "Node version? " nver fi done # Skip if [ "$ans" = "s" ]; then return fi # Create version git tag -d $tagname # Delete existing version sed -i "s/.*FROM node.*/FROM node:$node/" Dockerfile sed -i "s/.*ENV KIBANA_VERSION.*/ENV KIBANA_VERSION tags\/v$kibana/" Dockerfile git add Dockerfile git commit -m "Kibana v$tagname" git tag $tagname git reset HEAD~ git checkout -- Dockerfile } for version in $versions; do echo -e "${BLUE}-- ${GREEN}Version $version${NC}" # Get corresponding node version pushd . cd /tmp/kibana git checkout tags/v$version if [ -e .node-version ]; then node_version=$(cat .node-version | sed "s/.x//") else node_version="0.10" # Older versions fi popd # Main versions git checkout main create_version $version $node_version $version # Slim versions git checkout slim create_version $version $node_version-slim $version-slim # Alpine versions git checkout alpine create_version $version $node_version-alpine $version-alpine done # Back to master git checkout master echo echo -e "${RED}CAUTION: THIS ACTION IS IRREVERSIBLE!!${NC}" echo "This will delete all tags in the REMOTE repository!" read -r -p "Do you want delete all tags in REMOTE repository (yes/NO)? " ans if [ "$ans" = "yes" ]; then git push --delete origin $(git ls-remote --tags origin | cut -f 2-) fi echo echo "This will push all local tags to the remote repository!" read -r -p "Do you want push tags changes (YES/No)? " ans if [ "$ans" != "n" ]; then git push --tags --force fi echo echo -e "${YELLOW}Docker Hub trigger token is required to trigger builds${NC}" read -r -p "Trigger token: " trigger_token if [ "$trigger_token" = "" ]; then echo -e "${RED}No trigger token provided!${NC}" echo "Exiting..." exit 1 fi echo echo -e "${YELLOW}We are about to trigger builds${NC}" echo "This will trigger builging all versions, i. e. all tags." echo "If not, you will be asked to build main, slim and alpine versions." read -r -p "Do you want to trigger building all versions (Yes/NO)? " ans if [ "$ans" = "y" ]; then for tag in $(git tag); do echo -n -e "${YELLOW}$tag${NC} " curl -X POST -H "Content-Type: application/json" \ --data \{\"source_type\":\ \"Tag\",\ \"source_name\":\ \"${tag}\"\} \ https://registry.hub.docker.com/u/rigon/kibana-dev/trigger/$trigger_token/; echo sleep 1m done echo -e "${GREEN}DONE!${NC}" exit 0 fi echo read -r -p "Do you want to trigger building all main versions (YES/No)? " ans if [ "$ans" != "n" ]; then for tag in $(git tag | grep -v -E "alpine|slim"); do echo -n -e "${YELLOW}$tag${NC} " curl -X POST -H "Content-Type: application/json" \ --data \{\"source_type\":\ \"Tag\",\ \"source_name\":\ \"${tag}\"\} \ https://registry.hub.docker.com/u/rigon/kibana-dev/trigger/$trigger_token/; echo sleep 1m done fi echo read -r -p "Do you want to trigger building all slim versions (YES/No)? " ans if [ "$ans" != "n" ]; then for tag in $(git tag | grep slim); do echo -n -e "${YELLOW}$tag${NC} " curl -X POST -H "Content-Type: application/json" \ --data \{\"source_type\":\ \"Tag\",\ \"source_name\":\ \"${tag}\"\} \ https://registry.hub.docker.com/u/rigon/kibana-dev/trigger/$trigger_token/; echo sleep 1m done fi echo read -r -p "Do you want to trigger building all alpine versions (YES/No)? " ans if [ "$ans" != "n" ]; then for tag in $(git tag | grep alpine); do echo -n -e "${YELLOW}$tag${NC} " curl -X POST -H "Content-Type: application/json" \ --data \{\"source_type\":\ \"Tag\",\ \"source_name\":\ \"${tag}\"\} \ https://registry.hub.docker.com/u/rigon/kibana-dev/trigger/$trigger_token/; echo sleep 1m done fi echo -e "${GREEN}DONE!${NC}"
3dc372fdc71ecf64e2356cc873f6f44bb29370d7
[ "Markdown", "Shell" ]
2
Markdown
PolinaIP/docker-kibana-dev
ab66350fd382225d6467cf7d5ac3d430a2c347b3
94c5fe5e879984bfb2a88239af54a08b3028b468
refs/heads/main
<file_sep>"# how-to-close-running-excel-by-c-" <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Office.Interop.Excel; using Excel = Microsoft.Office.Interop.Excel; namespace Microsoft.Office.Interop { class Program { static void Main(string[] args) { Excel.Application xlApp; Excel.Workbook xlWorkBook; // xlApp = new Excel.Application(); xlApp= (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); xlApp.Visible = true; xlApp.ActiveWorkbook.Close(); /* xlWorkBook = xlApp.Workbooks.Open("c:/1.xlsx"); xlWorkBook.Close();*/ /* Excel._Application objExcel; objExcel = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); objExcel.ActiveWorkbook.Save(); int a = 3333; // objExcel.Workbooks.Open("c://1.xlsx"); MyExcel.Application EXC1 = new Excel.Application();*/ // System.Console.Write("dsafdsfsad"); } } }
c52434c954e6f853909e144dfdb98b2c21c84e85
[ "Markdown", "C#" ]
2
Markdown
zhangbo2008/how-to-close-running-excel-by-c-sharp
28dbc9ac3b2c00a0b5bfa3fc474931bb301a5a1e
81283d60c9ed396ca798767e4a21063e332d57da
refs/heads/master
<repo_name>MAD11877/mad-practical-5-recyclerview-kenwongz<file_sep>/app/src/main/java/sg/edu/np/mad/mad_recyclerview/Adapter.java package sg.edu.np.mad.mad_recyclerview; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> { private final String TAG = "DataList"; private List<String> mdatalist; private LayoutInflater minflater; private ItemClickListener mlistener; public Adapter(Context context, List<String> datalist) { this.minflater = LayoutInflater.from(context); this.mdatalist = datalist; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = minflater.inflate(R.layout.layout, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { String s = mdatalist.get(position); holder.mtextview.setText(s); } @Override public int getItemCount() { return mdatalist.size(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView mtextview; ViewHolder(View itemView) { super(itemView); mtextview = itemView.findViewById(R.id.result); itemView.setOnClickListener(this); } @Override public void onClick(View view){ if (mlistener != null) mlistener.onItemClick(view, getAdapterPosition()); } } String getItem(int i){ return mdatalist.get(i); } void setClickListener(ItemClickListener mitemclick){ this.mlistener = mitemclick; } public interface ItemClickListener{ void onItemClick(View view, int position); } }
78df055994fa9d6496ab6b2ef3153d6b6dca43a6
[ "Java" ]
1
Java
MAD11877/mad-practical-5-recyclerview-kenwongz
b2b37505662904dab0d63117cd6ba36942588977
0d139af75c600c548d44db237bef410eee17fcdd
refs/heads/master
<repo_name>AndryKazanovsky/excellence<file_sep>/src/js/burger.js 'use strict'; function hide () { document.body.classList.toggle('open'); burger.classList.toggle('open'); } var burger = document.getElementById('burger-button'); burger.addEventListener('click', function (e) { e.preventDefault(); hide(); }); var burgerMenu = document.getElementsByClassName('burger__menu')[0]; var links = burgerMenu.getElementsByTagName('li'); for(var i=0; i<links.length; i++) { links[i].onclick = function(e){ e.preventDefault(); hide(); window.location = e.target.href; } }<file_sep>/src/js/select.js var langs = document.querySelectorAll('[data-lang] a'); var ul=document.getElementsByClassName("language-select")[0]; var li=ul.getElementsByTagName("li"); ul.onclick=function(){ul.classList.toggle("open")}; for(var i=0;i<langs.length;i++){ langs[i].onclick=function(l){ l.preventDefault(); l.stopImmediatePropagation(); for(var e=0;e<li.length;e++){ li[e].classList.remove("active"); }; l.target.parentNode.classList.toggle("active"); ul.classList.toggle("open") var request = new XMLHttpRequest(); request.open('POST', this.getAttribute("href"), true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.send({}); return false; } }
4b05992b9e91d8915cd22910f2daf30d157f0bf4
[ "JavaScript" ]
2
JavaScript
AndryKazanovsky/excellence
2477282f4e9283203db789543706c154ecba0278
36f3a91e9b75e39724a67447b27d2b39d397048f
refs/heads/main
<repo_name>matangeorgi/Webol---hadassah<file_sep>/src/routes/messages.ts import * as express from 'express'; import * as controller from '../controller/messages'; import * as verify from '../token/verifyToken'; const router = express.Router(); // ----------- Auth Post Routes ----------- router.post('/sendmessage', verify.connect, controller.sendMessages); // ----------- Auth Get Routes ----------- router.get('/check', verify.connect, controller.checkMessages); router.get('/getusersmessages', verify.connect, controller.getUsersUnreadMessages); router.get('/getmessages/:senderId/:offset', verify.connect, controller.getMessages); router.get('/leaveconversation/:senderId', verify.connect, controller.leaveConversation); export default router;<file_sep>/src/entity/follow.ts import { BaseEntity, Entity, PrimaryGeneratedColumn, ManyToOne, Index } from "typeorm"; import User from './user'; @Entity("follow") export default class Follow extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Index() @ManyToOne(() => User, (user: User) => user.follower, {onDelete: "CASCADE", onUpdate: "CASCADE"}) follower: string; @Index() @ManyToOne(() => User, (user: User) => user.follow, {onDelete: "CASCADE", onUpdate: "CASCADE"}) user: string; };<file_sep>/src/app.ts import dotenv from 'dotenv'; dotenv.config(); import 'reflect-metadata'; import app from './server'; import { initStorage } from './storage'; import {socketConnection} from './socket/socket'; const http = require('http').createServer(app); const io = require('socket.io')(http, {cors: {origin: '*'}}); io.on("connection", socketConnection); // Server listen on http//localhost:3000 (async () => { await initStorage(); http.listen(process.env.PORT || 3000, () => console.log('Server is running')); })(); export default io;<file_sep>/src/routes/globalRequest.ts import * as express from 'express'; import * as controller from '../controller/globalPagesRequests'; import * as verify from '../token/verifyToken'; const router = express.Router(); // ----------- Auth Post Routes ----------- router.post('/addcomment', verify.connect, controller.addComment); // ----------- Auth Get Routes ----------- router.get('/addordeletelike/:postId/:userId', verify.connect, controller.addOrDeleteLike); router.get('/gethomepage/:offset', verify.connect, controller.getHomePage); router.get('/getcomments/:postId', verify.connect, controller.getComments); router.get('/getlikes/:postId/:offset', verify.connect, controller.getLikes); router.get('/getcategories/:category/:offset', verify.connect, controller.getCategories); // ----------- Auth Delete Routes ----------- router.delete('/deletecomment/:commentId', verify.connect, controller.deleteComment); export default router;<file_sep>/src/validate/registerValidate.ts import Joi from '@hapi/joi'; import { UserInput } from '../types'; export function registerValidation(data: UserInput) { const schema = Joi.object({ password: Joi.string() .required() .min(8), email:Joi.string() .required() .email(), fullName:Joi.string() .required(), username:Joi.string() .required() }); return schema.validate(data); }; export function loginValidation(data: Pick<UserInput, 'username'|'password'>) { const schema = Joi.object({ username: Joi.string() .required(), password: Joi.string() .required() .min(8) }); return schema.validate(data); }; export function passwordValidation(data: { password: string }) { const schema = Joi.object({ password: Joi.string() .required() .min(8) }); return schema.validate(data); }; export function emailValidation(data: { email: string }) { const schema = Joi.object({ email:Joi.string() .required() .email() }); return schema.validate(data); };<file_sep>/src/entity/post.ts import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, CreateDateColumn, Index } from "typeorm"; import User from './user'; import Comment from './comment' import Likes from "./likes"; @Entity("post") export default class Post extends BaseEntity { @PrimaryGeneratedColumn() id: string; @CreateDateColumn() createdAt: Date; @Column({ nullable: true }) description: string; @Column({ nullable: true }) url: string; @Column() category: string; @Index() @ManyToOne(() => User, (user: User) => user.post, {onDelete: "CASCADE", onUpdate: "CASCADE"}) user: string; @OneToMany(() => Comment, (comment: Comment) => comment.post, {cascade: true}) comment: Array<Comment>; @OneToMany(() =>Likes, (like: Likes) => like.post, {cascade: true}) like: Array<Likes>; };<file_sep>/test/passMailer.test.ts import dotenv from 'dotenv'; dotenv.config(); import { getConnection } from "typeorm" import { initLocalStorage } from '../src/storage'; import User from '../src/entity/user'; import { resetPasswordRequest, registerRequest} from './utilities/apiFunctions' import { faker } from '@faker-js/faker' describe("Mailer function", () =>{ beforeAll(async() =>{ try{ await initLocalStorage(); } catch(e){ console.log(e); } }); afterAll(async () =>{ try{ await getConnection() .createQueryBuilder() .delete() .from(User).execute(); } catch(e){ console.log(e); } }); test("When email is not valid should respond with a status code 400",async () => { const body = { email: faker.internet.userName() } const loginRes = await resetPasswordRequest(body); expect(loginRes.text).toBe("{\"error\":\"Email is not valid\"}"); expect(loginRes.statusCode).toBe(400); }); // test("When email is valid but not found respond with a status code 400",async () => { // const body = { // email: faker.internet.email() // } // const loginRes = await resetPasswordRequest(body); // expect(loginRes.text).toBe("{\"error\":\"User did not found\"}" ); // expect(loginRes.statusCode).toBe(400); // }); // test("When email valid and found respond with a status code 200 only send", async () => { // const body = { // username: faker.internet.userName(), // password: <PASSWORD>(), // fullName: faker.name.findName(), // email: faker.internet.email() // }; // const registerRes = await registerRequest(body); // expect(registerRes.statusCode).toBe(200); // expect(registerRes.text).toBe("{\"message\":\"Sign up successfully\"}"); // const user = { // email: body.email // } // const loginRes = await resetPasswordRequest(user); // expect(loginRes.text).toBe("{\"message\":\"Email send\"}"); // expect(loginRes.statusCode).toBe(200); // }); });<file_sep>/src/entity/messages.ts import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, ManyToOne, CreateDateColumn, Index, OneToMany } from "typeorm"; import User from "./user"; @Entity("messages") @Index(["sender", "recipient", "read"]) @Index(["recipient", "read"]) export default class Messages extends BaseEntity { @PrimaryGeneratedColumn() id: string; @CreateDateColumn() createdAt: Date; @Column() read: boolean; @Column() message: string; @Index() @ManyToOne(() => User, (user: User) => user.messageSend, {onDelete: "CASCADE", onUpdate: "CASCADE"}) sender: string; @Index() @ManyToOne(() => User, (user: User) => user.messageRecipient, {onDelete: "CASCADE", onUpdate: "CASCADE"}) recipient: string; };<file_sep>/src/entity/comment.ts import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, ManyToOne, CreateDateColumn, Index } from "typeorm"; import Post from './post'; import User from "./user"; @Entity("comment") export default class Comment extends BaseEntity { @PrimaryGeneratedColumn() id: string; @CreateDateColumn() createdAt: Date; @Column({ nullable: true }) content : string; @Index() @ManyToOne(() => User, (user: User) => user.comment, {onDelete: "CASCADE", onUpdate: "CASCADE"}) user: string; @Index() @ManyToOne(() => Post, (post: Post) => post.comment, {onDelete: "CASCADE", onUpdate: "CASCADE"}) post: string; };<file_sep>/src/routes/signInSignUp.ts import * as express from 'express'; import * as controller from '../controller/signInSignUp'; import * as verify from '../token/verifyToken'; const router = express.Router(); // ----------- Auth Post Routes ----------- router.post('/login', controller.logInPost); router.post('/register', controller.registerPosts); router.post('/googlelogin', controller.googleLogIn); router.post('/resetpass', controller.passwordReset); router.post('/updatenewpass', verify.resetPassToken, controller.passUpdate); export default router;<file_sep>/src/entity/notifications.ts import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, Index, ManyToOne } from "typeorm"; import User from "./user"; @Entity("notifications") @Index(["userConnect", "read"]) export default class Notification extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Column() message : string; @Column() read: boolean; @Column({ nullable: true }) postId: string; @Index() @Column() userConnect : string; @Index() @ManyToOne(() => User, (user: User) => user.notifications, {onDelete: "CASCADE", onUpdate: "CASCADE"}) user : string; };<file_sep>/src/controller/paypal.ts import { Request, Response } from 'express'; import _ from 'lodash'; import { getManager } from 'typeorm'; const AMOUNT = 20; export async function signToWebol(req: Request, res: Response){ try{ res.status(201).json(); } catch(err) { console.log(err) return res.status(500).json({error: err.message}); } }<file_sep>/src/socket/utilities.ts const users = {}; const notifications = {}; export function addUser(userId: string, socketId: string) { users[userId] = socketId return users }; export function removeUser(socketId: string){ Object.keys(users).map((k) => {users[k] === socketId && delete users[k]}) return users; }; export function getUser(userId: string){ return users[userId]; }; export function addNotification(userId: string) { notifications[userId]? notifications[userId] += 1 : notifications[userId] = 1; return notifications }; export function removeNotification(userId: string){ if(notifications[userId]) delete notifications[userId]; return notifications; };<file_sep>/src/routes/userRequest.ts import * as express from 'express'; import * as controller from '../controller/userPageRequests'; import * as verify from '../token/verifyToken'; const router = express.Router(); // ----------- Auth Post Routes ----------- router.post('/addpost', verify.connect, controller.addPost); // ----------- Auth Get Routes ----------- router.get('/:username', verify.connect, controller.getUserPage); router.get('/getfollowers/:username/:offset', verify.connect, controller.getFollowers); router.get('/getmoreuserpost/:username/:offset', verify.connect, controller.getMoreUserPost); router.get('/addordeletefollower/:userToFollowId', verify.connect, controller.addOrDeleteFollower); // ----------- Auth Delete Routes ----------- router.delete('/deletepost/:postId', verify.connect, controller.deletePost); export default router;<file_sep>/src/validate/postAndComment.ts import Joi from '@hapi/joi'; import { PostInput, CommentInput } from '../types'; export function addPostValidation(data : PostInput) { const schema = Joi.object({ description: Joi.string().required(), url: Joi.string(), category: Joi.string().required() }); return schema.validate(data); }; export function addCommentValidation(data : CommentInput) { const schema = Joi.object({ content: Joi.string().required(), postId: Joi.number().required(), userId: Joi.string().required() }); return schema.validate(data); };<file_sep>/src/controller/topBarRequest.ts import { Request, Response } from 'express'; import _ from 'lodash'; import { getManager } from 'typeorm'; import User from '../entity/user'; import Notifications from '../entity/notifications'; import { deeplyFilterUser, fixString } from './globalPagesRequests'; import Follow from '../entity/follow'; import Post from '../entity/post'; const AMOUNT = 20; export async function findPosts(req: Request, res: Response){ try{ const subQ = getManager() .createQueryBuilder(User,"user") .leftJoinAndSelect(Follow, 'f', 'user.id = f.followerId') .select('f.userId') .where(`user.id = '${req['user'].id}'`); const result = await getManager() .getRepository(Post) .createQueryBuilder("post") .leftJoinAndSelect("post.user", "u") .where("post.user IN (" + subQ.getQuery() + ")") .andWhere("post.description like :description", { description:`%${req.params.description.toLocaleLowerCase()}%`}) .orWhere(`post.user = '${req['user'].id}'`) .orderBy('post.id','DESC') .limit(AMOUNT).offset(+req.params.offset) .select('post.description') .addSelect('post.id') .addSelect('u.profileImage') .addSelect('u.displayUsername') .distinct(true) .getMany() for (let [ key, value ] of Object.entries(result)) if(value.description) value.description = value.description.substring(0,20) + '...'; res.status(201).json(result); } catch(err) { return res.status(500).json({error: err.message}); } }; export async function findUsersByRole(req: Request, res: Response){ const role = fixString(req.params.role) console.log(role) try{ const user = await getManager() .createQueryBuilder(User,"user") .where("user.role like :name", {name:`%${role}%`}) .select('user.displayUsername') .addSelect('user.profileImage') .addSelect('user.role') .orderBy('username','ASC') .limit(20).offset(+req.params.offset) .getMany(); const result = deleteUserInSearch(user, req['user'].username) res.status(201).json(result); } catch(err) { return res.status(500).json({error: err.message}); } }; export async function findUsers(req: Request, res: Response){ try{ const user = await getManager() .createQueryBuilder(User,"user") .where("user.username like :name", { name:`%${req.params.username.toLocaleLowerCase()}%`}) .select('user.displayUsername') .addSelect('user.profileImage') .orderBy('username','ASC') .limit(20).offset(+req.params.offset) .getMany(); const result = deleteUserInSearch(user, req['user'].username) res.status(201).json(result); } catch(err) { return res.status(500).json({error: err.message}); } }; export async function countNotifications(req: Request, res: Response){ try{ const notification = await getManager() .getRepository(Notifications) .createQueryBuilder("notification") .where(`notification.userConnect = '${req['user'].id}'`) .andWhere('notification.read = false') .getCount() res.status(201).json(notification); } catch(err) { return res.status(500).json({error: err.message}); } }; export async function getNotifications(req: Request, res: Response){ try{ const notification = await getManager() .getRepository(Notifications) .createQueryBuilder("notification") .where(`notification.userConnect = '${req['user'].id}'`) .leftJoinAndSelect("notification.user", 'user') .orderBy('notification.id','DESC') .limit(5) .getMany() const info = deeplyFilterUser(notification, req['user'].username.toLocaleLowerCase()); await Notifications.update({ userConnect: req['user'].id, read: false },{ read: true }); res.status(201).json(info); } catch(err) { return res.status(500).json({error: err.message}); } }; //------------------------------- Notifications functions ----------------------------------- export async function addNotification (message: string, userId: string, postId: string, userConnect: string){ if(!(userConnect === userId)){ try{ const notification = new Notifications; notification.message = message; notification.postId = postId; notification.userConnect = userId; notification.user = userConnect; notification.read = false; await notification.save(); }catch(err){ console.log('error with the notification save on controller/globalPageRequest:',err.message); } } }; export function deleteUserInSearch(user:User[], username:string){ let users = [] for (let [ key, value ] of Object.entries(user)) if(value.displayUsername != username) users.push(value) return users; }<file_sep>/src/types.ts export interface UserInput { password: string; email: string; fullName: string; username: string; }; export interface PostInput { description: string; url: string; }; export interface CommentInput { content: string; postId: string; };<file_sep>/src/controller/recommendation.ts import { Request, Response } from 'express'; import _ from 'lodash'; import { getManager, In, Not } from 'typeorm'; import Follow from '../entity/follow'; import Post from '../entity/post'; import User from '../entity/user'; import { deeplyFilterUser } from './globalPagesRequests'; const AMOUNT = 20; export async function globalPostRecommendation(req: Request, res: Response){ try{ let result: Post[] = [] if(req.params.category != 'All'){ result = await getManager() .getRepository(Post) .createQueryBuilder("post") .leftJoinAndSelect('post.user', 'user') .where("user.id NOT IN ("+ getMyFollow(req['user'].id).getQuery()+ ")") .andWhere(`user.id != '${req['user'].id}'`) .andWhere('user.isPrivate = false') .andWhere("post.category like :category", { category:`%${req.params.category}%`}) .limit(AMOUNT * 2) .offset(+req.params.offset) .distinct(true) .getMany(); } else{ result = await getManager() .getRepository(Post) .createQueryBuilder("post") .leftJoinAndSelect('post.user', 'user') .where("user.id NOT IN ("+ getMyFollow(req['user'].id).getQuery()+ ")") .andWhere(`user.id != '${req['user'].id}'`) .andWhere('user.isPrivate = false') .limit(AMOUNT * 2) .offset(+req.params.offset) .distinct(true) .getMany(); } const info = deeplyFilterUser(result, req['user'].username.toLocaleLowerCase()); res.status(201).json(info); } catch(err) { return res.status(500).json({error: err.message}); } } export async function globalUsersRecommendation(req: Request, res: Response){ try{ const result = await getUsersByRole(req['user'].id); if(result.length != 0){ const info = result.map(user=> _.pick(user, ['id', 'displayUsername', 'profileImage', 'role'])) res.status(201).json(info); } else{ const result = await getUsersByMostFollowers(); res.status(201).json(result); } } catch(err) { return res.status(500).json({error: err.message}); } } //------------------------------- Query functions ----------------------------------- async function getUsersByRole(id: string){ const result = await getManager() .getRepository(User) .createQueryBuilder("user") .leftJoinAndSelect(Follow, 'f', 'user.id = f.userId') .where("user.id IN (" + getFollowersOfMyFollowers(id).getQuery() + ")"+ "AND user.id NOT IN ("+ getMyFollow(id).getQuery()+ ")") .orWhere("user.role IN (" + getFollowersByRole(id).getQuery() + ")" + `AND user.id != '${id}'` + "AND user.id NOT IN ("+ getMyFollow(id).getQuery()+ ")") .limit(AMOUNT * 2) .distinct(true) .getMany(); return result; } async function getUsersByMostFollowers(){ const result = await User.find({ where: { id: In(await countFollowers()) }, take: AMOUNT * 2, select: ['id', 'displayUsername', 'profileImage', 'role'] }) return result; } //------------------------------- Sub Query functions ----------------------------------- async function countFollowers(){ const followers = await getManager() .createQueryBuilder(Follow, 'follow') .select("follow.userId") .addSelect('COUNT(*)', 'followers') .limit(AMOUNT) .distinct(true) .groupBy('follow.userId') .orderBy('followers','DESC') .getRawMany(); const arr: Array<string> = []; followers.map(k=> arr.push(k.userId)) return arr; } function getMyFollow(id: string){ return getManager() .createQueryBuilder(Follow, 'follow') .where(`follow.followerId = '${id}'`) .select("follow.userId") .limit(AMOUNT) .distinct(true); } function getFollowersByRole(id: string){ return getManager() .createQueryBuilder(Follow, 'follow') .leftJoinAndSelect(User, 'user', 'user.id = follow.userId') .select('user.role', 'role') .where(`follow.followerId = '${id}'`) .limit(AMOUNT) .distinct(true); } function getFollowers(id: string){ return getManager() .createQueryBuilder(Follow, 'follow') .where(`follow.followerId = '${id}'`) .select("follow.userId") .limit(AMOUNT) .distinct(true) } function getFollowersOfMyFollowers(id: string){ return getManager() .createQueryBuilder(Follow, 'follow') .where("follow.followerId IN (" + getFollowers(id).getQuery() + ")") .andWhere(`follow.userId != '${id}'`) .select("follow.userId") .limit(AMOUNT) .distinct(true) }<file_sep>/src/controller/userPageRequests.ts import { Request, Response } from 'express'; import User from '../entity/user'; import Post from '../entity/post'; import Like from '../entity/likes'; import _ from 'lodash'; import { getManager } from 'typeorm'; import * as validate from '../validate/postAndComment'; import Follow from '../entity/follow'; import { addNotification } from './topBarRequest'; const AMOUNT = 20; // Main function to get user's page export async function getUserPage(req: Request, res: Response){ try{ const user = await getManager() .getRepository(User) .createQueryBuilder("user") .leftJoinAndSelect("user.post", "p") .leftJoinAndMapOne('user.follow', Follow, 'f', `f.follower = '${req['user'].id}' and f.user = user.id`) .leftJoinAndMapOne('p.like', Like, 'like', `like.user = '${req['user'].id}' and p.id = like.post`) .orderBy('p.id','DESC').limit(AMOUNT) .where(`user.username = '${req.params.username.toLocaleLowerCase()}'`) .loadRelationCountAndMap("user.followers", "user.follow") .loadRelationCountAndMap("user.posts", "user.post") .loadRelationCountAndMap('p.comments', 'p.comment') .loadRelationCountAndMap('p.likes', 'p.like').getMany(); if(user) { const data = fixData(user, req['user'].id); res.status(200).json(data); } else res.status(404).json("Could not find any user"); } catch(err) { res.status(500).json({error: err.message}); } }; // Main function to get user's page when scrolling down export async function getMoreUserPost(req: Request, res: Response){ try{ const data = await getManager() .getRepository(Post) .createQueryBuilder("post") .leftJoin("post.user", "user", 'user.id = post.userId') .leftJoin('user.follow','follow', 'user.id = follow.userId') .leftJoinAndMapOne('post.like', Like, 'like', `like.user = '${req['user'].id}' and post.id = like.post`) .where(`follow.followerId = '${req['user'].id}' AND user.username = '${req.params.username.toLocaleLowerCase()}'`) .orWhere(`user.username = '${req.params.username.toLocaleLowerCase()}' AND post.userId = '${req['user'].id}' AND user.id = '${req['user'].id}'`) .distinct(true) .limit(AMOUNT).offset(+req.params.offset) .orderBy('post.id','DESC') .loadRelationCountAndMap('post.comments', 'post.comment') .loadRelationCountAndMap('post.likes', 'post.like').getMany(); res.status(201).send(data); }catch(err) { return res.status(500).json({error: err.message}); } }; // Create new post function export async function addPost(req: Request, res: Response){ // Validate the data const { error } = validate.addPostValidation(req.body); if (error) return res.status(400).json({error: error.details[0].message}); try{ await createPost(req.body, req['user'].id).save(); res.status(201).send(); }catch(err) { return res.status(500).json({error: err.message}); } }; // Add new follower export async function addOrDeleteFollower(req: Request, res: Response){ let follow : Follow; try{ follow = await Follow.findOne({ where: { follower: req['user'].id, user: req.params.userToFollowId }}); } catch(err) { return res.status(500).json({error: err.message}); } if(!follow){ try{ await createFollower(req['user'].id, req.params.userToFollowId).save(); res.status(201).send(); }catch(err) { return res.status(500).json({error: err.message}); } } else { await Follow.remove(follow); res.status(201).send(); } if(!follow){ const message = `${req['user'].username} is following you`; addNotification(message, req.params.userToFollowId, null, req['user'].id); } }; // Delete one post of user export async function deletePost(req: Request, res: Response){ try{ await Post.delete({id: req.params.postId, user: req['user'].id}) res.status(201).send(); }catch(err) { return res.status(500).json({error: err.message}); } }; // Delete one post of user export async function getFollowers(req: Request, res: Response){ try{ const subQ = getManager() .createQueryBuilder(User,"user") .leftJoinAndSelect(Follow,'f', 'user.id = f.userId') .where(`user.username = '${req.params.username.toLocaleLowerCase()}'`) .limit(20).offset(+req.params.offset) .select('f.follower') const result = await getManager() .getRepository(User) .createQueryBuilder("user") .where("user.id IN (" + subQ.getQuery() + ")") .select('user.displayUsername') .addSelect('user.profileImage') .distinct(true) .getMany() res.status(201).send(result); }catch(err) { return res.status(500).json({error: err.message}); } }; //------------------------------- Create functions ----------------------------------- function fixData(user: User[], id: string){ fixDate(user); const blackList = ['password', 'follow', 'username'] let data = []; const isMe = user[0].id == id; data.push(isMe); data.push(user[0].follow || isMe ? true : false); data.push(user[0].follow || isMe || !user[0].isPrivate? _(user[0]).pickBy((v, k) => !blackList.includes(k)).value() : _(user[0]).pickBy((v, k) => !blackList.includes(k) && k != "post").value() ); return data; } function fixDate(data: Array<any>){ for(let date of data[0].post) if(date.createdAt) date.createdAt = date.createdAt.toLocaleString() } function createPost (body: Post, id: string){ const post = new Post; post.description = body.description; post.url = body.url; post.category = body.category; post.user = id; return post; } function createFollower(userId: string, followingId: string){ const follow = new Follow; follow.follower = userId; follow.user = followingId; return follow; }<file_sep>/test/utilities/apiFunctions.ts import request from "supertest"; import app from '../../src/server'; import { UserInput } from "../../src/types"; export async function loginRequest (body: Pick<UserInput, 'username' | 'password'>){ return await request(app).post("/login").send(body); }; export async function registerRequest (body: UserInput){ return await request(app).post("/register").send(body); }; export async function googleRequest (body: {name: string, email: string}){ return await request(app).post("/googlelogin").send(body); }; export async function resetPasswordRequest (body: {email: string}){ return await request(app).post("/resetpass").send(body); }; export async function addPostRequest (body: {description: string, url: string}, token: string){ if(token) return await request(app).post("/user/addpost").set('auth_token', token).send(body); else return await request(app).post("/user/addpost").send(body); }; export async function getUserRequest (token: string, username: string){ if(token) return await request(app).get(`/user/${username}`).set('auth_token', token).send(); else return await request(app).get(`/user/${username}`).send(); }; <file_sep>/src/entity/user.ts import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, OneToMany } from "typeorm"; import Post from './post'; import Follow from './follow'; import Comment from './comment'; import Like from './likes'; import Message from './messages'; import Notifications from './notifications'; @Entity("users") export default class User extends BaseEntity { @PrimaryGeneratedColumn("uuid") id: string; @Column() fullName: string; @Column({ unique: true }) email: string; @Column({ unique: true }) username: string; @Column() displayUsername: string; @Column() profileImage: string; @Column() themeImage: string; @Column({ nullable: true }) password: string; @Column() isPrivate: boolean; @Column({ nullable: true }) price: number; @Column({nullable: true}) role: string; @Column({ nullable: true }) bio: string; @OneToMany(() => Post, (post: Post) => post.user, {cascade: true}) post: Array<Post>; @OneToMany(() => Follow, (follow: Follow) => follow.user, {cascade: true}) follow: Array<Follow>; @OneToMany(() => Follow, (follow: Follow) => follow.follower, {cascade: true}) follower: Array<Follow>; @OneToMany(() => Comment, (comment: Comment) => comment.user, {cascade: true}) comment: Array<Comment>; @OneToMany(() => Like, (like: Like) => like.user, {cascade: true}) like: Array<Like>; @OneToMany(() => Message, (message: Message) => message.sender, {cascade: true}) messageSend: Array<Message>; @OneToMany(() => Notifications, (notifications: Notifications) => notifications.user, {cascade: true}) notifications: Array<Notifications>; @OneToMany(() => Message, (message: Message) => message.recipient , {cascade: true}) messageRecipient : Array<Message>; }<file_sep>/test/userPost.test.ts import dotenv from 'dotenv'; dotenv.config(); import { getConnection } from "typeorm" import User from '../src/entity/user'; import { initLocalStorage } from '../src/storage'; import { loginRequest, registerRequest, addPostRequest } from './utilities/apiFunctions'; import { createFullUserDetails } from './utilities/utilitiesFunctions'; const post = { description: "superman", url: "some url.com" }; describe("User page request - add post functions", () =>{ beforeAll(async() =>{ try{ await initLocalStorage(); } catch(e){ console.log(e); }; }); afterAll(async () =>{ try{ await getConnection() .createQueryBuilder() .delete() .from(User).execute(); } catch(e){ console.log(e); } }); test("When post not connected respond with a status code of 401", async () => { const result = await addPostRequest(post, null); expect(result.statusCode).toBe(401); expect(result.text).toBe("{\"error\":\"Access Denide\"}" ); }); test("When post, respond with a status code of 201", async () => { const body = createFullUserDetails(); const registerRes = await registerRequest(body) expect(registerRes.statusCode).toBe(200); const user = { username: body.username, password: <PASSWORD> }; const loginRes = await loginRequest(user) expect(loginRes.statusCode).toBe(200) const result = await addPostRequest(post, loginRes.body['UserInfo'].auth_token); expect(result.statusCode).toBe(201); }); test("When post with content null in the post, respond with a status code of 400", async () => { const body = createFullUserDetails(); const registerRes = await registerRequest(body) expect(registerRes.statusCode).toBe(200); const user = { username: body.username, password: <PASSWORD> }; const loginRes = await loginRequest(user) expect(loginRes.statusCode).toBe(200) post.description = null; const result = await addPostRequest(post, loginRes.body['UserInfo'].auth_token); expect(result.statusCode).toBe(400); expect(result.text).toBe("{\"error\":\"\\\"description\\\" must be a string\"}"); }); test("When post with content empty in the post, respond with a status code of 400", async () => { const body = createFullUserDetails(); const registerRes = await registerRequest(body) expect(registerRes.statusCode).toBe(200); const user = { username: body.username, password: <PASSWORD> }; const loginRes = await loginRequest(user) expect(loginRes.statusCode).toBe(200) post.description = ""; const result = await addPostRequest(post, loginRes.body['UserInfo'].auth_token); expect(result.statusCode).toBe(400); expect(result.text).toBe("{\"error\":\"\\\"description\\\" is not allowed to be empty\"}"); }); });<file_sep>/test/utilities/utilitiesFunctions.ts import { faker } from '@faker-js/faker' export function createFullUserDetails (){ return({ username: faker.internet.userName().toLocaleLowerCase(), password: <PASSWORD>(), fullName: faker.name.findName(), email: faker.internet.email() }) };<file_sep>/src/mailer/passverification.ts import nodemailer from 'nodemailer'; import jwt from 'jsonwebtoken'; import { UserInput } from '../types'; export async function passResetMail(user: UserInput & { id: string }) { const newSecret = process.env.TOKEN_SECRET + user.password; const userInfo = { email: user.email, id: user.id }; const token = jwt.sign(userInfo, newSecret, { expiresIn: '10m'}); const transporter = nodemailer.createTransport({ service: process.env.EMAIL_SERVICE, auth: { user: process.env.WEBSITE_EMAIL, pass: process.env.EMAIL_PASS } }); const mailOptions = { from: process.env.WEBSITE_EMAIL, to: user.email, subject: 'Reset your password', html: `<h1> Webol</h1> <h2>Reset your password</h2> <h4> Hi ${user.fullName} </h4> <h4>Let's reset your password so you can get back to learn some more amazing things</h4> <p>kindly use this <a href="https://webol-front.herokuapp.com/resetpass/${user.id}/${token}"> link</a> to verify your email address</p> <p>always here to help, Webol</p>` }; return await transporter.sendMail(mailOptions); }; <file_sep>/src/token/verifyToken.ts import jwt from 'jsonwebtoken'; import { Request, Response, NextFunction } from 'express'; import User from '../entity/user'; // Middleware to check if the user is connected export async function connect(req: Request, res: Response, next: NextFunction) { const token = req.header('auth_token'); if (!token) return res.status(401).json({error: 'Access Denide'}); try{ req['user'] = jwt.verify(token, process.env.TOKEN_SECRET); if(req['user']) next(); else res.status(401).json({error: 'Access Denide'}); } catch (err) { res.status(401).json({error: 'Access Denide'}); } } // Middleware for new password, special link with special token to decrypt export async function resetPassToken(req: Request, res: Response, next: NextFunction) { const token = req.header('mail_token'); if (!token) return res.status(401).json({error: "Access Denied"}); let user: User; try{ user = await User.findOne({where: {id: req.body.id}, select : ['password']}); } catch(err) { return res.status(500).json({error: err.message}); } if (user){ const newSecret = process.env.TOKEN_SECRET + user.password; try{ const userInfo = jwt.verify(token, newSecret); if(userInfo){ req['user'] = userInfo; next(); } else return res.status(401).json({error: 'This link was expired'}); } catch { return res.status(401).json({error: 'This link was expired'}); } } else { res.status(500).json({error: 'Could not find the user'}); }; };<file_sep>/src/routes/paypal.ts import * as express from 'express'; import * as controller from '../controller/paypal'; import * as verify from '../token/verifyToken'; const router = express.Router(); // ----------- Auth Post Routes ----------- //router.post('/sendmessage', verify.connect, controller.sendMessages); // ----------- Auth Get Routes ----------- router.get('/sign', verify.connect, controller.signToWebol); export default router;<file_sep>/src/controller/messages.ts import { Request, Response } from 'express'; import _ from 'lodash'; import { getManager } from 'typeorm'; import Messages from '../entity/messages'; import User from '../entity/user'; import { deeplyFilterUser } from './globalPagesRequests'; const AMOUNT = 20; export async function checkMessages(req: Request, res: Response){ try{ const message = await getManager() .getRepository(Messages) .createQueryBuilder("message") .where(`message.recipient = '${req['user'].id}'`) .andWhere('message.read = false') .getCount() res.status(201).json(message); } catch(err) { return res.status(500).json({error: err.message}); } } export async function getUsersUnreadMessages(req: Request, res: Response){ try{ const unreadMessages = await getReadMessages(req['user'].id, false); const readMessages = await getReadMessages(req['user'].id, true); let final = readMessages.length > 0 ? unreadMessages.concat(readMessages) : unreadMessages final = _.uniqBy(final, 'id'); return res.status(201).json(final); } catch(err) { return res.status(500).json({error: err.message}); } } export async function sendMessages(req: Request, res: Response){ try{ if(req.body.recipient != req['user'].id) await createMessage(req.body, req['user'].id).save(); res.status(201).send(); } catch(err) { return res.status(500).json({error: err.message}); } } export async function getMessages(req: Request, res: Response){ try{ const result = await getManager() .getRepository(Messages) .createQueryBuilder("message") .leftJoinAndSelect("message.sender", 'sender') .where(`message.recipient = '${req['user'].id}' AND message.sender = '${req.params.senderId}'`) .orWhere(`message.recipient = '${req.params.senderId}' AND message.sender = '${req['user'].id}'`) .orderBy('message.id','DESC') .limit(AMOUNT).offset(+req.params.offset) .getMany() const info = deeplyFilterUser(result, req['user'].username.toLocaleLowerCase()); await Messages.update({ recipient: req['user'].id, sender: req.params.senderId, read: false },{ read: true }); res.status(201).json(info); } catch(err) { return res.status(500).json({error: err.message}); } } export async function leaveConversation(req: Request, res: Response){ try{ await Messages.update({ recipient: req['user'].id, sender: req.params.senderId, read: false },{ read: true }); res.status(201).json(); } catch(err) { return res.status(500).json({error: err.message}); } } //------------------------------- Create functions ----------------------------------- function createMessage (body: Messages, senderId: string){ const message = new Messages; message.read = false; message.recipient = body.recipient; message.sender = senderId; message.message = body.message; return message; } //------------------------------- Query functions ----------------------------------- async function getReadMessages(id: string, bool: Boolean){ const subQ = getManager() .getRepository(Messages) .createQueryBuilder("message") .leftJoinAndSelect("message.sender", "user") .where(`message.recipient = '${id}' AND message.read = ${bool}`) .select("message.sender", "id").distinct(true) const subQ1 = getManager() .getRepository(Messages) .createQueryBuilder("message") .leftJoinAndSelect("message.sender", "user") .where(`message.sender = '${id}' AND message.read = ${bool}`) .select("message.recipient", "id").distinct(true) const result = await getManager() .getRepository(User) .createQueryBuilder("user") .leftJoinAndSelect("user.messageSend", 'mes') .where("user.id IN (" + subQ.getQuery() + ")") .orWhere("user.id IN (" + subQ1.getQuery() + ")") .loadRelationCountAndMap('user.messages', 'user.messageSend', 'messages', (qb) => qb.where(`messages.recipient = '${id}' AND messages.read IS false`)) .select('user.id') .addSelect('user.displayUsername') .addSelect('user.profileImage') .orderBy('mes.id','DESC') .getMany() return result; }<file_sep>/src/routes/userSetting.ts import * as express from 'express'; import * as controller from '../controller/userSettingsRequest'; import * as verify from '../token/verifyToken'; const router = express.Router(); // ----------- Auth Post Routes ----------- router.post('/userimage/:image', verify.connect, controller.updateUserImage); router.put('/updatesettings', verify.connect, controller.updateSettings); router.put('/updateprivatesettings', verify.connect, controller.updateUserPrivateSetting); router.put('/updateuserprice', verify.connect, controller.updateUserPrice); // ----------- Auth Get Routes ----------- router.get('/userinfo', verify.connect, controller.getUserInfo); router.get('/profileinfo', verify.connect, controller.getProfileInfo); router.get('/updaterole/:role', verify.connect, controller.updateRole); router.get('/getroles/:role/:offset', verify.connect, controller.getRoles); export default router;<file_sep>/src/routes/topBar.ts import * as express from 'express'; import * as controller from '../controller/topBarRequest'; import * as verify from '../token/verifyToken'; const router = express.Router(); // ----------- Auth Get Routes ----------- router.get('/getnotification', verify.connect, controller.getNotifications); router.get('/getcountnotification', verify.connect, controller.countNotifications); router.get('/findusers/:username/:offset', verify.connect, controller.findUsers); router.get('/findroles/:role/:offset', verify.connect, controller.findUsersByRole); router.get('/findposts/:description/:offset', verify.connect, controller.findPosts); // ----------- Auth Delete Routes ----------- export default router;<file_sep>/src/entity/likes.ts import { BaseEntity, Entity, PrimaryGeneratedColumn, ManyToOne, Index } from "typeorm"; import Post from './post'; import User from "./user"; @Entity("likes") export default class Likes extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Index() @ManyToOne(() => User, (user: User) => user.like, {onDelete: "CASCADE", onUpdate: "CASCADE"}) user: string; @Index() @ManyToOne(() => Post, (post: Post) => post.like, {onDelete: "CASCADE", onUpdate: "CASCADE"}) post: string; };<file_sep>/src/controller/signInSignUp.ts import bcrypt from 'bcryptjs'; import jwt from 'jsonwebtoken'; import * as validate from '../validate/registerValidate'; import * as passEmailVer from '../mailer/passverification'; import { Request, Response } from 'express'; import User from '../entity/user'; const genUsername = require("unique-username-generator"); export async function registerPosts(req: Request, res: Response){ // Validate the data const { error } = validate.registerValidation(req.body); if (error) return res.status(400).json({error: error.details[0].message}); try{ // Check if user is in DB const result = await User.findOne({ where: [ { email: req.body.email.toLocaleLowerCase().trim() }, { username: req.body.username.toLocaleLowerCase().trim() } ], select: ['username', 'email'] }); if (result) { if(result.email == req.body.email) return res.status(400).json({error: "Email is already exist"}); else return res.status(400).json({error: "Username is already exist"}); } } catch(err){ return res.status(500).json({error: err.message}); } // Hash the password const salt = await bcrypt.genSalt(12); const hashpass = await bcrypt.hash(req.body.password, salt); // Create user for DB const { fullName, email, username } = req.body; const user = createUser(fullName, email, username); user.password = <PASSWORD>; // Save the user in DB try{ await user.save(); res.status(200).json({message: "Sign up successfully"}); } catch(err) { res.status(500).json({error: err.message}); } }; export async function logInPost(req: Request, res: Response){ // Validate the data const { error } = validate.loginValidation(req.body); if (error) return res.status(400).json({error: "Email or Password are incorrect"}); let result: User; try{ // Check if user is in DB result = await User.findOne({ where: [ { email: req.body.username.toLocaleLowerCase().trim() }, { username: req.body.username.toLocaleLowerCase().trim() } ], select: ['id', 'password', 'displayUsername', 'profileImage'] }); } catch(err) { return res.status(500).json({error: err.message}); } try{ if(result && await bcrypt.compare(req.body.password, result.password)){ const token = createToken(result.id, result.displayUsername); const UserInfo = { id: result.id, profileImage: result.profileImage, username: result.displayUsername, auth_token: token }; return res.status(200).json(UserInfo); } else{ return res.status(403).json({error: "Email or Password are incorrect"}); } }catch(err){ return res.status(403).json({error: err}); } }; export async function googleLogIn(req: Request, res: Response){ let user: User; // Create a user try{ user = await User.findOne({ where:{email: req.body.email.trim()}, select:['id', 'displayUsername', 'profileImage'] }); if(!user){ // Generate username const username = await userNameGenerator(req.body.email); // Save user in DB const { name, email } = req.body; const user = createUser(name, email, username); user.password = jwt.sign(email, process.env.TOKEN_SECRET) await user.save(); }; } catch(err) { return res.status(500).json({error: err.message}); }; if(!user){ try{ user = await User.findOne({ where:{ email: req.body.email.toLocaleLowerCase().trim() }, select: ['id', 'displayUsername', 'profileImage'] }); } catch(err) { return res.status(500).json({error: err.message}); } }; if(user){ const token = createToken(user.id, user.displayUsername); const UserInfo = { id: user.id, profileImage: user.profileImage, username: user.displayUsername, auth_token: token }; res.status(200).json(UserInfo); } else{ res.status(404).send(); } }; export async function passwordReset(req: Request, res: Response){ // Validate the data const { error } = validate.emailValidation(req.body); if (error) return res.status(400).json({error: "Email is not valid"}); let user: User; try{ user = await User.findOne({ where: { email: req.body.email.toLocaleLowerCase().trim() }, select: ['id', 'fullName', 'email', 'password'] }); } catch(err) { return res.status(500).json({error: err.message}); } try{ await passEmailVer.passResetMail(user); res.status(200).json({message:"Email send"}); }catch(error){ res.status(400).json({error:"User did not found"}); } }; export async function passUpdate(req: Request, res: Response){ const pass = { password: <PASSWORD> }; // Validate the data const { error } = validate.passwordValidation(pass); if (error){ return res.status(400).json({error: error.details[0].message}); } if (req.body.password == req.body.passwordConfirm){ // Hash the password const salt = await bcrypt.genSalt(12); const hashpass = await bcrypt.hash(req.body.password, salt); try{ await User.update({ id: req.body.id },{ password: <PASSWORD> }); res.status(200).send(); } catch(err) { return res.status(500).json({error: err.message}); } } else{ res.status(400).json({error: "The password must be equal"}); } }; //------------------------------- Create functions ----------------------------------- async function userNameGenerator(email: string){ let username: string; let tempUser: Pick<User, 'username'>; do { username = genUsername.generateFromEmail(email, 5); tempUser = await User.findOne({ where:{username: username}, select: ['username'] }); } while (tempUser); return username; }; function createUser(fullName: string, email: string, username: string){ const user = new User(); user.fullName = fullName; user.email = email.toLocaleLowerCase(); user.username = username.toLocaleLowerCase(); user.displayUsername = username; user.isPrivate = false; user.profileImage = process.env.PROFILE_IMAGE; user.themeImage = process.env.THEME_IMAGE; return user; }; export function createToken(id: string, username: string){ const tokenUser = { id: id, username: username }; return (jwt.sign(tokenUser, process.env.TOKEN_SECRET)); };<file_sep>/src/storage.ts import { createConnection } from "typeorm"; export async function initStorage() { await createConnection({ type: 'postgres', host: process.env.PG_HOST, port: parseInt(process.env.PG_PORT), username: process.env.PG_USER, password: <PASSWORD>, database: process.env.PG_USER, entities: [ __dirname + '/entity/*{.ts,.js}' ], synchronize: true, //logging: true }) }; export async function initLocalStorage() { await createConnection({ type: 'postgres', host: process.env.PG_HOST_LOCAL, port: parseInt(process.env.PG_PORT_LOCAL), username: process.env.PG_USER_LOCAL, password: <PASSWORD>, database: process.env.PG_DB_LOCAL, entities: [ __dirname + '/entity/*{.ts,.js}' ], synchronize: true, //logging: true }) }; <file_sep>/src/controller/globalPagesRequests.ts import { Request, Response } from 'express'; import Comment from '../entity/comment'; import _ from 'lodash'; import * as validate from '../validate/postAndComment'; import Likes from '../entity/likes'; import { getManager } from 'typeorm'; import { CommentInput } from '../types' import Post from '../entity/post'; import Like from '../entity/likes'; import User from '../entity/user'; import Follow from '../entity/follow'; import { addNotification } from './topBarRequest'; import Categories from '../entity/categories'; const AMOUNT = 20; export async function getHomePage(req: Request, res: Response){ try{ const subQ = getManager() .createQueryBuilder(User,"user") .leftJoinAndSelect(Follow, 'f', 'user.id = f.followerId') .select('f.userId') .where(`user.id = '${req['user'].id}'`); const result = await getManager() .getRepository(Post) .createQueryBuilder("post") .leftJoinAndSelect("post.user", "u") .where("post.user IN (" + subQ.getQuery() + ")") .orWhere(`post.user = '${req['user'].id}'`) .leftJoinAndMapOne('post.like', Like, 'like', `like.user = '${req['user'].id}' and post.id = like.post`) .loadRelationCountAndMap('post.comments', 'post.comment') .loadRelationCountAndMap('post.likes', 'post.like') .orderBy('post.id','DESC') .limit(AMOUNT).offset(+req.params.offset) .distinct(true) .getMany() if(result){ const info = deeplyFilterUser(result, req['user'].username.toLocaleLowerCase()); res.status(201).json(info); } else res.status(200).send(); } catch(err){ return res.status(500).json({error: err.message}); } }; export async function addOrDeleteLike(req: Request, res: Response){ let like : Likes; try{ like = await Likes.findOne({ where: { user: req['user'].id, post: req.params.postId }}) } catch(err) { return res.status(500).json({error: err.message}); } if(!like){ try{ const like = new Likes like.user = req['user'].id; like.post = req.params.postId; await like.save(); res.status(201).send(); }catch(err) { return res.status(500).json({error: err.message}); } }else{ await Likes.remove(like); res.status(201).send(); } if(!like){ const message = `${req['user'].username} liked your post`; addNotification(message, req.params.userId, req.params.postId, req['user'].id); } }; export async function addComment(req: Request, res: Response){ // Validate the data const { error } = validate.addCommentValidation(req.body); if (error) return res.status(400).json({error: error.details[0].message}); try{ await createComment(req.body, req['user'].id).save() res.status(201).send(); }catch(err) { return res.status(500).json({error: err.message}); } const message = `${req['user'].username} comment your post`; addNotification(message, req.body.userId, req.body.postId, req['user'].id); }; export async function getComments(req: Request, res: Response){ try{ const user = await getManager() .getRepository(Post) .createQueryBuilder("post") .leftJoinAndSelect("post.user", "u") .leftJoinAndSelect("post.comment", "c") .where(`post.id = '${req.params.postId}'`) .leftJoinAndMapOne('c.user', User, 'user', `c.user = user.id`) .leftJoinAndMapOne('post.like', Like, 'like', `like.user = '${req['user'].id}' and post.id = like.post`) .orderBy('c.id','DESC') .loadRelationCountAndMap("post.comments", "post.comment") .loadRelationCountAndMap('post.likes', 'post.like') .distinct(true) .limit(AMOUNT).getMany() if(user[0]){ const result = deeplyFilterUser(user[0], req['user'].username.toLocaleLowerCase()); res.status(200).json(result); } else res.status(200).send(); } catch(err) { res.status(500).json({error: err.message}); } }; export async function getLikes(req: Request, res: Response){ try{ const data = await getManager() .getRepository(Likes) .createQueryBuilder("likes") .leftJoinAndSelect("likes.user", "u") .orderBy('likes.id','DESC') .limit(AMOUNT).offset(+req.params.offset) .where(`likes.post = '${req.params.postId}'`) .select('u.displayUsername', 'displayUsername') .addSelect('u.profileImage', 'profileImage') .execute() if(data[0]) res.status(200).json(data); else res.status(200).send(); } catch(err) { res.status(500).json({error: err.message}); } }; export async function deleteComment(req: Request, res: Response){ try{ await Comment.delete({id: req.params.commentId, user: req['user'].id}) res.status(200).send(); } catch(err) { return res.status(500).json({error: err.message}); } }; export async function getCategories(req: Request, res: Response){ const stringCategory = fixString(req.params.category) try{ const category = await getManager() .createQueryBuilder(Categories,"categories") .where("categories.name = 'General'") .orWhere("categories.name like :name", { name:`%${stringCategory}%`}) .select('categories.name') .orderBy('name','ASC') .limit(AMOUNT).offset(+req.params.offset) .distinct() .getMany(); const arr: Array<string> = []; category.map(k=> arr.push(k.name)) res.status(200).json(arr); } catch(err) { return res.status(500).json({error: err.message}); } }; //------------------------------- Create functions ----------------------------------- function createComment (body: CommentInput, id: string){ const comment = new Comment; comment.content = body.content; comment.post = body.postId; comment.user = id; return comment; } function filterUser(user: User) { return _.pick(user, ['id', 'displayUsername', 'profileImage']); } function filterisMe(user: string, name:string) { return user === name? true : false; } export function deeplyFilterUser(obj: Object, username: string) { const clonedObj = _.cloneDeep(obj); for (let [ key, value ] of Object.entries(clonedObj)) { if(key === 'createdAt') clonedObj[key] = value.toLocaleString(); else if (key === 'user' || key === 'sender'){ clonedObj[key] = filterUser(value); clonedObj['isMe'] = filterisMe(value.username, username) } else if (_.isObject(value)) clonedObj[key] = deeplyFilterUser(value, username); else if (_.isArray(value)) clonedObj[key] = value.map(v => deeplyFilterUser(v, username)); } return clonedObj; } //------------------------------- Utilities functions ----------------------------------- export function fixString(str: String) { var tempString: String if(str) tempString = str.charAt(0).toUpperCase() if(str.length > 1) tempString += str.slice(1) return tempString; }<file_sep>/src/server.ts import express, { Response, Request } from 'express'; import cors from 'cors'; import { getConnection } from "typeorm" // Creat the Express application const app = express(); app.use(express.json()); app.use(express.urlencoded({extended: true})); app.use(cors({credentials: true, origin: '*'})); //app.use(cors({credentials: true, origin: ''})); // Fetch all the routes for the application import signInSignUp from './routes/signInSignUp'; import userRequest from './routes/userRequest'; import globalRequest from './routes/globalRequest'; import userSettings from './routes/userSetting'; import topBar from './routes/topBar'; import messages from './routes/messages'; import s3 from './routes/s3'; import paypal from './routes/paypal'; import recommendation from './routes/recommendation'; function errHandler(req: Request, res: Response){ res.status(404).json({error: "Sorry could not find the page"}); } // Routes app.use('/s3', s3); app.use('/topbar', topBar); app.use('/', signInSignUp); app.use('/paypal', paypal); app.use('/user', userRequest); app.use('/message', messages); app.use('/update', userSettings); app.use('/global', globalRequest); app.use('/recommendation', recommendation); //Get all the err without crash app.use(errHandler); async () =>{ await getConnection().close(); }; export default app;<file_sep>/src/validate/userValidate.ts import Joi from '@hapi/joi'; export function userNameValidation(data : {username: string}) { const schema = Joi.object({ username: Joi.string().required() }); return schema.validate(data); }; export function fullNameValidation(data : {fullName: string}) { const schema = Joi.object({ fullName: Joi.string().required().max(30) }); return schema.validate(data); }; export function addBioValidation(data : {bio:string}) { const schema = Joi.object({ bio: Joi.string().max(150) }); return schema.validate(data); }; export function newPasswordValidation(data : {password: string, newPassword: string, passwordConfirmation: string}) { const schema = Joi.object({ password: Joi.string() .required() .min(8), newPassword: Joi.string() .required() .min(8), passwordConfirmation: Joi.string() .required() .min(8) }); return schema.validate(data); };<file_sep>/src/entity/roles.ts import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, CreateDateColumn} from "typeorm"; @Entity("roles") export default class Roles extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Column() name: string; };<file_sep>/test/getUserPage.test.ts import dotenv from 'dotenv'; dotenv.config(); import { getConnection } from "typeorm" import User from '../src/entity/user'; import { initLocalStorage } from '../src/storage'; import { loginRequest, registerRequest, getUserRequest } from './utilities/apiFunctions'; import { createFullUserDetails } from './utilities/utilitiesFunctions'; const post = { description: "superman", url: "some url.com" }; describe("User page request - add post functions", () =>{ beforeAll(async() =>{ try{ await initLocalStorage(); } catch(e){ console.log(e); }; }); afterAll(async () =>{ try{ await getConnection() .createQueryBuilder() .delete() .from(User).execute(); } catch(e){ console.log(e); } }); test("When get try to get user page buy bot connected statuse code sould be 401", async () => { const body = createFullUserDetails(); const registerRes = await registerRequest(body) expect(registerRes.statusCode).toBe(200); const result = await getUserRequest(null, body.username); expect(result.statusCode).toBe(401); }); test("When get try to get my page and connect expect status code to be 200", async () => { const body = createFullUserDetails(); const registerRes = await registerRequest(body) expect(registerRes.statusCode).toBe(200); const user = { username: body.email, password: <PASSWORD> }; const loginRes = await loginRequest(user) expect(loginRes.statusCode).toBe(200) const result = await getUserRequest(loginRes.body['UserInfo'].auth_token, body.username); expect(result.statusCode).toBe(200); expect(result.body[0]).toBe(true); expect(result.body[1]).toBe(true); }); test("When get try to get someone page and connect but not following after", async () => { const body = createFullUserDetails(); const registerRes = await registerRequest(body) expect(registerRes.statusCode).toBe(200); const otherBody = createFullUserDetails(); const otherRegisterRes = await registerRequest(otherBody) expect(otherRegisterRes.statusCode).toBe(200); const user = { username: body.username, password: <PASSWORD> }; const loginRes = await loginRequest(user) expect(loginRes.statusCode).toBe(200) const result = await getUserRequest(loginRes.body['UserInfo'].auth_token, otherBody.username); expect(result.statusCode).toBe(200); expect(result.body[0]).toBe(false); expect(result.body[1]).toBe(false); }); test("When get try to get someone page and connect and following after", async () => { const body = createFullUserDetails(); const registerRes = await registerRequest(body) expect(registerRes.statusCode).toBe(200); const otherBody = createFullUserDetails(); const otherRegisterRes = await registerRequest(otherBody) expect(otherRegisterRes.statusCode).toBe(200); const user = { username: body.username, password: <PASSWORD> }; const loginRes = await loginRequest(user) expect(loginRes.statusCode).toBe(200) const result = await getUserRequest(loginRes.body['UserInfo'].auth_token, otherBody.username); expect(result.statusCode).toBe(200); expect(result.body[0]).toBe(false); expect(result.body[1]).toBe(false); // write to add follow function and call get getUserRequest again }); });<file_sep>/test/register.test.ts import dotenv from 'dotenv'; dotenv.config(); import { getConnection } from "typeorm" import { initLocalStorage } from '../src/storage'; import User from '../src/entity/user'; import { registerRequest } from './utilities/apiFunctions'; import { faker } from '@faker-js/faker'; describe("Register functions", () =>{ beforeAll(async() =>{ try{ await initLocalStorage(); } catch(e){ console.log(e); }; }); afterAll(async () =>{ try{ await getConnection() .createQueryBuilder() .delete() .from(User).execute(); } catch(e){ console.log(e); } }); test("When username is missing should respond with a status code of 400",async () => { const body = { username: "", password: <PASSWORD>(), fullName: faker.name.findName(), email: faker.internet.email() }; const registerRes = await registerRequest(body) expect(registerRes.text).toBe("{\"error\":\"\\\"username\\\" is not allowed to be empty\"}"); expect(registerRes.statusCode).toBe(400); }); // test("When password is missing should respond with a status code of 400",async () => { // const body = { // username: faker.internet.userName(), // password: "", // fullName: faker.name.findName(), // email: faker.internet.email() // }; // const registerRes = await registerRequest(body) // expect(registerRes.text).toBe("{\"error\":\"\\\"password\\\" is not allowed to be empty\"}"); // expect(registerRes.statusCode).toBe(400); // }); // test("When fullName is missing should respond with a status code of 400",async () => { // const body = { // username: faker.internet.userName(), // password: <PASSWORD>(), // fullName: "", // email: faker.internet.email() // }; // const registerRes = await registerRequest(body) // expect(registerRes.text).toBe("{\"error\":\"\\\"fullName\\\" is not allowed to be empty\"}"); // expect(registerRes.statusCode).toBe(400); // }); // test("When email is missing should respond with a status code of 400",async () => { // const body = { // username: faker.internet.userName(), // password: <PASSWORD>(), // fullName: faker.name.findName(), // email: "" // }; // const registerRes = await registerRequest(body) // expect(registerRes.text).toBe("{\"error\":\"\\\"email\\\" is not allowed to be empty\"}"); // expect(registerRes.statusCode).toBe(400); // }); // test("When password is to short should respond with a status code of 400",async () => { // const body = { // username: faker.internet.userName(), // password: "<PASSWORD>", // fullName: faker.name.findName(), // email: faker.internet.email() // }; // const registerRes = await registerRequest(body) // expect(registerRes.text).toBe("{\"error\":\"\\\"password\\\" length must be at least 8 characters long\"}"); // expect(registerRes.statusCode).toBe(400); // }); // test("When give correct data should respond with a status code of 200", async () => { // const body = { // username: faker.internet.userName(), // password: <PASSWORD>(), // fullName: faker.name.findName(), // email: faker.internet.email() // }; // const registerRes = await registerRequest(body) // expect(registerRes.statusCode).toBe(200); // expect(registerRes.text).toBe("{\"message\":\"Sign up successfully\"}"); // }); // test("When register with email that is already exist should respond with a status code 400", async () =>{ // const body = { // username: faker.internet.userName(), // password: <PASSWORD>(), // fullName: faker.name.findName(), // email: faker.internet.email() // }; // const registerRes = await registerRequest(body); // expect(registerRes.statusCode).toBe(200); // expect(registerRes.text).toBe("{\"message\":\"Sign up successfully\"}"); // const registerResult = await registerRequest(body) // expect(registerResult.statusCode).toBe(400); // expect(registerResult.text).toBe("{\"error\":\"Email is already exist\"}"); // }); });<file_sep>/src/controller/userSettingsRequest.ts import { Request, Response } from 'express'; import User from '../entity/user'; import bcrypt from 'bcryptjs'; import _ from 'lodash'; import * as validate from '../validate/userValidate'; import { createToken } from './signInSignUp'; import { fixString } from './globalPagesRequests'; import { getManager } from 'typeorm'; import Roles from '../entity/roles'; // get the user profile information export async function getUserInfo(req: Request, res: Response){ try{ const user = await User.findOne({where: {id: req['user'].id}, select : ['fullName', 'bio']}); res.status(201).send(user); } catch(err) { res.status(500).json({error: err.message}); } }; // get the user profile information export async function getProfileInfo(req: Request, res: Response){ try{ const user = await User.findOne({where: {id: req['user'].id}, select : ['role', 'isPrivate', 'price']}); res.status(201).send(user); } catch(err) { res.status(500).json({error: err.message}); } }; // Update the user profile image or theme image export async function updateUserImage(req: Request, res: Response){ try{ await User.update({ id: req['user'].id },{ [req.params.image]: req.body.imgurl }); res.status(201).send(); } catch(err) { res.status(500).json({error: err.message}); } }; export async function updateUserPrice(req: Request, res: Response){ try{ await User.update({ id: req['user'].id },{ price: +req.body.price }); res.status(201).send(); } catch(err) { res.status(500).json({error: err.message}); } }; export async function updateUserPrivateSetting(req: Request, res: Response){ try{ await getManager() .createQueryBuilder() .update(User) .set({ isPrivate: req.body.isPrivate, price: req.body.isPrivate? 0 : null }) .where(`id = '${req['user'].id}'`) .execute(); res.status(201).send(); } catch(err) { res.status(500).json({error: err.message}); } }; // Update the user profile image or theme image export async function updateRole(req: Request, res: Response){ const role = await Roles.findOne({where: {name:req.params.role}}) if(role){ try{ await User.update({ id: req['user'].id },{ role: req.params.role }); res.status(201).send(); } catch(err) { res.status(500).json({error: err.message}); } }else{ res.status(400).json({error: "Unvalide role"}); } }; // Update the user profile image or theme image export async function getRoles(req: Request, res: Response){ const stringRole = fixString(req.params.role) try{ const role = await getManager() .createQueryBuilder(Roles,"roles") .where("roles.name like :name", { name:`%${stringRole}%`}) .select('roles.name') .orderBy('name','ASC') .limit(20).offset(+req.params.offset) .distinct() .getMany(); const arr: Array<string> = []; role.map(k=> arr.push(k.name)) res.status(200).json(arr); } catch(err) { return res.status(500).json({error: err.message}); } }; // Update the settings of the user - password, username, fullname and bio. export async function updateSettings(req: Request, res: Response){ const errorMessage = {bio: null, fullName: null, password: null, username: null} validateTheInput(req.body, errorMessage); const data = dinamicData(req.body); let username: User; try{ if(data.username) username = await User.findOne({where: {username: data.username}, select : ['displayUsername']}); if(username && username.displayUsername != req['user'].username) errorMessage.username = 'Username is already exist'; const user = await User.findOne({where: {id: req['user'].id}, select : ['password', 'displayUsername']}); if(data.password){ if (await bcrypt.compare(req.body.password, user.password) && !errorMessage.password){ const salt = await bcrypt.genSalt(12); const hashpass = await bcrypt.hash(data.password, salt); data['password'] = hashpass; await User.update({ id: req['user'].id }, data); }else{ if(!errorMessage.password) errorMessage.password = 'Password <PASSWORD>'; return res.status(400).json(errorMessage); } }else await User.update({ id: req['user'].id }, data); const token = createToken(req['user'].id, data.username? data.displayUsername : user.displayUsername); const UserInfo = { username: user.username, auth_token: token }; res.status(200).send(UserInfo); }catch{ return res.status(400).json(errorMessage); } }; //------------------------------- Local functions ----------------------------------- function dinamicData(input: Object){ const updateData = { bio: input['bio'], fullName: input['fullName'], username: input['username'], displayUsername: input['username'], password: input['<PASSWORD>'] }; if (!updateData.bio) delete updateData.bio; if (!updateData.fullName) delete updateData.fullName; if (!updateData.username){ delete updateData.username; delete updateData.displayUsername; } else updateData.username = updateData.username.toLocaleLowerCase(); if (!updateData.password) delete updateData.password; return updateData; } function validateTheInput(input: Object, errorMessage: any){ if(input['bio']){ const { error } = validate.addBioValidation({bio: input['bio']}); if (error) errorMessage.bio = error.details[0].message; } if(input['username']){ const { error } = validate.userNameValidation({username: input['username']}); if (error) errorMessage.username = error.details[0].message; } if(input['fullName']){ const { error } = validate.fullNameValidation({fullName: input['fullName']}); if (error) errorMessage.fullName = error.details[0].message; } if(input['password'] || input['newPassword'] || input['passwordConfirmation']){ const data = { password: input['<PASSWORD>'], newPassword: input['<PASSWORD>'], passwordConfirmation: input['passwordConfirmation']} const { error } = validate.newPasswordValidation(data); if (error) errorMessage.password = error.details[0].message; else if(input['newPassword'] != input['passwordConfirmation']) errorMessage.password = 'The password confirmation does not match'; } }<file_sep>/src/routes/recommendation.ts import * as express from 'express'; import * as controller from '../controller/recommendation'; import * as verify from '../token/verifyToken'; const router = express.Router(); // ----------- Auth Post Routes ----------- router.get('/getrecommendpost/:category/:offset', verify.connect, controller.globalPostRecommendation); // ----------- Auth Get Routes ----------- router.get('/getrecommend', verify.connect, controller.globalUsersRecommendation); export default router;<file_sep>/src/routes/s3.ts import * as express from 'express'; import * as s3 from '../s3Connect/s3'; import * as verify from '../token/verifyToken'; import { Request, Response } from 'express'; const router = express.Router(); // ----------- Auth Post Routes ----------- router.get('/geturl',verify.connect, async (req: Request, res: Response) =>{ const url = await s3.generateUploadURL(req['user'].id); res.status(200).json(url); }); export default router;<file_sep>/src/socket/socket.ts import * as util from './utilities' import { Socket } from "socket.io"; import io from '../app'; export function socketConnection(socket: Socket){ socket.on("connected", (userId) => { const users = util.addUser(userId, socket.id); io.emit("getUsers", users) }); socket.on("disconnect", () => { const users = util.removeUser(socket.id); io.emit("getUsers", users); }); socket.on("sendMessage",async ({ senderId, receiverId, text}) => { const userSocket = await util.getUser(receiverId); if(userSocket){ io.to(userSocket).emit("getMessage", { senderId, text, }); } }); socket.on("sendNotification",async (receiverId)=> { const userData = util.addNotification(receiverId); const userSocket = await util.getUser(receiverId); if(userSocket) io.in(userSocket).emit("getNotification", userData[receiverId]); }); socket.on("eraseNotification",async (Id)=> { const userData = util.removeNotification(Id); }); }<file_sep>/src/s3Connect/s3.ts import aws from 'aws-sdk'; import crypto from 'crypto'; import { promisify } from 'util'; const randomBytes = promisify(crypto.randomBytes); const region = process.env.S3_REGION; const bucketName = process.env.S3_BUCKET; const accessKeyId = process.env.AWS_ACCESS_KEY_ID; const secretAccessKey = process.env.AWS_SECRET_KEY; const s3 = new aws.S3({ region, accessKeyId, secretAccessKey, signatureVersion: 'v4' }); export async function generateUploadURL(id: string) { const rawBytes = await randomBytes(16) const imageName = rawBytes.toString('hex') const params = ({ Bucket: bucketName, Key: `${id}/${imageName}`, Expires: 60 }) const uploadURL = await s3.getSignedUrlPromise('putObject', params) return uploadURL }; <file_sep>/README.md <div align="center"> <h1>Webol</h1> <p>New social media for uploading original content and making money out of it!</p> </div> <hr/> <div> <h2>About the project:</h2> <div align="center"> <img width="855" src="https://user-images.githubusercontent.com/87900560/168066947-346d6b67-7d9e-49e7-a892-b8c03f330130.png"/> </div> </div> <br/> <div> <p>This is the backend side of the final project of my BS.C in computer science, We have created this social media with the vision of creating an healthier enviroment where we can meet each other on the internet, learn new stuff and make some money out of it! <br/> The project is still ongoing but the develpoment is never on pause and a great result is soon yet to come!</p> </div> ## How to run: ### `clone the repo` ### `install package` ### `npm run dev` ### Written using TypeScript <file_sep>/test/login.test.ts import dotenv from 'dotenv'; dotenv.config(); import { getConnection } from "typeorm" import { initLocalStorage } from '../src/storage'; import User from '../src/entity/user'; import { googleRequest, loginRequest, registerRequest} from './utilities/apiFunctions' import { faker } from '@faker-js/faker' import { createFullUserDetails } from './utilities/utilitiesFunctions' describe("Login functions", () =>{ beforeAll(async() =>{ try{ await initLocalStorage(); } catch(e){ console.log(e); } }); afterAll(async () =>{ try{ await getConnection() .createQueryBuilder() .delete() .from(User).execute(); } catch(e){ console.log(e); } }); test("When username is missing should respond with a status code of 400",async () => { const body = { username: "", password: <PASSWORD>() }; const loginRes = await loginRequest(body); expect(loginRes.text).toBe("{\"error\":\"Email or Password are incorrect\"}"); expect(loginRes.statusCode).toBe(400); }); // test("When password is missing should respond with a status code of 400",async () => { // const body = { // username: faker.internet.userName(), // password: "" // }; // const loginRes = await loginRequest(body); // expect(loginRes.text).toBe("{\"error\":\"Email or Password are incorrect\"}"); // expect(loginRes.statusCode).toBe(400); // }); // test("When login but give wrong password should respond with a status code of 401", async () => { // const body = createFullUserDetails(); // const registerRes = await registerRequest(body) // expect(registerRes.statusCode).toBe(200); // const user = { // username: body.username, // password: <PASSWORD>() // }; // const loginRes = await loginRequest(user); // expect(loginRes.text).toBe("{\"error\":\"Email or Password are incorrect\"}"); // expect(loginRes.statusCode).toBe(401); // }); // test("When login but give wrong username should respond with a status code of 401", async () => { // const body = createFullUserDetails(); // const registerRes = await registerRequest(body) // expect(registerRes.statusCode).toBe(200); // const user = { // username: faker.internet.userName(), // password: <PASSWORD> // }; // const loginRes = await loginRequest(user); // expect(loginRes.text).toBe("{\"error\":\"Email or Password are incorrect\"}"); // expect(loginRes.statusCode).toBe(401); // }); // test("When login should respond with a status code of 200", async () => { // const body = createFullUserDetails(); // const registerRes = await registerRequest(body) // expect(registerRes.statusCode).toBe(200); // const user = { // username: body.username, // password: <PASSWORD> // }; // const loginRes = await loginRequest(user) // expect(loginRes.statusCode).toBe(200) // }); // test("When login with google should respond with a status code of 200", async () => { // const body = { // name: faker.internet.userName(), // email: faker.internet.email() // }; // const res = await googleRequest(body) // expect(res.statusCode).toBe(200) // }); });
8fdb067e422bafddfb7c38df4a2c8c343a303b7f
[ "Markdown", "TypeScript" ]
45
TypeScript
matangeorgi/Webol---hadassah
f91e418705a068fc9cc84bbbd11b3674ec0bdc66
64c275539657210ec3754e5df0bea37fc16f15b1
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class secondHandsMovement : MonoBehaviour { float rotationMultiplier = 6.0f; public float timeRemaining = 60; void Update() { if (timeRemaining > 0) { timeRemaining -= Time.deltaTime; transform.Rotate(Vector3.forward, Time.deltaTime * rotationMultiplier * -1f); } else { timeRemaining = 0; Debug.Log("Time's up!"); } } private void OnCollisionEnter2D(Collision2D other) { if (other.collider.tag == "DeathTrap") { Physics2D.IgnoreCollision(GetComponent<Collider2D>(), other.collider); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class dropScript : MonoBehaviour { Rigidbody2D RB2D; // Start is called before the first frame update public GameObject Player; void Start() { RB2D = GetComponent<Rigidbody2D>(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag.Equals("Player")) { WaitForSecs(4f); RB2D.isKinematic = false; //GetComponent<Collider2D>().enabled = false; } } private void OnCollisionEnter2D(Collision2D other) { if (other.collider.tag == "Ground") { Physics2D.IgnoreCollision(Player.GetComponent<Collider2D>(), GetComponent<PolygonCollider2D>()); RB2D.isKinematic = true; } } IEnumerator WaitForSecs(float secs) { yield return new WaitForSeconds(secs); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TrapUpDown : MonoBehaviour { public float speed; public GameObject target; public GameObject initialPosition; bool isUp; private void Start() { initialPosition.transform.position = transform.position; isUp = false; } private void Update() { if (isUp == false) { transform.position = Vector3.MoveTowards(transform.position, target.transform.position, speed * Time.deltaTime); if (transform.position == target.transform.position) { isUp = true; } } if (isUp == true) { transform.position = Vector3.MoveTowards(transform.position, initialPosition.transform.position, speed * Time.deltaTime); if (transform.position == initialPosition.transform.position) isUp = false; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BotDumpPatrol : MonoBehaviour { public float speed; public Transform[] moveSpots; private int randomSpot; private int spotIndex; public float startWaitTime; private float waitTime; // Start is called before the first frame update void Start() { spotIndex = 0; randomSpot = Random.Range(0, moveSpots.Length); } // Update is called once per frame void Update() { DoomPatrol(); } /* transform.position == moveSpots[randomSpot].position does not function as intended because of float exponents Check distance between two points for a fixed value instead */ private void DoomPatrol() { transform.position = Vector2.MoveTowards(transform.position, moveSpots[spotIndex].position, speed * Time.deltaTime); if (Vector2.Distance(transform.position, moveSpots[spotIndex].position) < 0.4f) { if (waitTime <= 0) { spotIndex++; waitTime = startWaitTime; } else { waitTime -= Time.deltaTime; } } if (spotIndex == moveSpots.Length) { spotIndex = 0; } } private void DoomPatrolRandom() { transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime); if (Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f) { if (waitTime <= 0) { randomSpot = Random.Range(0, moveSpots.Length); waitTime = startWaitTime; } else { waitTime -= Time.deltaTime; } } } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; public class DeathMenu : MonoBehaviour { public string MainMenuLevel; public void RestartGame() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } public void MainMenu() { SceneManager.LoadScene(0); } } <file_sep>using UnityEngine; using UnityEngine.SceneManagement; public class GameManage : MonoBehaviour { bool gameHasEnded = false; public GameObject player; public DeathMenu deathScreen; public GameObject levelWonScreen; public GameObject player_corpse; public void FinishLevel() { Debug.Log("GG!"); player.GetComponent<SpriteRenderer>().enabled = false; player.GetComponent<Player_Movement>().enabled = false; levelWonScreen.SetActive(true); if(SceneManager.GetActiveScene().buildIndex != 3){ SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } } public void EndGame() { if (gameHasEnded == false) { gameHasEnded = true; player.GetComponent<Player_Movement>().enabled = false; player.GetComponent<SpriteRenderer>().enabled = false; //player.GetComponent<CapsuleCollider2D>().enabled = false; //player_corpse.transform.position = new Vector3(player.transform.position.x, player.transform.position.y,player.transform.position.z); //player_corpse.SetActive(true); Debug.Log("Noob"); RestartGame(); } } void RestartGame() { //SceneManager.LoadScene(SceneManager.GetActiveScene().name); deathScreen.gameObject.SetActive(true); //player.gameObject.SetActive(false); } } <file_sep>using UnityEngine; public class EndTrigger : MonoBehaviour { public GameManage gameManager; private void OnTriggerEnter2D(Collider2D collision) { if (collision.tag == "Player") { gameManager.FinishLevel(); } } } <file_sep>**Running out of Time - A project for CS427 Mid-term** <img src="image/1.jpg" width = "400"> A little spider get stuck inside a clock cave. He is desperated to escape from the seconds hand ticking every seconds. Help him find the way out of the maze. Be careful! There are a lot of "tricky" obstacles stand on his way. **Menu UI** <img src="image/2.png" width = "400"> **Level 1: Deadly Cave** Basic level for player to get used to the movement of rounded map. <img src="image/3.png" width = "400"> <img src="image/4.png" width = "400"> <img src="image/5.png" width = "400"> **Level 2: Stone Cold** As deadly as the cold of ice. <img src="image/6.png" width = "400"> <img src="image/7.png" width = "400"> <img src="image/8.png" width = "400"> <img src="image/9.png" width = "400"> **Level 3: Fog of War** You never know what is going to happen.. <img src="image/12.png" width = "400"> <img src="image/13.png" width = "400"> <img src="image/14.png" width = "400"> <img src="image/15.png" width = "400"> <img src="image/16.png" width = "400"> **Contributor** <a href="https://github.com/bannnn511/furry-meme/graphs/contributors"> <img src="https://contributors-img.web.app/image?repo=bannnn511/furry-meme" /> </a> **Play on WebGL**: [Running out of time](https://bannnn511.itch.io/running-out-of-time) **Install on PC (Windows only)**: [Running out of time](http://www.mediafire.com/file/lz660d76kspujr1/file) **Unity Version** Unity 2019.4.1f1 **Team member** - <NAME> - 1751067 - <NAME> - 1751047 - <NAME> - 1751122 <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] [RequireComponent(typeof(Collider2D))] [RequireComponent(typeof(SpriteRenderer))] public class Player_Movement : MonoBehaviour { [Tooltip("This is the gameobject were the player is attracted to. If nothing, the player will fly, you can change that gameobject on Runtime")] public GameObject CenterOfGravity; public float GravityForce; public GameManage gameManager; // collisionPoint should be the player public Transform collisionPoint; // collisionRange is the range where event is triggerd public float collisionRange = 0.5f; // layer of which eneny need to check collider public LayerMask enemyLayer; public float PlayerSpeed; // MaxSpeed has no use, consider to remove this public float MaxSpeed; public float JumpSpeed; [Tooltip("For Double Jump or more. Set to 1 for a single jump")] public int NumberOfJump; private int JumpCount; private bool IsGrounded; private float distToGround; private Collider2D collider; public LayerMask GroundedMask; public LayerMask whatIsGround; private Rigidbody2D RB2B; public float checkRadius; public Transform feetPos; private SpriteRenderer PlayerSpriteRenderer; private Animator anim; private float AngularSpeedLimitation; void Start() { RB2B = GetComponent<Rigidbody2D>(); PlayerSpriteRenderer = GetComponent<SpriteRenderer>(); anim = GetComponent<Animator>(); collider = GetComponent<Collider2D>(); distToGround = collider.bounds.extents.y; JumpCount = NumberOfJump; On_PlayerMovement(); On_PlayerJump(); } void Update() { On_PlayerMovement(); On_PlayerJump(); MirrorAnimationPlayer(); ResetNumberOfJump(); CheckIfPlayerGrounded(); GravityDrag(); Debug.DrawRay(this.transform.position, -transform.up, Color.green); } private void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.tag == "DeathTrap") { gameManager.EndGame(); Debug.Log("You are death"); } } //This function calculate the speed limitation of the player depending of how far he is from the center of Gravity. //This will prevent the player from flying if he goes too fast, too close from the center of gravity private float CalculateAngularSpeedLimitation() { if (CenterOfGravity != null) { float speedLimitation; float distance; distance = Vector3.Distance(transform.position, CenterOfGravity.transform.position); distance = distance / 10; speedLimitation = Mathf.Lerp(0.5F, 2F, distance); speedLimitation = speedLimitation / 5; return speedLimitation; } else { return 1; } //If the player don't have gravity center, no speed limitation is set. } private void GravityDrag() { if (CenterOfGravity != null) { RB2B.AddForce((CenterOfGravity.transform.position - transform.position) * GravityForce); Vector3 dif = CenterOfGravity.transform.position - transform.position; float RotationZ = Mathf.Atan2(dif.y, dif.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0.0F, 0.0F, RotationZ + 90); } } private void On_PlayerMovement() { if(Input.GetKeyDown(KeyCode.RightArrow)|| Input.GetKeyDown(KeyCode.LeftArrow) ) FindObjectOfType<AudioScript>().PlaySound("PlayerWalking"); if (Input.GetKeyUp(KeyCode.RightArrow) || Input.GetKeyUp(KeyCode.LeftArrow)) FindObjectOfType<AudioScript>().StopSound("PlayerWalking"); if (Input.GetAxis("Horizontal") != 0) { Vector2 localvelocity; localvelocity = transform.InverseTransformDirection(RB2B.velocity); localvelocity.x = Input.GetAxis("Horizontal") * Time.deltaTime * PlayerSpeed * 100 * CalculateAngularSpeedLimitation(); RB2B.velocity = transform.TransformDirection(localvelocity); anim.SetBool("PlayerMoving", true); } else { //Slow down the player when no pressure on the Horizontal Axis (For more responcive controls). Vector2 localvelocity; localvelocity = transform.InverseTransformDirection(RB2B.velocity); localvelocity.x = localvelocity.x * 0.5F; RB2B.velocity = transform.TransformDirection(localvelocity); anim.SetBool("PlayerMoving", false); } } private void On_PlayerJump() { if (Input.GetButtonDown("Jump")) { if (JumpCount != 0) { Vector2 localvelocity; localvelocity = transform.InverseTransformDirection(RB2B.velocity); localvelocity.y = 0; RB2B.velocity = transform.TransformDirection(localvelocity); JumpCount--; RB2B.AddRelativeForce(new Vector2(0, 1) * JumpSpeed * 10, ForceMode2D.Impulse); anim.SetBool("PlayerJumping", true); FindObjectOfType<AudioScript>().PlaySound("PlayerJump"); } } else { anim.SetBool("PlayerJumping", false); } } private void CheckIfPlayerGrounded() { if (isGrounded()) { IsGrounded = true; //anim.SetBool("PlayerJumping", false); } else { IsGrounded = false; //anim.SetBool("PlayerJumping", true); } } private bool isGrounded() { if (Physics2D.OverlapCircle(feetPos.position, checkRadius, whatIsGround)) { return true; } return false; } //Below this point, The script is doing normal stuff (like animation)// private void MirrorAnimationPlayer() { Vector2 localVelocity = transform.InverseTransformDirection(RB2B.velocity); if (localVelocity.x > 0.5F) { if (PlayerSpriteRenderer.flipX == false) { PlayerSpriteRenderer.flipX = true; FindObjectOfType<AudioScript>().PlaySound("PlayerWalking"); } } else if (localVelocity.x < -0.5) { if (PlayerSpriteRenderer.flipX == true) { PlayerSpriteRenderer.flipX = false; FindObjectOfType<AudioScript>().PlaySound("PlayerWalking"); } } } private void ResetNumberOfJump() { if (JumpCount < NumberOfJump) { if (IsGrounded) { JumpCount = NumberOfJump; } } } }<file_sep>using UnityEngine; using Pathfinding; public class botScript : MonoBehaviour { public float direction = 1; public float speed = 1.5f; public GameObject CenterOfGravity; public float GravityForce; public float chaseDistance = 4.5f; Animator enemyAnimator; private SpriteRenderer spriteRenderer; Rigidbody2D enemyRigidBody; // Start is called before the first frame update AIPath aiPath; // Start is called before the first frame update void Start() { enemyAnimator = GetComponent<Animator>(); enemyRigidBody = GetComponent<Rigidbody2D>(); spriteRenderer = GetComponent<SpriteRenderer>(); aiPath = GetComponent<AIPath>(); } // Update is called once per frame void Update() { DumbMovement(); MirrorAnimation(); StartAttack(); GravityDrag(); } private void GravityDrag() { if (CenterOfGravity != null && aiPath == null) { enemyRigidBody.AddForce((CenterOfGravity.transform.position - transform.position) * GravityForce); Vector3 dif = CenterOfGravity.transform.position - transform.position; float RotationZ = Mathf.Atan2(dif.y, dif.x) * Mathf.Rad2Deg; transform.rotation = Quaternion.Euler(0.0F, 0.0F, RotationZ + 90); } } /* Bot will start attack when bot and player is in a fixed distance For Fog of War, add sfx when bot start moving -> Hieu heo lam cai nay nha :D */ void StartAttack() { if (aiPath != null) { if (aiPath.desiredVelocity.x <= 0.01f) { transform.eulerAngles = new Vector3(0, 180, 0); } else { transform.eulerAngles = new Vector3(0, 0, 0); } if (aiPath.remainingDistance <= chaseDistance) { aiPath.canMove = true; } else { aiPath.canMove = false; } } } private float CalculateAngularSpeedLimitation() { if (CenterOfGravity != null) { float speedLimitation; float distance; distance = Vector3.Distance(transform.position, CenterOfGravity.transform.position); distance = distance / 10; speedLimitation = Mathf.Lerp(0.5F, 2F, distance); speedLimitation = speedLimitation / 5; return speedLimitation; } else { return 1; } //If the player don't have gravity center, no speed limitation is set. } /* Dumb movement left and right when player not in range */ void DumbMovement() { if (aiPath == null) { Vector2 localvelocity; localvelocity = transform.InverseTransformDirection(enemyRigidBody.velocity); localvelocity.x = direction * Time.deltaTime * speed * 100 * CalculateAngularSpeedLimitation(); enemyRigidBody.velocity = transform.TransformDirection(localvelocity); } } private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("turn")) { Debug.Log("Turn"); direction *= -1; } } private void MirrorAnimation() { Vector2 localVelocity = transform.InverseTransformDirection(enemyRigidBody.velocity); if (localVelocity.x > 0.5F) { if (spriteRenderer.flipX == false) { spriteRenderer.flipX = true; } } else if (localVelocity.x < -0.5) { if (spriteRenderer.flipX == true) { spriteRenderer.flipX = false; } } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using Pathfinding; public class flyingBotScript : MonoBehaviour { public int maxHealth = 120; Animator enemyAnimator; int currentHealth; Rigidbody2D enemyRigidBody; // Start is called before the first frame update AIPath aiPath; // Start is called before the first frame update void Start() { enemyAnimator = GetComponent<Animator>(); currentHealth = maxHealth; enemyRigidBody = GetComponent<Rigidbody2D>(); enemyRigidBody.simulated = false; aiPath = GetComponent<AIPath>(); } // Update is called once per frame void Update() { if (aiPath.desiredVelocity.x <= 0.01f) { transform.eulerAngles = new Vector3(0, 180, 0); } else { transform.eulerAngles = new Vector3(0, 0, 0); } if (aiPath.remainingDistance <= 8) { enemyRigidBody.simulated = true; } else { enemyRigidBody.simulated = false; } } }
389fd1bc28c55e4fe92fca129e779c4932addcbb
[ "Markdown", "C#" ]
11
C#
ptv1811/furry-meme
ce11a79da2841083d02f7a57adb50a3749106c67
7f85b7b5ef46efab532f4cfa6470c14ce3670beb
refs/heads/master
<file_sep># subdo-scanner Simple a subdomain scanner python How to install? ``` $ pkg install git $ pkg install python $ git clone https://github.com/DH4CK1/subdo-scanner $ cd subdo-scanner $ pip2 install -r requirements.txt $ python2 scan.py ``` <file_sep>#!/bin/python2.7 #-*- coding: utf-8 -*- """ Copyright (c) 2020 Dst_207 """ """ Silahkan dipelajari slur tools nya tapi asal jangan di recode/reupload ya kak kalo mau pelajari pelajari aja ok! """ import os, time, sys, json, re, requests from var_animate import * logo = banner('Subdomain','Dst_207','0.1 Scanner') alert = animvar() input = animinput() ## Coloring ## c = color().show me = c('red') bi = c('blue') i = c('green') cy = c('cyan') pu = c('white') os.system('clear') print(logo) print('{}Team{}: {}Black Coder Crush {}& {}DevSecID\n').format(cy,me,pu,bi,pu) host = input.ask('Host') if 'www' in host: host = host.replace('www.') elif 'http://' in host: host = host.replace('http://') elif 'https://' in host: host = host.replace('https://') r = requests.get('https://api.hackertarget.com/hostsearch/?q='+host).text if 'error check your search parameter' in r: time.sleep(1) print('\n'+alert.false('Sepertinya Host Yg anda masukan salah')) time.sleep(1) exit() scan = r.split('\n') a = 1 for i in scan: rgx = re.search('(.*?),(.*)',i) print('{} ---- {}{} {}----').format(bi,me,a,bi) try: print('{}Host{}: {}{}').format(cy,me,pu,rgx.group(1)) print('{}Ip{}: {}{}').format(cy,me,pu,rgx.group(2)) except AttributeError: pass a += 1
d9ffe7bff333b11931cdb07f152751fd49299db8
[ "Markdown", "Python" ]
2
Markdown
yangwj2019/subdo-scanner
7d21a2049b55c985a3eb272c23ddad4bcce8bd5e
08df57dd70757a9bb451436cae4bece55f4ee8c1
refs/heads/master
<repo_name>sumanjs/suman-server<file_sep>/public/js/views/art/art.jsx "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var React = require("react"); var store = require("@redux-store"); // import store = require('../../data-stores/redux-store'); var art_child_1 = require("./children/art-child"); module.exports = (function (_super) { __extends(Home, _super); function Home(props) { return _super.call(this, props) || this; } Home.prototype.componentDidMount = function () { var s = store.getState(); this.unsubscribe = store.subscribe(function () { console.log('home is subscribed.'); }); }; Home.prototype.componentWillUnmount = function () { console.log('component will unsubscribe'); this.unsubscribe(); }; Home.prototype.render = function () { art_child_1.default = require('./children/art-child').default; return (<div> Wekkkpp zoom peaches <art_child_1.default /> </div>); }; return Home; }(React.Component)); <file_sep>/@build.sh #!/usr/bin/env bash cd $(dirname "$0") npm install <file_sep>/roodles.conf.js const path = require('path'); // module.exports = { // exec: 'bin/www.js', // exclude: [path.resolve(__dirname + '/node_modules/.*'), '.git', 'test', 'public','.idea'] // }; module.exports = { exec: 'bin/www.js', // any binary file or a file with a hashbang include: [__dirname], exclude: [ 'public', '.git', '.idea', 'package.json', 'node_modules', '.*\.log', '.*\.sh' ], signal: 'SIGINT', restartUponChange: true, restartUponAddition: false, restartUponUnlink: false, processLogPath: null, // if desired, pass a relative or absolute path to log file verbosity: 1, // an integer {1,2,3} processArgs: [] }; <file_sep>/test/one.test.js Promise.resolve().then(function(){ // throw 'bob'; }, function(err){ console.log(err); });<file_sep>/views/README.md ### this folder contains backend views only 1. 500 error page 2. 404 page 3. 403 page etc.<file_sep>/README.md # Suman-Server ### Suman server - Web UI for test results When this server is live, it will collect test results to a local SQLite3 database, and display results via a React single-page web application. Because Suman runs tests asynchronously (concurrently) - only using Suman server can you see the chronological and fully ordered/organized test output. Furthermore, Suman server allows you to easily share and discuss results with your team.
688eb02fcbada677d27fae07e559b718d4e60981
[ "JavaScript", "Markdown", "Shell" ]
6
JavaScript
sumanjs/suman-server
936f72c4f5fcb8ee81831e6f685727e0cc008de6
549a3816c6346b6c8a84439617b384d3d8cfb585
refs/heads/master
<file_sep>from django.shortcuts import render, HttpResponse def homepage(request): context = {} return render(request, "homepage.html", context)<file_sep>from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import auth # Create your views here. def login(request): if request.method == "POST": pass else: return render(request, 'accounts/login.html') def signup(request): if request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: User.objects.get(username = request.POST['username']) return render(request, 'accounts/signup.html', {"error": "Username already taken"}) except User.DoesNotExist: u = User.objects.create(username=request.POST['username'],email=request.POST['email'],password=request.POST['<PASSWORD>']) auth.login(request, u) return redirect('root') else: return render(request, 'accounts/signup.html') def logout(request): return HttpResponse("Logged out")<file_sep>from django.views.generic import CreateView from order import models from order.forms import * class NewOrderView(CreateView): model = models.Order fields = ("is_delivered", "is_collected", "pizzas") class NewCustomerView(CreateView): model = models.Customer #form_class = CustomerForm fields = ("name", "number", "address")<file_sep>from django import forms from order.models import Pizza, Customer class PizzaForm(forms.ModelForm): class Meta: model = Pizza fields = ('size', 'toppings') widgets = { 'size': forms.RadioSelect(), 'toppings': forms.CheckboxSelectMultiple(), } def process(self, order): data = self.cleaned_data size = data['size'] toppings = data['toppings'] pizza = Pizza.objects.create() pizza.size = size pizza.base_price = pizza.size.base_price for topping in toppings: pizza.toppings.add(topping) pizza.base_price += pizza.topping.base_price pizza.save() order.pizzas.add(pizza) order.save() class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ("name","number", "address") def __init__(self, *args, **kwargs): super(CustomerForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) def process(self, order): data = self.cleaned_data name = str(data['name']) number = str(data['number']) address = str(data['address']) customer = Customer.objects.create(name=name, number=number) order.customer = customer order.save() <file_sep># from django.conf.urls.defaults import * # from order.views import order_pizza, order_bread from django.urls import path from order.views import * urlpatterns = [ path('new/', NewOrderView.as_view(), name="new_order"), path('<int:pk>/customer/new', NewCustomerView.as_view(), name="new_customer") ]<file_sep>from django.contrib import admin from order.models import Size, Topping, Pizza from order.models import Customer, Order class OrderAdmin(admin.ModelAdmin): def pizza_count(self,obj): return obj.pizzas.count() def customer_address(self,obj): return obj.customer.address def customer_phone(self, obj): return obj.customer.number list_display = ("customer","customer_address","customer_phone", "date", "is_collected", "is_delivered","pizza_count", "subtotal", "total") class PizzaAdmin(admin.ModelAdmin): def toppings_info(self, obj): return list(obj.toppings.all()) list_display = ("size", "toppings_info", "base_price") #admin.site.register(Flavor) admin.site.register(Size) admin.site.register(Topping) admin.site.register(Pizza, PizzaAdmin) #admin.site.register(Bread) admin.site.register(Customer) admin.site.register(Order, OrderAdmin) <file_sep>{% extends 'base.html' %} {% block content %} <h1 class="h3 text-center main-heading">Login</h1> <div class="row justify-content-center"> <div class="col-md-4"> <form method="POST" action="{% url 'login' %}" class="form"> {% csrf_token %} <div class="form-group"> <label>Username</label> <input type="text" name="username" class="form-control"> </div> <div class="form-group"> <label>Password</label> <input type="<PASSWORD>" name="password" class="form-control"> </div> <input type="submit" class="btn btn-primary btn-block" /> </form> </div> </div> {% endblock content %}<file_sep># Generated by Django 2.1.1 on 2018-09-17 10:47 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=64)), ('number', models.CharField(max_length=20)), ('address', models.CharField(max_length=150)), ], ), migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField()), ('subtotal', models.DecimalField(decimal_places=2, default=0.0, max_digits=6)), ('total', models.DecimalField(decimal_places=2, default=0.0, max_digits=6)), ('is_collected', models.BooleanField(default=False)), ('is_delivered', models.BooleanField(default=False)), ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='order.Customer')), ], ), migrations.CreateModel( name='Pizza', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('base_price', models.DecimalField(decimal_places=2, default=0.0, max_digits=4)), ], ), migrations.CreateModel( name='Size', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=24)), ('base_price', models.DecimalField(decimal_places=2, default=0.0, max_digits=4)), ], ), migrations.CreateModel( name='Topping', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=24)), ('base_price', models.DecimalField(decimal_places=2, default=1.0, max_digits=4)), ], ), migrations.AddField( model_name='pizza', name='size', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='order.Size'), ), migrations.AddField( model_name='pizza', name='toppings', field=models.ManyToManyField(to='order.Topping'), ), migrations.AddField( model_name='order', name='pizzas', field=models.ManyToManyField(blank=True, to='order.Pizza'), ), ] <file_sep>import unittest import datetime from django.conf import settings from django.test.client import Client from order.models import Order, Customer, Pizza, Bread, Topping from order.views import place_order, order_pizza from django.test.utils import setup_test_environment setup_test_environment() """ Model tests """ class OrderTestCase(unittest.TestCase): def setUp(self): self.customer = Customer.objects.create(name='Jim') self.order = Order.objects.create(customer=self.customer, date = datetime.datetime.now()) def test_order(self): self.assertEqual(self.order.customer.name, 'Jim', 'customer name incorrect') def tearDown(self): self.order.delete() self.customer.delete() class PizzaTestCase(unittest.TestCase): def setUp(self): self.pepperoni = Topping.objects.create(name='Pepperoni') self.sausage = Topping.objects.create(name='Sausage') self.pizza = Pizza.objects.create(size='M', crust='GR') self.pizza.toppings.add(self.pepperoni, self.sausage) def test_size(self): self.assertEqual(self.pizza.size, 'M', "Size not added correctly.") def test_toppings(self): toppings = self.pizza.toppings.all() self.assertEqual(toppings[0].name, 'Pepperoni', "Pepperoni not added correctly.") self.assertEqual(toppings[1].name, 'Sausage', "Sausage not added correctly.") def test_crust(self): self.assertEqual(self.pizza.crust, 'GR', "Crust not added correctly.") def tearDown(self): self.pizza.delete() self.pepperoni.delete() class BreadTestCase(unittest.TestCase): def setUp(self): self.bread = Bread.objects.create(type='GR') def test_type(self): self.assertEqual(self.bread.type, 'GR', "Bread type incorrect.") def test_price(self): self.assertEqual(self.bread.base_price, 4.00, "Bread price incorrect.") def tearDown(self): self.bread.delete() """ View tests """ class OrderPizzaTestCase(unittest.TestCase): fixtures = ['order_order', 'order_pizza'] def setUp(self): client = Client() self.response = client.get('/order/', follow=True) def test_order(self): order = self.response.order.all()[0] pizza = order.pizzas.all()[0] toppings = pizza.toppings.all() self.assertEqual(pizza.size, 'M', "Pizza size incorrect on order 1.") self.assertEqual(toppings[0].name, 'Pepperoni', "Pepperoni not on pizza, order 1") self.assertEqual(toppings[1].name, 'Bacon', "Bacon not on pizza, order 1") <file_sep># Pizza order system in django 2.0 and Python 3.6 ## Requirements: - psycopg2 ## Installation: #### You should have anaconda installed prior coz conda is used to manage dependencies ### Install postgres if not installed already ### Create postgres user and give it authority so create database and login to database ``` $ sudo -i -u postgres $ createuser --createdb --login pizza -P password: <PASSWORD> $ psql # CREATE DATABASE pizza WITH OWNER pizza; # \q $ exit ``` ### Create conda virtual environment and install dependencies ``` $ conda create -n pizza python=3.6 $ conda install django $ conda install psycopg2 ``` ### Run the migrations ``` $ python manage.py makemigrations $ python manage.py migrate ``` ### Run server ``` $ python manage.py runserver ``` #### Open browser and open localhost:8000<file_sep>import decimal from decimal import Decimal from django.db import models from django.urls import reverse quant = Decimal('0.01') class Size(models.Model): name = models.CharField(max_length=24) base_price = models.DecimalField(max_digits=4,decimal_places=2,default=0.00) def __str__(self): return self.name class Topping(models.Model): name = models.CharField(max_length=24) base_price = models.DecimalField(max_digits=4,decimal_places=2,default=1.00) def __str__(self): return self.name class Customer(models.Model): name = models.CharField(max_length=64) number = models.CharField(max_length=20) address = models.CharField(max_length=150) def __str__(self): return self.name def get_absolute_url(self): return reverse("root") class Pizza(models.Model): size = models.ForeignKey(Size, null=True, on_delete=models.CASCADE) toppings = models.ManyToManyField(Topping) #crust = models.ForeignKey(Flavor, null=True, on_delete=models.CASCADE) base_price = models.DecimalField(max_digits=4, decimal_places=2, default=0.00) made_by = models.ForeignKey(Customer, on_delete=models.CASCADE) def save(self, *args, **kwargs): if not Pizza.objects.filter(id=self.id): super(Pizza, self).save(*args, **kwargs) else: price = Decimal('0.00') if self.size: price = self.size.base_price print(price) for topping in self.toppings.all(): if topping.base_price: price = price + topping.base_price self.base_price = decimal.Decimal(str(price)).quantize(quant) print(price) super(Pizza, self).save(*args, **kwargs) def __str__(self): if self.size.name: name = self.size.name + " Pizza" else: name = "Pizza" for topping in self.toppings.all(): if topping.name: name = name + ", " + topping.name return name class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) date = models.DateField() pizzas = models.ManyToManyField(Pizza, blank=True) #breads = models.ManyToManyField(Bread, blank=True) #is_made = models.BooleanField(default=False) subtotal = models.DecimalField(max_digits=6, decimal_places=2,default=0.00) total = models.DecimalField(max_digits=6, decimal_places=2, default=0.00) is_collected = models.BooleanField(default=False) is_delivered = models.BooleanField(default=False) def save(self, *args, **kwargs): if not Order.objects.filter(id=self.id): super(Order, self).save(*args, **kwargs) else: decimal.getcontext().rounding = decimal.ROUND_HALF_EVEN self.subtotal = Decimal('0.00') for pizza in self.pizzas.all(): self.subtotal += pizza.base_price for topping in pizza.toppings.all(): self.subtotal += topping.base_price for bread in self.breads.all(): self.subtotal += bread.base_price if self.subtotal < 30.00: self.total = self.subtotal + 8.00 self.total = self.total.quantize(quant) super(Order, self).save(*args, **kwargs) def __str__(self): return str(self.id) def get_absolute_url(self): return reverse("new_customer", kwargs={"pk": self.id})
b52d333ac5c47599184345579f1fadaa6b87c9d1
[ "Markdown", "Python", "HTML" ]
11
Python
rabinpoudyal/Pizza
2b48284cc98424c8a225a949940ac86eefdbeb5b
9e9b63722a03062d5e52c0543c9dc8a362b1ee05
refs/heads/master
<file_sep>const socketController=(socket)=>{ console.log('Cliente conectado ',socket.id); socket.on('disconnect',()=>{ console.log('Cliente desconectado ',socket.id); }) socket.on('enviar-mensaje', (payload,callback)=>{ const id=12345689 callback(id) socket.broadcast.emit('mensaje-servidor',payload) }) } export {socketController}
1d6a9d4e6c2a8beba0845f89100b8bfb2a2d73a1
[ "JavaScript" ]
1
JavaScript
mpgigat/borrar-sockets
2df3efaf74ab486de158c109f4b6838f81623b33
872c7c52d9fc8a72e2eab53ee47cb1a932e9cb39
refs/heads/main
<repo_name>nikolajokic96/Testing<file_sep>/src/DTO/Statistic.php <?php namespace MyApp\DTO; class Statistic { /** * @var string */ private string $name; /** * @var string */ private string $studentId; /** * @var array */ private array $grades; /** * @var string */ private string $finalResult; /** * @var float */ private float $averageGrade; /** * @param string $name * @param string $studentId * @param array $grades * @param string $finalResult * @param float $averageGrade */ public function __construct(string $name, string $studentId, array $grades, string $finalResult, float $averageGrade) { $this->name = $name; $this->studentId = $studentId; $this->grades = $grades; $this->finalResult = $finalResult; $this->averageGrade = $averageGrade; } /** * @return string */ public function getName(): string { return $this->name; } /** * @return string */ public function getStudentId(): string { return $this->studentId; } /** * @return array */ public function getGrades(): array { return $this->grades; } /** * @return string */ public function getFinalResult(): string { return $this->finalResult; } /** * @return float */ public function getAverageGrade(): float { return $this->averageGrade; } /** * @return array */ public function toArray(): array { return [ 'studentId' => $this->getStudentId(), 'studentName' => $this->getName(), 'averageGrade' => $this->getAverageGrade(), 'grades' => $this->getGrades(), 'finalResult' => $this->getFinalResult(), ]; } }<file_sep>/src/services/CSMB.php <?php namespace MyApp\services; use MyApp\contracts\FinalResults; use MyApp\DTO\Student; class CSMB implements FinalResults { public const BOARD = 'CSMB'; public const GRADE_TO_PASS = 8; /** * @inheritDoc * * @param Student $student */ public function finalResults(array $grades): string { if (count($grades) > 2) { array_shift($grades); } foreach ($grades as $grade) { if ($grade > self::GRADE_TO_PASS) { return self::PASS; } } return self::FAILED; } }<file_sep>/router.php <?php use MyApp\controllers\StudentController; use MyApp\repositories\StudentRepository; use MyApp\services\StudentService; session_start(); /** * @param $route */ function get($route) { if ($_SERVER['REQUEST_METHOD'] == 'GET') { route($route); } } function any($route) { route($route); } /** * Routes to adequate controller * * @param $route */ function route($route) { $root = $_SERVER['DOCUMENT_ROOT']; if ($route == "/404") { include_once("$root/'path to 404 not found page'"); exit(); } $request_url = filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL); $request_url = rtrim($request_url, '/'); $request_url = strtok($request_url, '?'); $route_parts = explode('/', $route); $requestUrlParts = explode('/', $request_url); array_shift($route_parts); array_shift($requestUrlParts); if (count($route_parts) != count($requestUrlParts)) { return; } if ($route === $request_url) { switch ($requestUrlParts[0]) { case '': call_user_func([new StudentController(new StudentService(new StudentRepository())), 'index']); break; } } } function out($text) { echo htmlspecialchars($text); }<file_sep>/src/repositories/StudentRepository.php <?php namespace MyApp\repositories; use Cassandra\Exception\ValidationException; use Exception; use MyApp\database\DB; use MyApp\DTO\Student; class StudentRepository { /** * Returns student for given id * * @param string $id * @return Student * @throws Exception */ public function getStudent(string $id): Student { $sql = 'SELECT * FROM students where id = ' . $id; $results = DB::executeQuery($sql); if (!$results) { throw new Exception('There are no user with given id!', 404); } $studentArray = reset($results); return new Student( $studentArray['id'], json_decode($studentArray['grades']), $studentArray['name'], $studentArray['board'] ); } }<file_sep>/src/controllers/StudentController.php <?php namespace MyApp\controllers; use Exception; use MyApp\database\DB; use MyApp\helpers\Request; use MyApp\services\StudentService; class StudentController { public const STUDENT_QUERY_PARAM = 'student'; /** * @var StudentService */ private StudentService $studentService; /** * @param StudentService $studentService */ public function __construct(StudentService $studentService) { $this->studentService = $studentService; } /** * Gets request for students statistic */ public function index() { try { $this->isParamValid(); echo $this->studentService->getStudentStatistic(Request::getQueryParam(self::STUDENT_QUERY_PARAM)); } catch (Exception $e) { require_once(__DIR__ . '/../views/html/validQueryParam.phtml'); } DB::closeConnection(); } /** * Checks if query param is sent * @throws Exception */ private function isParamValid() { $studentId = Request::getQueryParam(self::STUDENT_QUERY_PARAM); if (!$studentId) { throw new Exception('Please enter student id', 404); } } }<file_sep>/src/contracts/FinalResults.php <?php namespace MyApp\contracts; use MyApp\DTO\Student; interface FinalResults { public const PASS = 'PASS'; public const FAILED = 'FAILED'; /** * Calculates student final result * * @param array $grades * @return string */ public function finalResults(array $grades): string; }<file_sep>/routes.php <?php require_once("{$_SERVER['DOCUMENT_ROOT']}/router.php"); require_once realpath("vendor/autoload.php"); get('/'); <file_sep>/src/DTO/Student.php <?php namespace MyApp\DTO; class Student { /** * @var int */ private int $id; /** * @var array */ private array $grades; /** * @var string */ private string $name; /** * @var string */ private string $board; /** * @param int $id * @param array $grades * @param string $name * @param string $board */ public function __construct(int $id, array $grades, string $name, string $board) { $this->id = $id; $this->grades = $grades; $this->name = $name; $this->board = $board; } /** * @return int */ public function getId(): int { return $this->id; } /** * @return array */ public function getGrades(): array { return $this->grades; } /** * @return string */ public function getName(): string { return $this->name; } /** * @return string */ public function getBoard(): string { return $this->board; } }<file_sep>/src/helpers/Request.php <?php namespace MyApp\helpers; class Request { /** * Returns query param if exists * * @param string $param * @return string|null */ public static function getQueryParam(string $param): ?string { return $_GET[$param]; } }<file_sep>/src/database/DB.php <?php namespace MyApp\database; use mysqli; use SQLiteException; /** * class DB */ class DB { public const HOST = 'localhost'; public const USERNAME = 'root'; public const PASSWORD = ''; public const DATABASE = 'school'; /** * @var mysqli */ public static mysqli $instance; /** * Gets mysql connection * * @return mysqli */ public static function getConnection(): mysqli { if (!isset(self::$instance)) { self::$instance = mysqli_connect(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASE); if (!self::$instance) { throw new SQLiteException('Connection Error' . mysqli_connect_error()); } } return self::$instance; } /** * Executes given sql query * * @param string $query * @return array|null */ public static function executeQuery(string $query): ?array { $result = mysqli_query(self::getConnection(), $query); $arrayResults = mysqli_fetch_all($result, MYSQLI_ASSOC); mysqli_free_result($result); return $arrayResults; } /** * Close connection */ public static function closeConnection() { if (isset(self::$instance)) { mysqli_close(self::$instance); } } }<file_sep>/school.sql -- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Sep 14, 2021 at 05:23 PM -- Server version: 10.4.21-MariaDB -- PHP Version: 8.0.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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: `school` -- -- -------------------------------------------------------- -- -- Table structure for table `students` -- CREATE TABLE `students` ( `id` int(11) NOT NULL, `grades` varchar(255) NOT NULL, `board` varchar(25) NOT NULL, `name` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `students` -- INSERT INTO `students` (`id`, `grades`, `board`, `name`) VALUES (1, '[7,10,6,9]', 'CSM', '<NAME>'), (2, '[8,10,6,6]', 'CSMB', '<NAME>'), (3, '[7,7,6,5]', 'CSM', '<NAME>'), (4, '[7,6,5,6]', 'CSMB', 'Mika Mikic'); -- -- Indexes for dumped tables -- -- -- Indexes for table `students` -- ALTER TABLE `students` ADD PRIMARY KEY (`id`); 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 */; <file_sep>/src/services/StudentService.php <?php namespace MyApp\services; use Exception; use MyApp\DTO\Statistic; use MyApp\repositories\StudentRepository; use SimpleXMLElement; class StudentService { /** * @var StudentRepository */ private StudentRepository $studentRepository; /** * @param StudentRepository $studentRepository */ public function __construct(StudentRepository $studentRepository) { $this->studentRepository = $studentRepository; } /** * Returns student statistic * * @param string $id * @return string * @throws Exception */ public function getStudentStatistic(string $id): string { $student = $this->studentRepository->getStudent($id); $grades = $student->getGrades(); $passCondition = $student->getBoard() === CSM::BOARD ? new CSM() : new CSMB(); if ($student->getBoard() === CSMB::BOARD && count($grades) > 2) { unset($grades[array_search(min($grades), $grades)]); } $statistic = new Statistic( $student->getName(), $student->getId(), $grades, $passCondition->finalResults($grades), $this->averageGrade($grades) ); return $student->getBoard() === CSM::BOARD ? json_encode($statistic->toArray()) : $this->convertToXML($statistic->toArray()); } /** * Calculates average student grade * * @param array $grades * @return float */ private function averageGrade(array $grades): float { $gradeSum = 0; foreach ($grades as $grade) { $gradeSum += $grade; } return $gradeSum / count($grades); } /** * Converts array to simple xml * * @param $array * @param null $rootElement * @param null $xml * @return bool|string * @throws Exception */ private function convertToXML($array, $rootElement = null, $xml = null): bool|string { $_xml = $xml; if ($_xml === null) { $_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>'); } foreach ($array as $k => $v) { if (is_array($v)) { $this->convertToXML($v, $k, $_xml->addChild($k)); } else { $_xml->addChild($k, $v); } } return $_xml->asXML(); } }<file_sep>/src/services/CSM.php <?php namespace MyApp\services; use JetBrains\PhpStorm\Pure; use MyApp\contracts\FinalResults; class CSM implements FinalResults { public const BOARD = 'CSM'; public const PASS_LIMIT = 7; /** * @inheritDoc * * @param array $grades */ #[Pure] public function finalResults(array $grades): string { $gradeSum = 0; foreach ($grades as $grade) { $gradeSum += $grade; } $gradeAverage = $gradeSum / count($grades); return $gradeAverage >= self::PASS_LIMIT ? self::PASS : self::FAILED; } }
9cbbdf2f901cacd97c364f727dccdb3568dce804
[ "SQL", "PHP" ]
13
PHP
nikolajokic96/Testing
ec50809faf952a78a2cd00d50cd857d60698bb56
165fcb6194ab201c96e713d5292255af3ff7e169
refs/heads/master
<repo_name>Shenjieping/blog<file_sep>/进阶学习/第五天-类的继承/extend.js // ES5 的继承 function Animal() { this.name = 'name'; } Animal.prototype.say = function() { console.log('say'); } function Tiger() { Animal.call(this); // 调用父类构造函数,改变this指向 } // 1. 继承实例属性 /* function Tiger() { Animal.call(this); // 调用父类构造函数,改变this指向 } let tiger = new Tiger(); console.log(tiger.name); */ /* 每个函数(类)都有prototype,每个人都有__proto__ 指向所属类的原型 */ /* let anmial = new Animal(); console.log(anmial.__proto__ === Animal.prototype); // true console.log(anmial.__proto__.__proto__ === Object.prototype); // true console.log(Object.prototype.__proto__); // null,根节点 console.log(Object.__proto__ === Function.prototype); // true,对象的链指向函数的原型 console.log(Function.prototype.__proto__ === Object.prototype); // true // __ptoto__ 查找属性和方法 console.log(Function.__proto__ === Function.prototype); // true console.log(Function.__proto__ === Object.__proto__); //true // constructor 定义在原型上,指向当前的构造函数 console.log(Animal.prototype.constructor); //Animal */ // Tiger.prototype = Animal.prototype; // 这个交混合,不叫继承 // 2. 继承公共属性 // Tiger.prototype.__proto__ = Animal.prototype; // 通过原型链继承公共属性 // Tiger.prototype = Object.create(Animal.prototype); // 和上面类似,但是原理不一样 /* Tiger.prototype = create(Animal.prototype); // 手动实现create function create(parentPrototype) { function Fn() {}; Fn.prototype = parentPrototype; return new Fn(); } */ /* IE 低版本游览器不支持 __proto__ 可以使用 Object.setPrototypeOf(Tiger.prototype, Animal.prototype) */ let anmial = new Animal(); let tiger = new Tiger(); console.log(tiger.say); /* ES6的继承,是利用 函数.call() 加上 Object.create 来实现的,也就是 extends 的原理 */ <file_sep>/进阶学习/第七天-eventloop-commonjs/note.md # 回顾 ## 1. 关于函数 - 什么是高阶函数 把函数作为参数,或者返回值是函数 - 柯理化函数(函数更加具体,核心像bind,可以保留参数) =》 思考:反柯理化,让函数的调用范围扩大 Object.prototype.toString.call(); - AOP(装饰器) 将函数进行包装(代理模式),before after @装饰器 数组的方法劫持 AOP(面向切面变成),主要的作用就是把一些跟核心业务逻辑模块无关的功能进行抽离出来,其实就是给原函数增加了一层,不用管函数内部的实现 - 发布订阅模式,promise 可以then多次,观察者模式(event on emit) 一种一对多的关系,发布者和订阅者是否有关联,观察者模式基于发布订阅模式 ## 2. promise - promise 中链式调用如何中断 - promise.finally 原理 - promise有哪些优缺点 - 优点:可以解决异步并发问题,promise.all, 链式调用 - 缺点:还是基于回调,Promise无法终止,基于Promise封装的fetch 无法中断 xhr.abort() - promise.race & promise.all 原理 - 如何中断promise -> abort方法 - generator & co - async + await 语法糖 ## 3. ES6 - let & const(1. 没有变量提升 2. 不会污染全局作用域 3. 不能重复声明 4. 拥有自己独立的作用域) - symbol 第六种基本数据类型,独一无二 ```js // 元编程 let obj = { [Symbol.hasInstance]() { // 将原方法进行了改写 return true; }, [Symbol.toPromitive](type) { return 100; // 重写方法 } }; let a = 'a'; console.log(a instanceof obj); // 正常情况下是报错的 ``` - sperad(展开运算符) 深拷贝 数据类型的判断 - set map(WeakMap) 去重(交集,并集,差集) - defineProperty proxy reflect - ES6中的模块化(静态导入、动态导入)import export - ES6 中的类 ## 浏览器事件环 - 进程(计算机分配任务和调度任务的最小单位,每个进程互不影响,而且可以协同工作)里面包含线程的,我们写代码的时候都是关注的js执行线程 - 流浪器事件环 主线程只有一个 <file_sep>/第十二天/数据类型检测的四种方法.md ## JS中数据类型检测的四种方法 - typeof - 语法:typeof(val), 返回当前数据类型的字符串 - 优势:检测基本类型的值很准确,操作方便 - 劣势: - typeof null => 'object' - typeof 检测数组、对象、正则等都是 'object' 无法细分对象类型 - instanceof - val instanceof 类,检测和这个值是否是属于这个类,从而验证是否是这个类 - 优势:对于数组,正则,对象可以细分 - 劣势: - 无法检测基本数据类型 - 检测的原理,只要在当前实例的 __proto__ 上都是true - constructor - 和instnceof 类似,也是非专业检测数据类型的。 - 语法 val.constructor === 类 - 相对于 instanceof 来说,可以处理基本类型的值,也可以区分Array和Object - 劣势:constructor 是可以随意改变的,改了之后就不准确了 - Object.prototype.toString.call - 在其他数据类型的内置类型上有 toString方法,但是都是用来转为字符串,只有Object原型上的toString 是用来检测数据类型的 - obj.toString(),obj这个实例调用Object.prototype.toString 执行,方法里面的this是当前操作的实例obj,此方法就是检测this的数据类型的,返回的结果 `"[object 所属类]"` - 基于call强制改变方法中的this是value,相当于检测 value的类型,可以简写 `({}).toString.call(val)` ```js // instanceof [] instanceof Array; // true [] instanceof Object; // true,数组也是Object的实例 function Fn() {} Fn.prototype = Array.prototype; var fn = new Fn(); fn instanceof Array; //true // Object.prototype.toString.call let obj = {name: 'x'}; obj.toString(); // [object, Object] Object.toString.call(1); // [object, Number] ``` ## jQ中是如何检测的 ```js var class2type = {}; var toString = class2type.toString; // Object.toString 是用来检测数据类型的 var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; // // => Function.prototype.toString var ObjectFunctionString = fnToString.call( Object ); // "function Object() { [native code] }" var isFunction = function isFunction( obj ) { // 检测是否是function // typeof obj.nodeType !== "number" 处理低版本浏览器兼容 return typeof obj === "function" && typeof obj.nodeType !== "number"; }; var isWindow = function isWindow( obj ) { // 检测是否为window // 利用浏览器的机制 window.window === window return obj != null && obj === obj.window; }; /* jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( _i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); */ ["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object", "Error", "Symbol"].forEach(function(name, _i) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // console.log(class2type); /* class2type = { [object Array]: "array" [object Boolean]: "boolean" [object Date]: "date" [object Error]: "error" [object Function]: "function" [object Number]: "number" [object Object]: "object" [object RegExp]: "regexp" [object String]: "string" [object Symbol]: "symbol" } */ function toType( obj ) { // 检测数据类型的公共方法 // 传入的是 null 就返回 "null" if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) // 引用数据类型,是基于Object.prototype.call(),如果是基本数据类型 则使用 typeof // 如果是 new Number(1), 仍然会返回 "number" return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; } console.log(toType({a: 1})); // 检测是否为数组或者类数组 function isArrayLike( obj ) { // length 是 length或者length的属性值 var length = !!obj && "length" in obj && obj.length, type = toType( obj ); if ( isFunction( obj ) || isWindow( obj ) ) { // 排除函数和window return false; } /* type === "array" 是数组 length === 0 空的类数组 {length:0} typeof length === "number" && length > 0 && ( length - 1 ) in obj; 有length 属性,并且为了保证有效数字索引并且是递增的,基于 length - 1 最大索引是都在obj中来检测 =》 类数组 */ return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } /* JQ检测是否为纯对象,obj.__proto__ === Object.prototype */ var getProto = Object.getPrototypeOf; jQuery.isPlainObject = function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // 获取当前的原型 // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; } /* 检测是否为一个空对象 */ function isEmptyObject( obj ) { var name; for ( name in obj ) { // 如果能进入for-in循环,则说明不是个空对象 return false; } return true; } /* 检测是否为一个数组,但是 "1"也会是一个number */ var isNumeric = function( obj ) { var type = jQuery.type( obj ); return ( type === "number" || type === "string" ) && !isNaN( obj - parseFloat( obj ) ); }; ``` ## 简单封装检测数据类型方法 ```js function myTypeof(value) { var typeArray = ["Boolean", "Number", "String", "Function", "Array", "Date", "RegExp", "Object", "Error", "Symbol", "BigInt"]; var class2type = {}; var toString = class2type.toString; typeArray.forEach((name, index) => { class2type[`[object ${name}]`] = name.toLowerCase(); }); if (value == null) { return value + ''; } return typeof value === 'object' || typeof value === 'function' ? class2type[toString.call(value)] || 'object' : typeof value; } var res = myTypeof(function() {}); console.log(res); ``` <file_sep>/进阶学习/第五天-类的继承/homework.js // 1. 实现new方法 // 2. 实现reduce方法 // 3. 数组的扁平化<file_sep>/第三天/变量提升.md ```js var a = 0; if (true) { a = 1; function a () {}; a = 21; console.log(a); // 21 } console.log(a); // 1 ``` ## 变量提升 在当前上下文中(无论是全局/私有/块级)JS代码自上而下执行之前,浏览器会提前处理一些事情,(可以理解为词法解析的一个环节,词法解析一定发生在代码执行之前) 会把当前上下文所有带 var、 function 的关键字进行提前的申明和定义 var a = 10; 声明,创建一个变量 declare: var a; 定义,赋值 defined: a = 10; ```js /* 在代码执行之前,全局变量的上下文中的变量提升 带var 的只会提前声明,带function的会提前声明加定义 提升 var a; 默认值是undefined */ console.log(a); // undefined var a = 12; // 创建值12,不需要再声明 a 了,在变量提升阶段完成了 a = 13; // 让全局的 a = 13; console.log(a); ``` ```js // 真实项目中,建议使用 函数表达式的形式创建变量,因为这样在变量提升阶段只会声明 func ,不会赋值 func(); // TypeError: func is not a function var func = function() { console.log('ok'); } ``` ```js // 匿名函数具名化,虽然是起了个名字,但是这个名字不能再外面使用,也就是不会在当前上下文中创建这个名字 // 起名,一是为了规范函数,二是,在当函数执行的时候,在形成私有上下文中,会把这个具名化的名字作为私有上下文中的变量,值就是这个函数 // 在递归调用的时候会使用到,告别在严格模式下不再支持的 arguments.callee var func = function test() { console.log('ok'); console.log(test); // fn } // test(); // test is not a function func(); ``` ```js // 此处没有声明,也就是没有提升 console.log(a); // ReferenceError: a is not defined a = 12; console.log(a); ``` ```js // ES6 中的 let const 不会变量提升 console.log(a); // ReferenceError: a is not defined let a = 12; console.log(a); ``` - 基于 var 或者 function 在全局上下文中声明的变量(全局变量),会映射到 GO(全局对象window)上一份,作为他的属性, 接下来是一个修改,另一个也会跟着修改 ```js var a = 12; console.log(a); // 全局变量 console.log(window.a); // 映射到window上的属性 a = 13; console.log(a); // 一个修改映射的另一个也会修改 ``` ```js /* GC(G) 全局上下文中的变量提升 不论条件是否成立,都要进行变量提升,此时条件中带function的在新版本浏览器中只会提前声明,不会提前赋值,老版本中,会声明加定义 */ console.log(a, fn); // 新版本中是 undefined undefined,在IE10 及以下是 undefined fn if (!('a' in window)) { // a 是否为window属性,提升过了就会有 window.a var a = 1; function fn() {} } console.log(a); // undefined ``` ```js /* EC(G) 全局上下文中的变量提升 */ fn(); // 5 function fn() { // 不再处理 console.log(1); } fn(); // 5 function fn() { // 声明过了不会重复声明,但是会重复赋值 console.log(2); } fn(); // 5 var fn = function() { // 在变量提升阶段没有执行过这个赋值,此处需要赋值 console.log(3); } fn(); // 3 function fn() { console.log(4); // 3 } fn(); // 3 function fn(){ console.log(5); } fn(); // 3 ``` ```js var foo = 1; function bar() { if (!foo) { var foo = 10; // 此处会发生变量提升,所以在bar 作用域中 foo = undefined; } console.log(foo); // 10 } bar(); console.log(foo); // 1 ``` ```js var a = 0; if (true) { a = 1; function a () {} a = 21; console.log(a); // 21 } console.log(a); // 1 /* 现在最新版本的浏览器,要向前兼容ES3和ES5的规范 1. 判断体和函数体不存在块级上下文,上下文只有全局和私有 2. 不论条件是否成立,function都要声明加定义 向后兼容ES6规范 1. 存在块级作用域,大括号中出现 let/const/function 都会被认为是块级作用域 2. 无论条件是否成立,带 function 的只会提前声明,不会提前赋值 */ /* 新版浏览器的处理规则: 因为要兼容ES3/ES6。a 在全局下声明过 也在私有下处理过,遇到此行代码,私有下不会再处理 但是浏览器会把当前代码 之前, 所有对a 的操作 映射一份给全局一份,以此兼容ES3,但是后面的代码 和全局就没有关系了 */ ``` <file_sep>/第十一天/练习题.md ## 1. 编写程序 ```js let ary = [12, 23, 12, 13, 13, 12, 23, 14, 8]; Array.prototype.myUnique = function() { return [...new Set(this)]; } Array.prototype.mySort = function() { return this.sort((a, b) => a - b); } ary.myUnique().mySort(); // 执行后的结果[8, 12, 13, 14, 23] ``` ## 2. 输出下面的结果 ```js var x = 3, obj = { x: 5 }; /* 全局下: x: 3 obj: { x: 5, fn: } */ obj.fn = (function() { /* obj.fn执行一次 作用域链:<EC(AN), EC(G)> 初始化this:window 代码执行 this.x = window.x *= ++x => 3 * (++3) = 12 window.x = 12; return function(y){...} (0x0001) */ this.x *= ++x; return function(y) { this.x *= (++x) + y; console.log(x); } })(); var fn = obj.fn; /* 此时的结果: window.x = 12; window.obj = { x: 5, fn: 0x0001 } window.fn = 0x0001 */ obj.fn(6); /* 初始化this y = 6; this.x => obj.x obj.x = 5 * (13 + 6) = 95 window.x = 13; x => 13 */ fn(4); /* 初始化this: window y = 4; this.x => window.x window.x = 13 * (14 + 4) = 234; x => 234 */ console.log(obj.x, x); // 95, 234 ``` ## 3. 下面的结果 ```js let obj = { fn: (function() { return function() { console.log(this); } })() } obj.fn(); // obj let fn = obj.fn; fn(); // widnow ``` ## 4. 下面的结果 ```js var fullName = 'language'; var obj = { fullName: 'jsvascript', prop: { getFullName: function() { return this.fullName; } } } console.log(obj.prop.getFullName()); // undefined let test = obj.prop.getFullName; console.log(test()); // language ``` ## 5. 输出下面的结果 ```js var name = 'window'; var Tom = { name: 'Tom', show: function() { console.log(this.name); }, wait: function() { // this => Tom var fn = this.show; fn(); } } Tom.wait(); // 'window' ``` ## 6. 输出下面的结果 ```js window.val = 1; var json = { val: 10, dbl: function() { this.val *= 2; } } /* 全局下: val = 1 json = { val: 10, dbl: function() {} } */ json.dbl(); /* json.sbl this => json json.val = 20 */ var dbl = json.dbl; dbl(); /* this => window window.val = 2 */ json.dbl.call(window); /* this => window window.val = 4 */ console.log(wondow.val + json.val); // 4 + 20 ``` ## 7. ```js (function() { var val = 1; var json = { val: 10, dbl: function() { val *= 2; } }; json.dbl(); console.log(json.val + val); // 10 + 2 })(); ``` ## 8. ```js var name = 'shenjp'; function A(x, y) { var res = x + y; console.log(res, this.name); } function B(x, y) { var res = x - y; console.log(res, this.name); } B.call(A, 40, 30); B.call.call.call(A. 20, 10); Function.prototype.call(A, 60, 50); Function.prototype.call.call.call(A, 80, 70); ``` ## 9. ```js ~function() { function change(context, ...args) { // => 实现你的代码 context = context || window; let key = Symbol('key'); context[key] = this; let res = context[key](...args); delete context[key]; retuen res; }; Function.prototype.change = change; }(); let obj = { name: 'shenjp' }; function func(x, y) { this.total = x + y; return this; } let res = func.change(obj, 100, 200); console.log(res); // {name: 'shenjp', total: 300} ``` <file_sep>/进阶学习/第一天/1.promise.js // 低版本的IE不支持,需要polilly去支持 // promise 内部会提供两个方法,可以更改Promise的状态 // Promise有三个状态:等待态,成功态,失败态 const Promise = require('./promise'); let promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('ok11'); }, 1000); // console.log('ok') }); promise.then(data => { return new Promise((resolve, reject) => { resolve(new Promise((resolve, reject) => { resolve('1123') })); }) }).then(data => { console.log(data); }, (err) => { console.log('...', err); }) /* promise.then((data) => { // onfulfilled console.log(data); return data; }, (err) => { // onrejected console.log(err); }).then(data => { console.log(data); return new Promise((resolve, reject) => { setTimeout(() => { resolve('next'); }, 1000); }); }).then(data => { console.log(data); return new Promise((resolve, reject) => { reject('失败'); }); }, () => {}).then(() => {}, (err) => { console.log(err); }) */ // then 中返回的是一个普通值,或者一个成功的Promise,会走下一个then的成功 /* step1: 引用同一个对象 let promise2 = new Promise(() => { return promise2; // 返回值又引用了自己 }); promise2.then(() => { }, (e) => { console.log(e); // Type Error }); stpe2: 判断x的类型,如果是对象或者函数,说明有可能是一个Promise */ <file_sep>/第七天/var-let-const三者的区别.md ## var let const 三者有什么区别? ### let VS const 突出的是指针指向已经等号复制的底层机制 1. 等号赋值其实是指针指向的过程,先创建值,再创建变量(引申,堆内存上以及 AO/VO 上)最后指针关联 2. let 创建的是变量,是因为可以修改当前变量的指针指向 3. const 创建的变量,指针指向一旦确定,就不能再修改,(引申,平时也看到一些文章说,const 创建的是常量,我认为这种说法并不严谨,因为,毕竟他只是指针不能改变,如果指向的是一个对象,在不改变指针的情况下,我们是可以修改对象中的值的) 4. 真实项目中,我们对于一些需要宏观管控的标识值,一般都是基于 const 创建(比如:在vue或者redux中,需要派发的行为标识)这样在用户误操作修改他的值后会报错 5. 后续不能再更改指向的变量或者函数,也会基于const创建 ### var VS let/const 1. let 不存在变量提升(加一句,所以不能再声明变量之前使用)我之前在公司写项目,基本上都是基于ES6的let处理了,这样我会把后续需要用到的变量,在代码起始位置先声明加定义,给一个默认值,也就是 ”变量声明前置“。而且创建的函数也一般是基于函数表达式的方式创建,这样就保证只有在创建代码后函数才可以有效的执行 2. let 不允许重复申明,(真实项目中,代码量比较多,除了申明前置外,还可以有效的避免重复声明报错的问题,而且我会尽可能的对业务进行拆分,每一个小模块在一个单独的闭包中,降低相同上下文中,变量声明的个数,这也是防止重复声明的办法) 3. 在全局执行上下文中,基于let 声明的全局变量和全局对象和window没有关系,var 申明的变量会和 GO 有一个映射机制 4. 暂时性死区问题,基于typeof 检测一个未声明的变量时,不会报错,结果是 undefined (引申,我之前看过一些源码,比如JQ,他们利用这个机制,检测上下文中是否存在window/module,从而验证是浏览器环境还是node环境),但是如果此变量在后面会被let声明,则直接报错,错误信息是,不允许在声明之前使用变量(这个是在浏览器词法解释阶段处理的事情) 5. 我认为除了上述说到的,最重要的是,let/const 都会把当前所以在的大括号,(除函数以外)自以为一个全新的块级上下文,应用这个机制,我们在项目开发的时候,如果遇到循环事件绑定的时候,无需在用闭包存储起来了,只需要基于let 的块级作用域特征即可解决,很方便,当然还有一些其他的应用,也是利用的块级上下文解决的 ```js typeof n // => undefined 检测一个未声明的变量,不会报错,结果是undefined // 如果下面用let 定义了 let n = 10; // 报错,不能在定义之前报错 ```<file_sep>/第七天/闭包面试技巧.md ## 谈谈你对闭包的理解,以及在项目中的应用 1. 阐述闭包是什么?(衍生的问题是,堆栈,EC, VO, SCOPE) 2. 闭包的作用,以及在真实项目中的应用,以及带来的问题和解决 3. 由闭包引发的高级编程技巧 4. 突出自己在分析研究框架的源码,(比如自己写的类库,插件的时候)是怎么用这些东西的 ### 闭包是什么 浏览器加载页面会把代码放到栈内存中去执行(ECStack),函数进栈执行之前,会产生一个私有的上下文(EC),此上下文能保护里面的私有变量(AO),不受外界的干扰,并且如果当前上下文中的某些内容,被当下文以外的内容占用,当前上下文是不会出栈释放的,形成不被销毁的栈内存。这样可以保存里面的变量和变量值。所有我认为闭包是一种保存和保护内部私有变量的机制。 ### 闭包在真实项目中的应用 在真实项目中,我的应用场景还是比较多的,比如: 1. 我会基于闭包把自己编写的模块内容包起来,这样编写的代码都是自己私有的,防止和全局变量或者别人写的代码冲突,这一点利用的是闭包的保护机制 2. 在之前没有用let之前,我们循环处理事件绑定的时候,在事件触发需要用到索引的时候,我们会基于闭包把每一轮循环的索引值保存起来,这样来实现我们的需求,只不过现在都是基于let来完成,因为let会产生块级作用,来保存需要的内容,机制和闭包类似 3. 但是不建议过多使用闭包,因为会形成不会释放栈的上下文,是占用内存空间的,过多的使用会导致页面渲染变慢,所以要合理应用闭包 ### 由闭包引发的高级编程技巧 除了这些传统的业务开发中会用到闭包,我之前在研究别人源码和自己写一写插件的时候,往往会利用一些JS高级编程技巧来实现的管理和功能的开发,他们的底层原理其实就是闭包,比如: 1. 惰性思想 2. 柯理化函数 3. compose函数 4. ...<file_sep>/第十天/this的基础.md ## this 的五种情况 全局上下文下,this是window,块级上下文中没有自己的this,继承上级上下文中的this,在函数的私有上下文中,this的情况也会多种多样,接下来我们重点研究 this 不是执行上下文(EC才是执行上下文),this是执行主体 如何区分执行主体: 1. 事件绑定:给事件的某个事件行为绑定方法,当事件触发,方法执行,方法中的this是当前元素本身(特殊:IE~IE8中基于 attachEvent方法实现的DOM2事件绑定,事件触发后,方法中的this指向window,而不是元素本身) ```js // 事件绑定 // DOM0 let body = document.body; body.onclick = function() { console.log(this); // 方法中的this指向 body } // DOM2 body.addEventListener('click', function() { console.log(this); // 指向body }); // IE6~IE8 body.attachEvent('onclick', function() { console.log(this); // 指向window }) ``` 2. 普通方法执行(包含自执行函数执行,普通函数执行,对象成员反问读取方法执行),只需要看函数执行的时候,方法名前面是否有 "点(.)" , "点(.)" 前面是谁this就是谁,如果没有,this就是window(严格模式下是undefined) ```js // 自执行函数 // "use strict"; // 如果开启严格模式,this => undefined (function() { console.log(this); // window })(); let obj = { fn: (function() { console.log(this); // window return function() {} })() // 把自执行函数执行的结果赋值给Obj.fn } // 普通执行 function func() { console.log(this); } let obj = { func: func } func(); // 方法中的this => window obj.func(); // 方法中的this => obj [].slice(); // =》 数组中的实例基于原型链机制,找到Array 原型上的slice方法,然后再把slice执行,此时 slice 中的this一定是当前数组 Array.prototype.slice(); // slice执行中的this:Array.prototype function func() { console.log(this); // window } document.body.onclick = function() { console.log(this); // body func(); // 此处是在window上调用的 } // 点击body 之后,输出的结果是window // 点击body 先之后回调函数,里面的this是body,再给window上执行的func ``` 3. 构造函数执行(new xx):构造函数中的this是当前类的实例 ```js function Func() { this.name = 'shenjp'; console.log(this); // 构造体函数中的this,在构造体函数执行的情况下,是当前类的一个实例,并且this.xx=xx,是给当前实例设置属性 } Func.prototype.getName = function() { console.log(this); // 只有在执行的时候才能确定,不一定都是实例,看之后的时候 “点(.)” 前面的内容 } let f = new Func(); f.getName(); f.__proto__.getName(); Func.prototype.getName(); ``` 4. ES6 中提供了 Arrow function(箭头函数),箭头函数没有自己的this(也没有arguments),它的this是继承所在上下文中的this ```js let obj = { func: function() { console.log(this); }, sum: () => { // 没有自己的this console.log(this); }, num() { // 这是ES6中的简写,不是箭头函数,等同于 func: function(){} console.log(this); } } obj.func(); // this 指向 obj obj.sum(); // this 指向window obj.sum.call(obj); //箭头函数没有this,哪怕强制改也没有用 obj.num(); // this指向obj // this指向 let obj = { i: 0, /* func() { // this => obj let _this = this; setTimeout(function() { // 当前函数在全局下执行 // this => window _this.i++; console.log(obj.i); // 1 }, 1000); } */ /* func() { setTimeout(function() { // 基于bind把函数中的this预先处理为obj this.i++; console.log(obj.i); // 1 }.bind(this), 1000); } */ func() { setTimeout(() => { // 箭头函数没有自己的this,用的是所在上下文中的this,那么this就是 obj this.i++; console.log(obj.i); // 1 }, 1000); } } obj.func(); ``` 5. 可以基于 call/apply/bind 三种方式,强制手动改变函数中的 this 指向,这三种方式很暴力,前三种情况下,在使用这三种方法中后,都已手动改变的为主 ## 练习题 ```js var num = 10; var obj = { num: 20 } /* 全局下: num: 10, obj: 0x0000 fn: 0x0002 */ obj.fn = (function(num) { // 自执行this => window,形成私有变 num this.num = num * 3; // window.num = 20 * 3 = 60 num++; // 私有的 num = 21 return function(n) { // => 0x0002 this.num += n; num++; console.log(num); } })(obj.num); // 20 var fn = obj.fn; fn(5); // 此时的this指向window, window.num = 65, num是上级上下文中的 num = 22 // 执行结果22 obj.fn(10); // 此时的this指向obj, obj.num = 30, num 是上级上下文中的 num = 23 // 执行结果23 console.log(num, obj.num); // 全局的num = 65, obj.num = 30 ``` ![练习题讲解](./练习题.png)<file_sep>/进阶学习/第一天/观察者.js let fs = require('fs'); // 观察者模式,观察者,和被观察者,是有关联的。观察者需要吧自己放到观察者之上,当被观察者转态发送变化,需要通知所有的观察者 class Subject { // 被观察者 constructor(name) { this.name = name; this.state = '开心'; this.observers = []; } setState (state) { this.state = state; // 更新被观察者的状态 this.observers.forEach(fn => fn.update(this)) } attach(o) { // 需要将注册者放到自己身上 this.observers.push(o); } } class Observer { // 观察者 constructor(name) { this.name = name; } update (s) { // 等会被观察者的状态发送变化会调用这个方法 console.log(this.name, '说:', s.state); } } let baby = new Subject('小宝宝'); let parent = new Observer('爸爸'); let mothor = new Observer('妈妈'); baby.attach(parent); baby.attach(mothor); baby.setState('不开心'); setTimeout(() => { baby.setState('开心了'); }, 1000); /* // 异步的解决方案,最早是基于回调函数的 fs.readFile('./age.txt', 'utf8', function(error, data) { // console.log(error, data); e.emit('age', data) }); fs.readFile('./name.txt', 'utf8', function(error, data) { // console.log(data); e.emit('name', data) }); // 订阅好一件事,当事件发生的时候,触发对应的函数 // 订阅 => on 发布 => emit e.on(function(obj) { // 每次发布都会触发此函数 if (Object.keys(obj).length === 2) { // 用户根据结果自己觉得输出 console.log(obj) } }); */<file_sep>/第十五天/ajax.md ## ajax 基础知识 (async javascript and xml) - 核心四步 - 创建Ajax实例对象 - 打开url(发送请求前的一些处理) - 监听ajax的转态信息 - 发送请求 - 请求的方式 - GET系列 get/delete/head/options - get 用户获取信息,也可以传一些信息给客户端 - delete 一般用于删除服务器上的文件或一些大量的信息 - head 只需要获取响应头的信息 - options 试探性请求,用于CORS跨域资源共享的时候,在每一个正常的请求之前,我们默认先发一个options请求,这个请求用来校验客户端和服务器端是否连接即可 - POSt系列 post/put - 一般认为向服务器发送信息,也可以返回信息 - put 一般用于给服务器传递文件,或大的数据 缓存问题,浏览器在处理GET请求的时候,如果两次请求的地址和参数都一致,浏览器会设置数据缓存,解决方式就是每次请求的地址都不一样 ### Ajax 状态 xhr.readyState XMLHttpRequest.prototype: - DONE: 4 响应主体也加载返回了 - LOADING: 3 响应主体正在加载返回中 - HEADERS_RECEIVED: 2 浏览器已经返回相应头信息 - OPENED: 1 已打开,执行了open - UNSENT: 0 未发生,开始创建XHR默认状态是0 ### HTTP网络状态码 xhr.state - 2开头的,服务器正常返回数据,项目中所谓的成功和失败,分为两种:1. 网络层面的(服务器没有返回任何信息或者和服务器没有连接上)。2. 业务层面的(已经从服务端获取数据,只不过获取的数据是不符合业务需要的也可以看做失败) - 3开头的 - 304 读取的是协商缓存的数据 - 301 永久重定向 一般用于域名的转移 - 302 临时重定向 一般用于服务器的负载均衡 - 307 临时转移 - 4开头的 - 400 客户端错误 - 5开头的 - 500 服务端发送未知错误<file_sep>/进阶学习/第一天/发布订阅.js let fs = require('fs'); let e = { _obj: {}, _callback: [], on(callback) { // 订阅就是将函数放到数组中 this._callback.push(callback); }, emit(key, value) { this._obj[key] = value; this._callback.forEach(method => method(this._obj)); } } // 异步的解决方案,最早是基于回调函数的 fs.readFile('./age.txt', 'utf8', function(error, data) { // console.log(error, data); e.emit('age', data) }); fs.readFile('./name.txt', 'utf8', function(error, data) { // console.log(data); e.emit('name', data) }); // 订阅好一件事,当事件发生的时候,触发对应的函数 // 订阅 => on 发布 => emit e.on(function(obj) { // 每次发布都会触发此函数 if (Object.keys(obj).length === 2) { // 用户根据结果自己觉得输出 console.log(obj) } }); <file_sep>/进阶学习/第七天-eventloop/core.js // core 掌握node中的全局对象,global // 全局对象:在文件中不用申明就可以直接使用的 /* 默认文件中的this不是global 使用var声明的变量也不会挂载到global中 */ /* console.log(this === global) var a = 1; console.log(global.a); // undefined */ /* process 进程对象 Buffer 缓存区,内存 clearInterval,clearTimeout,setInterval,setTimeout setImmediate,clearImmediate 是一个宏任务 */ // console.log(Object.keys(global)); // console.dir(global, {showHidden: true}) // 1. process 代表当前运行的进程 /* platform 平台 mac/window/linux... argv 用户执行node时传递的参数 cwd 代表用户执行node时所在的目录 current working directory nextTick 下一队列 是一个微任务 env 环境变量 */ // console.log(process.platform); // mac -> darwin // console.log(process.argv.slice(2)); // 放在数组中 // 方法1. 拿到获取的参数 node core.js -p 3000 -c webpack.js /* let res = process.argv.slice(2).reduce((mome, current, index, arr) => { if (current.startsWith('-')) { mome[current.replace(/-/g, '')] = arr[index + 1] || true; } return mome; }, {}); console.log(res); // { p: '3000', c: 'webpack' } */ // 方法2. commander 命令行管家 /* let program = require('commander'); program.version('1.0.0', '-v, --version'); program.parse(process.argv); */ // 2. env 当前运行时的环境变量 // console.log(process.env); // 不同的环境设置的方式不同,mac-> export window->set // cross-env 包,可以设置不同平台的环境变量 // 3. cwd 代表用户执行的目录 // console.log(process.cwd()); // 是一个绝对路径 // 4. nextTick 下一队列,给不同的方法都设置了不同的队列(执行结果和浏览器一致) /* setTimeout(() => { console.log('timeout') }); setImmediate(() => { console.log('立即') }); // 这两个的执行顺序不确定,setTimeout 的默认时间是2-4ms https://nodejs.org/zh-cn/docs/guides/event-loop-timers-and-nexttick/ */ /* Promise.resolve().then(() => { console.log('then'); }) process.nextTick(() => { console.log('tick') // 更快 }) */ /* 默认会先执行主栈中的代码,执行后,会清空微任务,和浏览器一样,每次执行宏任务都会清空微任务,进入的eventLoop 开始循环, 会先检测事件是否到达,如果没到达,会向下切换,走到poll阶段,如果用户有绑定 setImmediate 会执行setImmediate, 当一轮执行后,会再次进入循环,如果时间还没到,就进入到poll,会在poll阶段进行等待,等待时间到达 */ const fs = require('fs'); fs.readFile('node.js', 'utf-8', function() { setTimeout(() => { console.log('timeout'); }); setImmediate(() => { console.log('immediate'); }) }); /* 根据事件环的的执行顺序,读写文件属于poll 阶段,poll执行完之后的下一阶段是先执行check阶段。所以此时的immediate一定会先执行 */ /* 如果是node 10 之前的版本,浏览器是 1 个宏任务执行完就清空微任务,node中是清空完整个队列之后再清空微任务 */ setTimeout(() => { console.log(2); Promise.resolve().then(() => { console.log(3); }) }, 0); setTimeout(() => { console.log(1); }, 0); // 在新版本中node和浏览器一样,顺序是 2 3 1 ,老版本中就是 2 1 3 <file_sep>/进阶学习/第一天/promiseRace.js const fs = require('fs'); const path = require('path'); const {promisify} = require('util'); // const Promise = require('./promise'); function resolve (dir) { return path.join(__dirname, dir) } const read = promisify(fs.readFile); function isPromise(promise) { if ((typeof promise === 'object' && promise !== null) || typeof promise === 'function') { if (typeof promise.then === 'function') { return true; } return false; } return false; } Promise.race = function(arr) { // } // 如果全成功了才会成功,只要有一个失败就失败了 Promise.race([read(resolve('./name.txt'), 'utf8'), read(resolve('./age.txt'), 'utf8')]) .then(data => { console.log(data); }).catch(err => { console.log(err); }); // 实现promise.race<file_sep>/进阶学习/第六天-数据结构/map.js // map hash表 // 特点:查找快,可以直接通过所以查找 class Map { constructor() { this.arr = []; } calcKey(key) { let hash = 0; for(let k of key) { hash += k.charCodeAt(); // hash值的简单算法 } return hash % 100; // 假设最多存100个 } set(key, value) { let index = this.calcKey(key); this.arr[index] = value; } get(key) { let index = this.calcKey(key); return this.arr[index]; } } let map = new Map(); map.set('hello', 'word'); map.set('word', 'hello'); console.log(map.get('hello'));<file_sep>/进阶学习/第六天-数据结构/tree.js // 二叉树 二叉搜索树 // 遍历树 广度 深度 /* 规则:先创建根节点,下一个数和根节点比较,大的放右边,小的放左边 100 200 30 80 70 100 30 200 80 70 */ class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } class Tree { constructor() { this.root = null; } insertTree(currentNode, newNode) { if (newNode.value < currentNode.value) { if (currentNode.left == null) { currentNode.left = newNode; } else { this.insertTree(currentNode.left, newNode); } } else { if (currentNode.right == null) { currentNode.right = newNode; } else { this.insertTree(currentNode.right, newNode); } } } set(val) { let node = new Node(val); if (!this.root) { this.root = node; } else { this.insertTree(this.root, node); } } } // let tree = new Tree(); // tree.set(100); // tree.set(200); // tree.set(30); // tree.set(80); // tree.set(70); // console.log(tree); /* { "root": { "value":100, "left": { "value": 30, "left":null, "right":{ "value":80, "left":{ "value":70, "left":null, "right":null }, "right":null } }, "right":{ "value":200, "left":null, "right":null } } } */ <file_sep>/进阶学习/第三天-ES6/proxy.js // 缺点是兼容性差(IE11以下兼容) let obj = { name: 'shenjp', age: { a: 100 } }; /* 如果设置失败会返回false,如果使用 Object.defineProperty 会直接报错 let obj1 = Object.freeze({a: 1}); let flag = Reflect.defineProperty(obj1, 'a', { value: 100 }); console.log(obj1, flag); */ let handler = { set(target, key, value) { // target[key] = value; // 更新原对象 // // set是要求有返回值的 返回 boolean,告诉他是否成功 // return true; if (key === 'length') { // 如果更新的是长度,就不更新视图 return true; } update(); return Reflect.set(target, key, value); // 使用这个更加语义化,如果失败就会返回false }, get(target, key) { // 当取值的时候,如果还是个对象,就递归调用,将属性进行代理,返回代理后的结果 if (typeof target[key] === 'object' && target[key] !== null) { return new Proxy(target[key], handler); } return Reflect.get(target, key); } } // let proxy = new Proxy(obj, handler); function update() { console.log('update'); } // proxy.age.a = 'hello'; // console.log(obj); let arr = [1, 2, 3, 4]; let proxy = new Proxy(arr, handler); proxy.push(5); // 调用push的时候,会把值放进去,再更改length<file_sep>/手写题.md ## call ```js Function.prototype.call = function(context, ...params) { context = context || window; let type = typeof context; if (!/^(object|function)$/.test(type)) { if (/^(symbol|bigint)$/.test(type)) { context = Object(context); } else { context = new context.constructor(context); } } let key = Symbol('key'); context[key] = this; let result = context[key](...params); delete context[key]; return result; } ``` ## apply ```js Function.prototype.apply = function(context, params) { context = context || window; let type = typeof context; if (!/^(object|function)$/.test(type)) { if (/^(symbol|bigint)$/.test(type)) { context = Object(context); } else { context = new context.constructor(context); } } let key = Symbol('key'); context[key] = this; let result = context[key](...params); delete context[key]; return result; } ``` ## bind ```js (proto => { function myBind(thisArg, ...args) { let _this = this; thisArg = thisArg == undefined ? window : thisArg; return function an(...innerArgs) { if (this instanceof an) { return new _this(...args, ...innerArgs); } return _this.call(thisArg, ...args.concat(innerArgs)); } } proto.myBind = myBind; })(Function.prototype); ``` ## new ```js function _new(Func, ...args) { let obj = Object.create(Func.prototype); let result = Func.call(obj, ...args); return result instanceof Object ? result : obj; } ``` ## 深拷贝 ```js function deepClone2(obj, hash = new WeakMap()) { if (obj !== null && typeof obj !== 'object') { return obj; } if (hash.has(obj)) { return hash.get(obj); } let cloneObj = new obj.constructor; hash.set(obj, cloneObj); for (let key in obj) { if (obj.hasOwnProperty(key)) { cloneObj[key] = deepClone2(obj[key], hash); } } return cloneObj; } ``` ## 节流 ```js function throttle(fun, delay) { let last, deferTimer return function (args) { let that = this let _args = arguments let now = +new Date() if (last && now < last + delay) { clearTimeout(deferTimer) deferTimer = setTimeout(function () { last = now fun.apply(that, _args) }, delay) }else { last = now fun.apply(that,_args) } } } ``` ## 防抖 ```js function debounce(func, wait = 500) { let timer = null; return function() { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { func.apply(this, ...arguments) }, wait) } } ``` ## 快排 ```js function quickSort(arr) { let len = arr.length; if (len <= 1) return arr; let pivot = len / 2 | 0; let pivotValue = arr.splice(pivot, 1)[0]; let leftArr = []; let rightArr = []; arr.forEach(item => { if (item > pivotValue) { rightArr.push(item); } else { leftArr.push(item); } }); return [...quickSort(leftArr), pivotValue, ...quickSort(rightArr)]; } ``` ## 去重 ```js // for for (let i = 0; i < arr.length - 1; i++) { let item = arr[i]; for (let j = i + 1; j < arr.length; j++) { if (item === arr[j]) { arr[j] = arr[arr.length - 1]; arr.length--; j--; } } } console.log(arr); // 对象 let arr = [1, 2, 3, 1, 1, 4, 2, 3]; let obj = {}; for (let i = 0; i < arr.length; i++) { let item = arr[i]; if (obj[item] !== undefined) { arr[i] = arr[arr.length - 1]; arr.length--; i--; continue; } obj[item] = item; } console.log(arr); // set let obj = { y: 200 }; let arr = [obj, 1, 2, 3, 1, obj, 1, 4, 2, 3, '3', { x: 100 }, { x: 100 }]; arr = Array.from(new Set(arr)); console.log(arr); ``` ## instanceof ```js function myInstanceof(left, right) { let prototype = right.prototype; left = left.__proto__ while(true) { if (left === null || left === undefined) { return false; } if (prototype === left) { return true; } left = left.__proto__; } } ``` ## Object.create ```js function create(proto) { function F() {} F.prototype = proto; return new F(); } ``` ## 解析url参数 ```js let url = 'http://www.baidu.com?lx=18&name=shenjp#app'; String.prototype.queryUrlParams = function(name) { /* const searchIndex = this.indexOf('?'); let hashIndex = this.indexOf('#'); let searchText = ''; let hashText = ''; hashIndex = !!~hashIndex ? hashIndex : this.length; searchText = this.substring(searchIndex + 1, hashIndex); hashText = this.substring(hashIndex + 1); */ // 或者使用 a 标签的特性获取对应的属性 let link = document.createElement('a'); link.href = this; let searchText = link.search.substring(1); let hashText = link.hash.substring(1); link = null; const res = {}; if (searchText) { const paramsArray = searchText.split(/(?:&|=)/g); for (let i = 0; i < paramsArray.length; i += 2) { let key = paramsArray[i]; let value = paramsArray[i + 1]; key ? res[key] = value : null; } } hashText ? res['_SHAH'] = hashText : null; return name ? res[name] : res; } // 使用正则 String.prototype.queryUrlParams = function(name) { let obj = {}; this.replace(/([^?&=#]+)=([^?&=#]+)/g, (_, $1, $2) => ($1 ? obj[$1] = $2 : null)); this.replace(/#([^?&=#]+)/g, (_, $1) => ($1 ? obj['_SHAH'] = $1 : null)); return name ? obj[name] : obj; } ``` ## 封装一个数据类型检测 ```js function myTypeof(value) { var typeArray = ['Boolean', 'Number', 'String', 'Function', 'Array', 'Date', 'RegExp', 'Object', 'Error', 'Symbol', 'BigInt'] var class2type = {}; var toString = class2type.toString; typeArray.forEach((name, index) => { class2type[`[object ${name}]`] = name.toLowerCase(); }); if (value == null) { return value + ''; } return typeof value === 'object' || typeof value === 'function' ? class2type[toString.call(value)] || 'object' : typeof value; } ```<file_sep>/进阶学习/第一天/promisify.js let fs = require('fs'); let path = require('path'); // let {promisify} = require('util'); const Promise = require('./promise'); function resolve (dir) { return path.join(__dirname, dir) } /* function read (...args) { return new Promise((resolve, reject) => { fs.readFile(...args, (err, data) => { if (err) reject(err); resolve(data); }); }); } */ /* function read (...args) { let dfd = Promise.defer(); // 延迟对象,可以解决Promise的嵌套问题(原生没有此方法) fs.readFile(...args, (err, data) => { if (err) dfd.reject(err); dfd.resolve(data); }); return dfd.promise; } */ function promisify (fn) { return function (...args) { return new Promise((resolve, reject) => { fn(...args, (err, data) => { if (err) reject(err); resolve(data); }) }) } } // 可以将异步的方法转为Promise let readFile = promisify(fs.readFile); readFile(resolve('./name.txt'), 'utf8').then(data => { console.log(data); }) .catch(err => { console.log(err); })<file_sep>/第一天/数据类型.md ## 学习方法: 1. 温故而知新 2. 多练习 3. 纵向和横向发展 1. 多接触一些非技术类的知识,比如管理学 2. 多参与开源讨论 3. 研究源码 ## 课程类容: - js中的数据类型 7+2 - 数据类型分类 - 检测数据类型 - 加号 ## 数据类型: - 基本数据类型: + Number + String + Boolean + Null + Undefined + Symbol + Bigint - 引用数据类型 + object + 普通对象 + 数组对象 + 正则对象 + 日期对象 + Math对象 + ... + function(每一个函数的的 __proto__指向Function.prototype) ## 数据类型的检测 - typeof 检测数据类型的逻辑运算符 - instanceof 检测是否为某个类的实例 - constructor 检测构造函数 - Object.prototype.toString.call() 检测数据类型 typeof [value] 返回当前指的数据类型 是个字符串, 特殊 typeof null = 'object' typeof function(){} == 'function' - 返回的结果都是字符串 - 局限性: - typeof null => "object" - typeof 不能细分对象类型,检测普通对象和数组对象,都是object ```js let a = typeof typeof typeof [1, 2]; console.log(a); // "string" ``` ## 数字类型 - NaN 不是一个有效数字 - Infinity 无穷大的数,有正负之分 NaN 和谁都不相等,NaN !== NaN; isNaN(value) 检测这个值是否为有效数字,如果不是有效数字,返回true,是有效数字返回false ```js let res = parseFloat('left:200px;'); // => NaN if (res == 200) { console.log(200); } else if (res == NaN) { console.log('NaN'); } else if (typeof res == 'number') { console.log('number'); } else { console.log('Invalid number'); } // "number" ``` ## 把其他类型的值转为数字 - 强转换(基于底层机制转换)Number([value]) - 一些隐式转换都是基于Number完成的 - isNaN('12px'); 先转为数字再检查 - 数学运算 '12' - 2 - 字符串 == 数字 - 弱转换(基于一些额外的方法)ParseInt([value])/parseFloat([value]) ```js parseInt(''); // NaN // 从左侧的第一个数字开始找,知道非字符结束,无果没找到数字则是 NaN Number(''); // 0 // 直接调用浏览器最底层的机制转换,字符串中都是有效数字才会转为数字,否则为NaN,特殊 '' => 0, null => 0, undefined => NaN isNaN(''); // flase // 先把字符串转为数字(Number) parseInt(null); // NaN Number(null) // 0 isNaN(null); // false parseInt('12px'); // 12 Number('12px'); // NaN isNaN('12px'); // NaN parseFloat('1.6px') + parseInt('1.2px') + typeof parseInt(null) // 1.6 + 1 + number = 2.6number isNaN(Number(!!Number(parseInt('0.8')))); // false typeof !parseInt(null) + !isNaN(null); // boolean + true = booleanstrue ``` ```js let result = 10 + false + undefined + [] + 'Tencent' + null + true + {}; // 10 + 0 + NaN + 0 + 'Tencent' + 'null' + 'true' + '[object Object]' // NaNTencentnulltrue[object Object] ``` ## == 比较转换规则 - 对象 == 字符串 对象转换为字符串 - null ==undefined 但是和其他值都不相等 - 剩下的两边都转为数字<file_sep>/进阶学习/第七天-eventloop-commonjs/homework.js // 1. 反柯理化 目的是扩大函数的作用范围 const { resolve } = require("path"); const { reject } = require("async"); // let res = Object.prototype.toString.call({name: 'shenjp'}); // console.log(res); function uncurring(fn) { return function(context, ...args) { // return fn.call(context, ...args); // 直接调用可能会调用别人实例上的方法 // 保证一定是调用的原型上的方法 // 将fn执行,并且将后续的参数传递给apply方法 // return Function.prototype.apply.call(fn, context, args); // 以上方法可以用Reflect简写 return Reflect.apply(fn, context, args); } } let toString = uncurring(Object.prototype.toString); let res = toString({name: 'shenjp'}); // console.log(res); let join = uncurring(Array.prototype.join); let res2 = join([1, 2, 3, 4], ':'); // console.log(res2); // 2. promise.race // 多个Promise,谁先执行完,就执行谁的 let p1 = new Promise((resolve) => { setTimeout(() => { resolve('p1 resolve'); }, 100); }); let p2 = new Promise((resolve) => { setTimeout(() => { resolve('p2 resolve'); }, 200); }); function isPromise(value) { return value instanceof Promise; } Promise.race = function(promises) { return new Promise((resolve, reject) => { if (!Array.isArray(promises)) { throw new TypeError('promises is not Array'); } promises.forEach((current) => { if (isPromise(current)) { current.then(resolve, reject); } else { resolve(current); } }) }) } // Promise.race([p1, p2]).then(res => { // console.log(res); // }) // 3. wrap 可以包裹一个Promise,并且给这个Promise提供一个abord方法,可以让Promise变成失败态 function wrap(p1) { // 在内部再构建一个Promise,这个Promise,我可以将他的失败方法暴露在abort上 // 如果用户调用了abort,会让这个Promise.race立即失败 let abort = null; let p = new Promise((resolve, reject) => { abort = reject; }) let newPromise = Promise.race([p1, p]); newPromise.abord = abort; return newPromise; } let p = wrap(new Promise((resolve, reject) => { setTimeout(() => { resolve('ok'); // 走完后只是抛弃掉了 }, 3000); })); p.then((data) => { console.log(data); }, err => { console.log(err); }) // 如果超过2s,这个Promise的成功结果就不要了 setTimeout(() => { p.abord('超时'); }, 5000); // finally Promise.prototype.finally = function(callback) { // finally 是then的简写 return this.then((value) => { // Promise.resolve 具备等待效果 return Promise.resolve(callback()).then(() => value); }, (err) => { return Promise.resolve(callback()).then(() => {throw err}); }); } Promise.reject('123').finally(() => { console.log('finally ok'); return new Promise((resolve) => { // 这里可以返回Promise,下一个.then 执行会等这里的Promise执行完之后再往下走 setTimeout(() => { resolve('ok'); }, 3000); }) }).catch(err => { console.log(err); }); // try 如果代码是同步的,如果出错了,我希望是同步执行 function fnc() { throw new Error('1122'); } Promise.resolve(fnc()).catch(err => { // then是异步的,会延迟抛出错误 console.log('..........', err); }); console.log(456); // mergeOptions function mergeOptions (o1, o2) { if (typeof o1 !== typeof o2 || o1.constructor !== o2.constructor) { return o2; } // 数组 对象 if (Array.isArray(o1)) { return [...new Set([...o1, ...o2])]; } // 其他的就是对象 for (let key in o2) { if (o1.hasOwnProperty(key) && typeof o2[key] === 'object') { mergeOptions(o1[key], o2[key]); } else { o1[key] = o2[key]; } } return o1; } let obj1 = {a: 1, d: [1, 2, 3]}; let obj2 = {a: 2, b: 3, c: {a: 1}}; let res = mergeOptions(obj1, obj2); console.log(res); <file_sep>/进阶学习/第五天-类的继承/ES6/src/class.js class Animal { constructor(name) { this.name = name; // 类的实例化检测 if (new.target === Animal) { // 说明new的是自己 throw new Error('not new'); } } say() { console.log('say'); } } // extends = apply + Object.create + __proto__ class Tiger extends Animal { // 如果子类没有写constructor,会自动将参数传给父类 constructor(name) { super(name); // 调用父类的方法,这里的super指的就是父类 } say() { super.say(); // super 指父类的 prototype } static a() { // 静态方法中的super指向父类 return super.a(); } } let tiger = new Tiger('老虎'); console.log(tiger.name, tiger.say()); // 抽象类:可以被继承,但是不能被new<file_sep>/第十二天/JQ源码分析.md ## JQ 中核心的基础内容,JQ选择器 - 基于选择器。机票去到需要操作的DOM元素,获取到的是一个JQ对象 - 接下来可以调用JQ上提供的方法来实现操作 - 样式操作 css/addClass/removeClass/toggleClass/hasClass... - 筛选:filter/children/find/sibling/prev/prevAll/nextAll... - DOM增删改:text/html/appent/val/appentTo/insterBerfore/remove... - 操作属性的:attr/removeAttr/prop... - 动画:stop/finish/animate/show/hide/toggle/faseIn... - 事件:on/bind/unbind/off/delgate... - JQ中还提供了额外的方法 - $.ajax() - $.each() - $.extend() - $.type() - ... ```js /* typeof window !== "undefined" ? window : this 判断浏览器是否存在winodw */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // 此条件成立,说明是基于 commonjs 也即是node端 } else { factory( global ); } })(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { var jQuery = function( selector, context ) { return new jQuery.fn.init( selector, context ); }; jQuery.fn = jQuery.prototype = { constructor: jQuery // 重定向之后会丢失constructor } var init = jQuery.fn.init = function( selector, context, root ) { } jQuery.extend = jQuery.fn.extend = function() {} init.prototype = jQuery.fn; if ( typeof noGlobal === "undefined" ) { window.jQuery = window.$ = jQuery; } }) /* 我们在导入JQ后,使用的$就是闭包中的jQuery $('.box'); 选择器执行其实就是让jQuery执行 jQuery(seleator选择器, context获取当前元素的上下文) 返回的结果是 jQuery.fn.init(init)这个类的实例,基于 __proto__ 找到 init.prototype。而 init.prototype 是jQuery.prototype 可以说创建的实例就是jQuery这个类的实例(俗称JQ对象) 可以调用jQ原型上的方法 JQ把方法放到了两个部分 jQuery.prototype:$('xxx').xxx(); jQuery:$.(xxx) 项目中红尽可能把获取到的结果存起来。因为每一次执行都是创建一个全新的实例 */ ``` <file_sep>/进阶学习/第四天-模块/src/a.js const a = 1; export { // 不是对象,叫接口列表 a }; export default 'hello'<file_sep>/第七天/作业讲解.md ```js !(!"Number(undefined)"); // true isNaN(parseInt(new Date())) + Number([1]) + typeof !(null); // true + 1 + 'boolean' = '2boolean' Boolean(Number("")) + !isNaN(Number(null)) + Boolean("parseInt([])") + typeof !(null); // false + true + true + 'boolean' = '2boolean' parseFloat("1.6px") + parseInt('1.2px') + typeof parseInt(null); // 1.6 + 1 + 'number' = '2.6number' isNaN(Number(!!Number(parseInt('0.8px')))); // isNaN(0) = false !typeof parseFloat('0'); // !'number' = false !typeof "parseInt(null)" + 12 + !!Number(NaN); // false + 12 + false = 12 !typeof (isNaN("")) + parseInt(NaN); // false + NaN = NaN typeof !parseInt(null) + !isNaN(null); // 'boolean' + true = 'booleantrue' ``` ```js var x = 1; function func(x, y = function anonymouse1() {x = 2}) { x = 3; y(); console.log(x); // 2 } func(5); console.log(x); // 1 var x = 1; function func(x, y = function anonymouse1() {x = 2}) { // 1. 只有在函数执行的时候,如果设置了形参变量,并且给部分形参变量赋默认值,就会形成块级作用域,函数大括号看做一个块级上下文 // 2. 当前形参变量在当前大括号中形参被重新使用var声明过 var x = 3; y(); console.log(x); // 3 } func(5); console.log(x); // 1 var x = 1; function func(x, y = function anonymouse1() {x = 2}) { var x = 3; y = function anonymouse1() {x = 4} y(); console.log(x); // 4 } func(5); console.log(x); // 1 ``` ```js /* ES3 中创建变量使用的是 var ES6 中创建变量使用的是 let / const */ ``` <file_sep>/第十五天/js/countDown.js /* 拿当前时间和目标时间对比,计算出差值 new Date() 获取的是客户端本地的时间(这个时间客户可以改) 倒计时抢购的当前时间以服务器时间为准(服务器返回的响应头信息中有服务器时间) 思路:加载页面先从服务器获取时间(尽可能减少时间差),使用HEAD请求更快,把获取的时间存起来,以后每隔一秒让获取的时间累加 */ let target = new Date('2020/7/28 07:31:00'), now = new Date(), timer = null; let spanBox = document.getElementById('spanBox'); function queryServerTime() { let xhr = new XMLHttpRequest(); xhr.open('HEAD', './js/data.json?_=' + now); xhr.onreadystatechange = function() { if (xhr.status >= 200 && xhr.status < 400) { if (xhr.readyState === 2) { // 把服务器获取到的格林尼治时间 GMT 转为北京时间 GMT+0800 now = new Date(xhr.getResponseHeader('date')); computed(); // 计算时间差 // 每隔一秒让时间累加 interval(); } } } xhr.send(); } function computed () { let spanTime = target - now; if (spanTime <= 0) { spanBox.innerHTML = '00:00:00'; clearTimeout(timer); timer = null; return; } let hours = Math.floor(spanTime / (60 * 60 * 1000)); spanTime = spanTime - (60 * 60 * 1000) * hours; let minutes = Math.floor(spanTime / (60 * 1000)); spanTime = spanTime - (60 * 1000) * minutes; let seconds = Math.floor(spanTime / 1000); spanBox.innerHTML = `${zero(hours)}:${zero(minutes)}:${zero(seconds)}`; } function zero (num) { return num < 10 ? ('0' + num) : num; } function interval () { timer = setTimeout(() => { // 在自身的基础上加1秒 now = new Date(now.getTime() + 1000); computed(); if (timer) { interval(); } }, 1000); } queryServerTime();<file_sep>/第十一天/函数的三种角色.md ```js /* EC(G): 声明加定义: Foo, getName 声明: getName */ function Foo() { // 0x0001 getName = function() { console.log(1); } return this; } Foo.getName = function() { console.log(2); } Foo.prototype.getName = function() { console.log(3); } var getName = function() { console.log(4); } function getName() { console.log(5); } /* 代码执行: Foo -> 0x0001 Foo.getName -> 2 getName -> 4 */ Foo.getName(); // 2 /* Foo私有的属性 => 2 */ getName(); // 全局下的getName执行 => 4 Foo().getName(); // 1 /* 先执行Foo() 将全局下的 getName 改为 -> 1 返回this => widnow 在执行window.getName -> 1 */ getName(); // 1 /* 全局下的getName已经在上一步改为1函数了 结果就是 1 */ new Foo.getName(); // 2 /* 运算符优先级的问题,参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Operator_Precedence new xxx 如果加括号 优先级是 19 new xx 如果不加括号 优先级是 18 成员访问的优先级是 19 所以这里会先执行 Foo.getName() 在执行 new Foo.getName() => 2 new 执行后的结果,不会打印了 */ new Foo().getName(); // 3 /* 优先级问题:此时是有参数的new,所以此时先执行 new Foo() 在执行 xx.getName() new Foo() 返回Foo的实例。再执行 实例.getName() => 也就是指向 Foo.prototype.getName => 3 */ new new Foo().getName(); // 3 /* 先执行 new Foo(), 再执行 new (new Foo()), 最后执行 (new (new Foo())).getName(); new Foo(), 返回Foo的实例。在执行new 实例,再执行 Foo.prototype.getName => 3 */ ``` ## 函数的三种角色 通过上面的题可以看出: 1. 函数可以作为一个普通函数执行 2. 函数可以做为一个构造函数执行,返回该函数的实例 3. 函数可以作为一个对象,可以再上面添加私有属性<file_sep>/进阶学习/第一天/回调.js // node 中的文件操作都是异步的 let fs = require('fs'); // 异步的解决方案,最早是基于回调函数的 fs.readFile('./age.txt', 'utf8', function(error, data) { console.log(error, data); // renderObj['age'] = data; out('age', data); }); fs.readFile('./name.txt', 'utf8', function(error, data) { console.log(data); // renderObj['name'] = data; out('name', data); }); let out = after(2, function(renderObj) { console.log(renderObj); }) function after(times, callback) { let renderObj = {}; return function(key, data) { // out renderObj[key] = data; if (--times === 0){ callback(renderObj); } } } // 发布订阅 // 观察者模式<file_sep>/进阶学习/第六天-数据结构/stack.js // 栈 class Stack { constructor() { this.arr = []; } push(element) { // 入栈 this.arr.push(element); } pop() { // 出栈 return this.arr.pop() } } let stack = new Stack(); // 增删改查的方法 queue.stack(1); queue.stack(2); queue.stack(3); queue.stack(4); console.log(queue.arr); console.log(queue.pop()); console.log(queue.arr);<file_sep>/第十四天/输入URL到渲染的过程.md ## 当用户在浏览器地址栏输入一个网址,到看到整个页面,中间都经历了哪些事情 1. URL解析(客户端完成) 2. DNS域名解析(DNS服务器) 3. 建立TCP连接(3次握手) 4. 发送HTTP请求 5. 服务器处理,服务器基于HTTP响应客户端需要的内容 6. 关闭TCP的连接通道(4次挥手) 7. 客户端渲染 ![解析过程](./解析过程.png) ## URL 组成部分 > 区分 URI/URL/URN 1. URI = Universal Resource Identifier 统一资源标志符 2. URL = Universal Resource Locator 统一资源定位符 3. URN = Universal Resource Name 统一资源名称 [URI/URL/URN参考链接](https://www.jianshu.com/p/09ac6fc0f8cb) 协议:// 域名 :端口号/请求的路径名称?问号传参 #哈希值 http://www.baidu.com:80/home/index.html?type=1&query=hello#video 传输协议:就是用来在服务器和客户端之间进行信息传入的 - http 超文本传输协议 - https 比http更安全(里面涉及了SSL加密) - ftp 文件上传下载协议(把文件上传到服务器) > 推荐图解HTTP:HTTP1.1/1.0/2.0 https VS http 域名:顶级域名,一级域名,二级域名 ... - www.qq.com 顶级域名(有的也叫一级域名) - sport.qq.com 二级域名 - kbs.sport.qq.com 三级域名 ? 传参:应用场景比较多 - 客户端想把信息传递给服务器(GET系列请求) - 从客户端A页面跳转到B页面,两个页面就可以通过 ? 传参 - 编码/解码 - encodeURI/decodeURI -- 对整个URL处理,把里面的汉字和特殊字符进行编码、解码 - encodeURIComponent/decodeURIComponent -- 对所有的符号进行编码、解码,一般只针对参数处理 - escape/unescape -- 这个一般只在客户端使用 哈希 # - hash 路由 - 锚点定位 ## DNS解析 - 本地的DNS解析(缓存) - 客户端 -> 浏览器缓存 -> 本地的hosts文件 -> 本地DNS解析器缓存 -> 本地DNS服务器 - 网络DNS解析 ## TCP 三次握手(客户端和服务端建立链接) ![三次握手](./三次握手.png) ## TCP 四次挥手(TCP关闭链接) ![四次挥手](./四次挥手.png) <file_sep>/进阶学习/第四天-模块/es5-class.js // prototype __proto constructor // es5中没有类,只有构造函数,可以把一个函数当做类 // 实现只能通过new来调用 var Animal = (function() { // 用ES5来模拟一个ES6的类型。也就是不能直接调用,只能通过new来调用 function Animal() { if (!(this instanceof Animal)) { throw new Error('不是new调用的'); } this.name = 'shenjp'; } // 给原型上添加方法 defineProperty(Animal, [ { key: 'say', value: function() {} }, { key: 'et', value: function() {} }, ], [ { key: 'getAge', value: function() { console.log('static'); } } ]) return Animal; })(); function defineProperty (Constructor, protoProps, staticProps) { if (protoProps) { define(Constructor.prototype, protoProps); } if (staticProps) { define(Constructor, staticProps); } } function define(target, props) { if (Array.isArray(props)) { for (let i = 0; i < props.length; i++) { let property = props[i]; Object.defineProperty(target, property.key, { enumerable: true, configurable: true, ...property }); } } } /* function Animal() { this.name = 'shenjp'; } Animal.prototype.say = function() { // 标识公共方法 console.log('heheh'); } */ let animal = new Animal(); // 如果没有返回值,构造函数中的this,默认指向实例,如果返回了引用类型的值,则this指向返回的结果 console.log(Animal.prototype); Animal.getAge(); // Animal(); 不能直接调用<file_sep>/进阶学习/第三天-ES6/deepClone.js // 深拷贝 let obj = { name: 'shenjp', age: { a: 18, b: 19 } }; // 最简单的拷贝,使用JSON.stringfy 和JSON.parse // JSON 只能拷贝基本的值。不支持函数,正则,日期,undefined // let newObj = JSON.parse(JSON.stringify(obj)); // console.log(newObj === obj); //false // 递归拷贝对象(函数一般不拷贝) function deepClone(obj, hash = new WeakMap()) { if (obj == null || typeof obj !== 'object') { // 如果是null 或者undefined直接返回 // 基本数据类型:string, number, boolean, symbol,bigInt return obj; } // 正则,日期的typeof也是 object if (obj instanceof RegExp) { return new RegExp(obj); } if (obj instanceof Date) { return new Date(obj); } if (hash.get(obj)) { // 如果映射表中存在,直接将结果返回 return obj; } // obj 可能是 [] 或者 {} let cloneObj = new obj.constructor; hash.set(obj, cloneObj); // 如果不存在就创建映射 for (let key in obj) { if (obj.hasOwnProperty(key)) { // 只拷贝实例上的属性 // 可能当前项还是一个应用类型 // 这里要防止循环引用导致的死循环 cloneObj[key] = deepClone(obj[key], hash); } } return cloneObj; } // let newObj = deepClone(obj); // newObj.age.a = 100; // console.log(newObj); let obj1 = {a: 1}; obj1.b = obj1; // 循环引用问题 <file_sep>/第十四天/浏览器缓存.md ## 页面优化 - 减少DNS请求次数 - DNS预获取 + 浏览器遇到 `<link rel="dns-prefetch" href="//static.360buyimg.com">` 会派另一个线程去解析DNS,浏览器会继续渲染页面 + 允许的最大并发数是 6-7 个 - 减少HTTP请求次数和资源大小 - 资源合并压缩 - 字体图标 - Base64 - Gzip(一般文件能压缩60%以上) - 图片懒加载 - 数据延迟分批加载 - CDN资源 - 应用缓存 ## 缓存 1. 资源缓存 - 强缓存 - 每一次向服务器发送请求获取资源文件,都会先看一下本地是否有缓存(先看是否有强缓存,没有再去看是否有协商缓存,都没有才是重新获取资源) - 协商缓存 2. 数据缓存 - GET请求缓存(一般不要,因为是不可控的) - 第一次获取数据,如果这些数据不是需要经常更新的,我们会基于本地存储把数据缓存起来,在一定时间内,再加载页面,直接从本地缓存获取数据 缓存的位置: - Service Worker 浏览器独立线程缓存(一般很少用) - Memory Cache 内存缓存 - Disk Cache 硬盘缓存 - Push Cache 推送缓存(http2中的) 打开网页,地址栏输入地址,差汇总啊disk cache 中是否有匹配,如果有则使用,如果没有则发送请求 ## 强缓存 Expries/Cache-Control 常用的是 Cache-Control(HTTP/1.1): max-age=0 Cache-Control: `Cache-Control:max-age=2592000` 第一次拿到资源后的 2592000(30天) 秒内,再次发送请求,读取缓存中的信息(HTTP/1.1) Expries (HTTP/1.0) 如果两个都设置,以 Cache-Control 为主,如果不支持再走Expries 浏览器向服务端发请求后,服务端会设定 Cache-Control 和Expries ,浏览器看到这两个字段后就会把资源强制缓存起来 ![强制缓存](./强缓存.png) ## 协商缓存 Last-Modified(HTTP/1.0)/ETag(HTTP/1.1) 协商缓存就是强制缓存失效后,浏览器携带缓存标识想服务器发送请求,由服务器根据缓存标识觉得是否使用缓存的过程 协商缓存是存在HTTP请求的,如果协商缓存生效,返回 304 和 Not Modified ![协商缓存](./协商缓存.png) ### Last-Modified和If-Modified-Since 第一次访问资源,服务器返回资源的同时,响应头中设置Last-Modified(服务器上的最后修改时间)浏览器收到后,缓存文件和响应头,下一次请求这个资源时,浏览器检测有 Last-Modified ,于是就会添加 If-Modified-Since 请求头,值是 Last-Modified 中的值,服务器再次收到这个请求,会根据 If-Modified-Since 中的值与服务器最后修改的时间对比,如果没有变化,返回 304 和空的响应体,浏览器直接从缓存取。如果 If-Modified-Since 小于服务器中这个资源的最后修改时间,于是返回资源文件和 200。但是Last-Modified 只能以秒计,如果在不可感知的时间内修改了文件,那么服务器还是会认为命中了缓存,并不会返回资源。 ### Etag和If-None-Match 第一次请求资源,服务器会返回资源文件的一个唯一标识(由服务器生成)只要资源变化,Etag就会重新生成,下一次加载资源向服务器发送请求时,会将上一次返回的的Etag放在 If-None-Match 中,服务端只需要比较客户端传来的 If-None-Match 跟自己服务器上生成的Etag是否一致,就能很好的判断出,当前的资源相对于客户端是否发生变化过,如果Etag是一直的,那直接返回304和空的响应体,如果不一样,则返回200,将Etag设置为最新的标识。 <file_sep>/进阶学习/第三天-ES6/set.js // set 代表的是集合, map 代表 hash表 // 集合就是不能有重复的项,数组去重 new Set() let set = new Set([1, 1, 2, 3, 4, 4, 4]); // 他的key 和值是一样的 console.log(set); // 数据结构的增删改查 console.log(set.entries()); // Object.keys() Object.value() Object.entries(); let obj = { a: 1, b: 2, [Symbol()]: 100 }; console.log(Object.keys(obj)); // 无法取到Symbol console.log(Object.getOwnPropertySymbols(obj)); // 只能取Symbol // 以后所有的 Object.xxx 都会变成 Reflect.xxx console.log(Reflect.ownKeys(obj)); // [ 'a', 'b', Symbol() ] // 如何求两个数组的 并集,差集,交集 let arr1 = [1, 2, 3]; let arr2 = [3, 4, 5]; // 并集 let union = [...new Set([...arr1, ...arr2])]; console.log(union); // 交集 // let s1 = new Set(arr1); // let s2 = new Set(arr2); // let intersection = [...s1].filter(value => { // return s2.has(value); // }); // console.log(intersection) // 差集 let s1 = new Set(arr1); let s2 = new Set(arr2); let def = [...s1].filter(value => { return !s2.has(value); }); console.log(def)<file_sep>/第十天/关于Function和Object的关系.md ## Function.prototype ![Function和Object的关系](./Function和Object的关系.png) - 每一个函数(包括内置函数)都是Function 的一个实例,所以它们的__proto__一定是Function.prototype - 每一个对象(包含原型对象)都是Object的实例,所以最后它们基于__proto__一定都可以找到Object.prototype ```js Function instanceof Function => true Function.prototype === Function.__proto => true // Object 作为一个类(一个函数)它是Function的实例,Function 虽然是函数(类)但是它也是一个对象,所以它是Object的实例 ``` ```js Function instanceof Function => true Function.prototype === Function.__proto => true // Object 作为一个类(一个函数)它是Function的实例,Function 虽然是函数(类)但是它也是一个对象,所以它是Object的实例 ```<file_sep>/第十三天/DOM事件基础.md ## DOM基础知识 - 什么是事件,什么是事件绑定? - 浏览器自带的事件 经典面试题: window.onload 和 document.ready (JQ.$(document).ready())的区别? 1. load 是等待所有资源都加载完成,才会触发执行,而我之前研究过部分JQ的源码 $(document).ready() 是用的 DOMContentLoaded 时间时间本身是DOM结构加载完成就会触发执行,所以他要优先于window.onload触发 2. window.onload 是基于DOM0级绑定,整个页面只能绑定一次,所以页面只能用一次,而JQ中是基于 DOM2级完成的,所以在一个页面中可以绑定多个不同的方法,也就是多次使用,我之前在JQ开发中,经常把编写的代码放在 $(function() {}),既能形参闭包,又可以等DOM结构加载完才会执行 3. 不论哪一种办法都是保证dom结构加载完才会执行,这样在方法中肯定能获取到元素,防止把js放在DOM之前加载。(引申问题:JS/CSS/IMG 结构加载的顺序和机制,浏览器渲染机制)<file_sep>/进阶学习/第六天-数据结构/linkList.js // 链表 class Node { constructor(element) { this.element = element; this.next = null; } } class LinkList { constructor() { this.head = null; // 头指针 this.length = 0; // 链表的长度 } // 新增 append(element) { let node = new Node(element); if (!this.head) { this.head = node; } else { let current = this.head; while (current.next) { // 不停的找next current = current.next; } current.next = node; } this.length++; } // 插入 insert(position, element) { checkPosition(position, this.length); let node = new Node(element); if (position === 0) { let oldNode = this.head; this.head = node; node.next = oldNode; } else { let current = this.head; let previous = null; let index = 0; while (index++ < position) { previous = current; current = current.next; } previous.next = node; node.next = current; } this.length++; } // 删除 del(position) { checkPosition(position, this.length); if (position === 0) { let oldNode = this.head; this.head = oldNode.next; } else { let current = this.head; let previous = null; let index = 0; while (index++ < position) { previous = current; current = current.next; } previous.next = current.next; } this.length--; } // 修改 modifiy(position, element) { checkPosition(position, this.length); let current = this.head; let index = 0; while (index++ < position) { current = current.next; } current.element = element; } } function checkPosition(position, length) { if (typeof position !== 'number') { throw new Error('position is not a number'); } if (position < 0 || position >= length) { throw new Error('position out of limit'); } } // 方便对链表中的元素进行操作 let linkList = new LinkList(); linkList.append(1); linkList.append(2); linkList.append(3); linkList.insert(1, 'hello'); linkList.del(0) linkList.modifiy(0, 'word'); console.log(linkList); /* element element element next -----> next --------> next 上一个数据的next指向下一个数据的next */<file_sep>/第十三天/index.js function fun(num) { let res = [[]]; for (let i = 0; i < num.length; i++) { let len = res.length; for (let j = 0; j < len; j++) { res.push(res[j].concat([num[i]])) } } return res; } var arr = [1, 2, 3, 4, 5] console.log(fun(arr));<file_sep>/进阶学习/第七天-eventloop-commonjs/node.js // node 能干什么? // 可以写一些工具库 // node 中间层,基于JavaScript,运行时 runtime ,node只包含了 ECMAScript + 内置的模块,创建高性能的web服务 // 缺陷:安全和稳定性,只适合做 I/O密集型的,比如文件读写 // node 单线程(I/O密集型)异步非阻塞I/O 事件驱动,可以实现高并发(同一时间内多个请求) // 多线程的好处:可以再同一时间内处理多个请求,通过时间片切换 // node 适合 web服务器,调取接口,访问文件的这种 I/O惨景,如果复杂的情况下,可能会导致阻塞,node 可以开启子进行 /* 多线程:同步 阻塞 单线程:异步 非阻塞 */ /* const cpus = require('os').cpus().length; // 获取cup的核数 console.log(cpus); */<file_sep>/第十四天/微前端.md ## 微前端 - Single-spa - qiankun<file_sep>/进阶学习/第七天-eventloop-commonjs/module.js // node 中使用 module.exports require /* 模块化的作用: 方便维护,隔离作用域,防止命名冲突 */ /* commonjs 规范 1. 每个文件都是一个模块 2. 需要使用 module.exports 导出 3. 别人使用就是 require */ /* require 的核心是读取文件 先读取文件 module.exports = 'hello'; 再给外面包一个自执行的函数 (function(exports, require, module, __dirname, __filename) { module.exports = 'hello'; return module.exports; })() */ const str = require('./module/a'); console.log(str); /* 1. Module._load 加载某个模块 2. Module._resolveFilename 解析文件名 3. new Module 创建一个新的模块 4. tryModuleLoad 尝试加载模块 */<file_sep>/第四天/闭包的应用.md ```js let x = 5; function fn(x) { return function (y) { console.log(y + (++x)); } } let f = fn(6); f(7); // 7 + (++6) = 14 fn(8)(9); // 9 + (++8) = 18; f(10); // 10 + (++7) = 18; console.log(x); // 5 /* 1. 创建一个函数 2. 把函数的堆内存地址作为值返回 */ ``` ```js let i = 10; console.log(5 + i++); /* 先计算 5 + i 的值。那当前的原始值计算 计算完之后再让 i 的值加1 所以此时的值 5 + i = 15 i++ = 11 即使是 5 + (i++); 也是用上面的规则运算 */ console.log(5 + (++i)); /* 先计算 ++i 的值,再计算 5 + i 的值 */ ``` ```js let a = 0, b = 0; function A(a) { A = function (b) { alert(a + b++); } alert(a++); } A(1); A(2); ``` ![画图讲解](./作业二.png) ```js var x = 3; obj = { x: 5 }; obj.fn = (function() { this.x = ++x; return function (y) { this.x *= (++x) + y; console.log(x); } })(); var fn = obj.fn; obj.fn(6); // 5 this指向obj fn(4); // 50 this指向window /* obj = { x: 6, fn: function (y) { this.x *= (++x) + y; console.log(x); } } 5 * (5 + 6) = 55 x = 5; 5 * (6 + 4) = 50; x = 50 */ ```<file_sep>/第七天/闭包的高级应用-柯理化.md ## 柯理化 -- 预先存储或者叫预先处理 ```js function fn(x, y) { // 第一次执行函数,形成一个临时不被释放的上下文,在闭包中我们保存下来传递的信息,当后期小函数执行的时候,可以根据作用域机制,找到闭包中存储的信息,并且拿来使用,所以形成的闭包类似于预先把一些信息进行存储 return function (z) { // 最后执行的时候,要把之前的值和新的值累加 return x + y + z; } } let res = fn(1, 2)(3); console.log(res); // 6 ``` ### Function.prototype.bind 预先处理this,利用的就是柯理化函数 ### redux/react-redux 也是大量使用了柯理化函数 <file_sep>/第十天/call的应用.md ## call的实现 ```js Function.prototype.call = function(context, ...params) { // 在非严格模式下不传,传null,传undefined 都是window context = context || window; // 核心原理,给context设置为一个属性名(属性名尽可能保持唯一, 避免这里设置的属性覆盖对象中的结构,例如用 Symbol, 也可以创建一个时间撮),属性值一定是我们要执行的函数(this),处理完之后别忘记把给context设置的属性删除掉 // 如果context是基本类型的值,是不能设置属性的,这里需要把基本类型的值,修改为引用类型的值 let type = typeof context; if (!/^(object|function)$/.test(type)) { if (/^(symbol|bigint)$/.test(type)) { context = Object(context); } else { context = new context.constructor(context); } } let key = Symbol('key'); context[key] = this; let result = context[key](...params); delete context[key]; // 用完之后删除 return result; // 将执行的访问结果返回 } let obj = { name: 'shenjp' }; function func(x, y) { console.log(this, x, y); } func.call(obj, 10, 20); ``` ```js /* 创建一个值的两种方式: 一、字面量的方式创建 二、构造函数的方式创建 对于引用类型的值来说,两种方式创建的是指没有区别。但是对于值类型,字面量创建的方式创建的是基本类型的值,构造函数创建的是对象类型的值,不管是基本类型的值,还是对象类型的值,都是所属类的实例,都可以调用原型上的方法 区别就是:基本类型的值无法设置属性,对象类型的值可以设置属性 */ let num1 = 1; let obj1 = { a: 1 }; console.log(num1, obj1); // 1 {a: 1} num1.a = 1; console.log(num1.a); // undefined // 无法设置 let num2 = new Number(1); let obj2 = new Object({ a: 1 }); console.log(num2, obj2); // Number {1} {a: 1} num2.a = 1; console.log(num2.a); // 2 ``` ## 阿里面试题 ```js function fn1() { console.log(1); } function fn2() { console.log(2); } fn1.call(fn2); // 1 fn1.call.call(fn2); // 2 Function.prototype.call(fn1); // Function.prototype.call.call(fn1);// 1 /* fn1.call(fn2) 把call方法执行 this => fn1 context => fn2 fn2[key] = fn1; fn2[key]() 结果输出1,fn1 中的this指向fn2 fn1.call.call(fn2) fn1.call => call函数 最后一个call执行 this => calss函数 context => fn2 fn2.xx = call函数 fn2.xxx() 让call函数执行,call函数中的this变成了fn2 this => fn2 context => undedined => window window.xx = fn2 window.xx() 结果输出2,fn2中的this指向window Function.prototype.call(fn1) Function.prototype 是一个匿名空函数 this => Function.prototype context => fn1 fn1.xx = Function.prototype fn1.xx() => 空函数执行后,什么也不会输出 Function.prototype.call.call(fn1); Function.prototype.call 是一个call函数,执行的是最后一个call函数 this => call函数 context => fn1 fn1.xxx => call函数 fn1.xxx(); 让call函数执行,call中的this变为fn1 第二次:this => fn1 context => undefined => window window.xx = fn1 window.xx() 结束输出1,this指向window */ ```<file_sep>/进阶学习/第二天/src/main.js /* 模块化解决的问题: 命名冲突,之前是靠命名空间,采用自执行函数的方式 解决代码的高内聚低耦合 cmd => seajs amd => require.js umd 统一模块 node模块 commonjs规范 使用一个模块 require 给别人用 module.exports es6模块规范 esModule umd 使用模块 import,给别人用 export */ // 如果通过相对路劲引用,表示自定义的模块 // import 特点,可以变量提升,在定义之前可以直接使用,不能放在作用域下,只能放在顶层 // import * as obj from './a.js' // import obj, {a, b} from './a.js'; // 默认的可以单独写,剩下的采用结构 import {a, b, default as obj} from './a.js'; // default是关键字,重命名使用 as /* // 这样引用会报错 { import { a } from './a.js' } */ console.log(obj, a, b); // 每次拿到的是变量对应的值 /* 默认import语法叫静态语法,只能在顶层先声明,再使用 require 是动态语法 新的语法 import() 可以实现动态加载。可以拿来做懒加载,返回的是一个Promise */ // 点击按钮的时候,动态加载文件,需要配置插件 plugin-syntax-dynamic-import let btn = document.createElement('button'); btn.innerHTML = 'click me' btn.onclick = async function() { let reslut = await import('./x'); console.log('...', reslut); } document.body.appendChild(btn);<file_sep>/第十天/call-apply-bind.md ## Function.prototype - call: `[function].call([context], params1, params2...)`,function 作为Function的内置的一个实例,可以基于__proto__找到Function.prototype的call方法,并且把找到的call方法执行,在call方法执行的时候,会把function执行,并且把函数的this指向为context,并且把params1, params2...分别传递给函数 - apply:`[function].apply([context], [params1, params2...])` 和call的作用一样,只不过传递给函数的参数,需要已数组的形式传递给apply - bind:`[function].bind([context], params1, params2...)` 语法和call是一样的,但是作用和call/apply都不大一样,call/apply 是把函数立即执行,并且改变函数中的this指向,而bind是一个预处理的思想,基于bind只是预先把函数中的this指向context,把parmas参数值存储起来,但是函数并没用立即执行 ```js const body = document.body; let obj = { name: 'shenjp' }; function func(x, y) { console.log(this, x, y); } func(10, 20); // window // obj.func(); // 报错 func.call(obj, 10, 20); // obj, 10, 20 func.apply(obj, [10, 20]); // obj, 10, 20 func.call(); // 第一个参数不传,在非严格模式下,让this指向window,严格模式下,传什么就是什么,不传就是undefined func.call(null, 10, 20); // 传null 非严格模式下是window,严格模式下是 null function(11) // 非严格模式下是 Number(11); 会转为对象类型的值,严格模式下是 11 body.onclick = func; // 把func函数本身绑定给body的onclick事件行为,此时func并没用执行,只有触发body的click 事件,方法才会执行 body.onclick = func(10, 20); // 先把func执行,把方法执行的结果作为返回值绑定给body的click事件 // 把func函数绑定给body的click事件,要求当触发body的click后,执行func 但此时需要让func中的this改变为obj,并且给func传递10, 20 body.onclick = func.bind(obj, 10, 20); // 在没有bind的情况下, 因为bind不兼容IE6~8 body.onclick = function() { func.call(obj, 10, 20); } ``` ## bind的原理 ```js const body = document.body; let obj = { name: 'shenjp' }; function func(x, y) { console.log(this, x, y); } Function.prototype.bind = function(context = window, ...params) { // this => func let _this = this; return function anonymouse(...inner) { // 返回一个匿名函数给事件绑定 // this => body // _this.call(context, ...params, ...inner); _this.apply(context, [...params, ...inner]) } } body.onclick = func.bind(obj, 10, 20); // bind的内部机制就是利用闭包(柯理化函数思想)预先把需要执行的函数以及要改变的this,再以及后需要给函数传递的参数信息,都保存到不销毁的上下文中,后需要使用的时候直接拿来用,这就是经典的预先存储思想 ```<file_sep>/第九天/面试题讲解.md ```js // 创建一个对象,把它的 __proto__ 给去掉了,就破坏了浏览器内置原型链的查找规则 var obj = Object.create(null); // 此处只是给 obj 设置了一个私属性叫 __proto__ ,在调用的时候,不会在这个私有属性上查找 obj.__proto__ = Array.prototype; // 私有属性中没有slice,原型也被破坏了 console.log(obj.slice); // undefined var obj = Object.create({}); // 这样不会破坏原型链机制 obj.__proto__ = Array.prototype; console.log(obj.slice); // fn ``` ```js // Array.prototype.push 向数组末尾添加数组 /* Array.prototype.push = function push(val) { // 1. 向数组(this)末尾添加新类容, 数组索引是连续的,所以新增的索引,肯定在原始最大长度上加1 this[this.length] = val; // 1. 原始数组(this)长度在之前的基础上自动加1 // this.length++; // 浏览器自动就会加1 // 2. 返回新增后的数组的长度 } */ let obj = { 2: 3, 3: 4, length: 2, // 此处如果不写,执行push的时候,就会从索引0开始计算,把length默认从0开始加1 push: Array.prototype.push } obj.push(1); /* push 中的this 是 obj 1. obj[this.obj.length] = 1; 2. obj.length++ 3. return obj.length obj[2] = 1; obj.length++ = 3 obj = { 2: 1, 3: 4, length: 3, push: Array.prototype.push } */ obj.push(2); console.log(obj); ``` ```js /* = 赋值,变量和值进行关联 == 比较,如果左右两边的类型不一致,则默认转为一致的数据类型 对象 == 字符串, 把对象转为字符串 剩下的情况下(出了null/undefined)一般都是转为数字 === 绝对相等,类型和值都要相等 */ // 基本数据类型转为数字 =》 默认都是隐式调用 Number() 处理的 // 对象转为数字 => 需要先转为字符串(先调用 valueOf 方法,获取其原始值,如果原始值不是基本类型的值,则继续调用 toString),在把字符串转为数字 let obj = {}; let str = new String('shenjp'); let arr = [10, 20]; // 数组的原型上没有valueOf,只有toString; 所以数组会调用toString /* 方法1: var a = { i: 1, valueOf() { // 对象转为数字会先调用 valueOf/toString,只要这里返回基本类型的值,这样就不会再去原型上找了 return this.i++; } }; */ /* 方法2: var a = [1, 2, 3]; // 让a 的私有属性toString等于Array.prototype原型上的 shift, (每次执行都删除数组中的额一项,返回删除的那一项) */ /* 方法3:数据劫持(只能劫持某个属性),在每一次回去a的值的时候,我们把它劫持掉,返回我们需要的值 */ var i = 1; Object.defineProperty(window, 'a', { get() { // 在每一次获取window.a的时候,就会触发 return i++; }, // set() { // // 在每一次给window.a赋值的时候会触发 // } }) a.toString = a.shift() if (a == 1 && a == 2 && a == 3) { console.log('ok'); } ```<file_sep>/第一天/执行环境.md > Js之所以能在浏览器中运行,是因为浏览器给js提供了执行换行 => 执行栈(Stack) ```js var a = 12; var b = a; b = 13; console.log(a); // 12 var a = {n: 12}; var b = a; n.n = 13; console.log(a.n); // 13 var a = {n: 12}; var b = a; b = {n: 13}; console.log(a.n) // 12 ``` ## 内存 - 堆(Heap) 栈(Stack)内存 + 栈内存 => 用来提供代码执行的环境 + 堆内存 => 用来存放东西(存放的属性方法) - ECStack (Execution Context Steck) 执行环境栈 + EC 执行上下文,代码自己执行所在的环境 + EC(G) 全局执行上下文 + 函数都会在一个单独的私有的上下文中处理 + ES6中的块级上下文 - GO (Global Object) 全局对象,浏览器把内置的一些属性方法放到一个单独的内存中 堆内存中,浏览器中会让window 指向 GO - VO (varibale Object) 变量对象,在当前上下文中,用来存放创建的值和变量的地方(每一个执行上下文中都会有一个自己的变量对象,函数私有的上下文叫中 AO) + VO(G) 全局变量对象 - AO (Activation Object) 获取对象 也是变量对象,只是VO的一个分支 ## var a = 10; 的如何执行的 - 创建一个值 + 基本数据类型的值都是直接存到栈内存中 + 引用数据类型的值,是先开辟一个堆内存,把东西存储进去,最后把地址存放到栈中供变量关联使用 - 创建一个变量 - 将变量和值关联在一起 ```js var obj = { name: 'shenjp', fn: (function(x) { return x + 1; })(obj.name) } console.log(obj.fn); // VM97:6 Uncaught TypeError: Cannot read property 'name' of undefined /* 1. 创建一个值 开辟一个堆内存 存储键值对 name: 'shenjp' fn: 自执行函数执行,需要把 obj.name 值当做实参传递进来,此时的obj还不存在 2. 创建一个变量 3. 将值和变量关联起来 */ ```<file_sep>/第四天/垃圾回收.md ## 垃圾回收 - Chrome 下是通过应用查找(或称标记清除)进行垃圾回收 - IE 下是通过引用计数进行垃圾回收 ## 常见的内存泄漏 1. 全局变量 在非严格模式下当引用未声明的变量时,会在全局对象中创建一个新变量。在浏览器中,全局对象将是window,这意味着 ```js function foo(arg){ bar ="some text"; // bar将泄漏到全局. } ``` 2. 被遗忘的定时器和回调函数 ```js var someResource = getData(); setInterval(function() { var node = document.getElementById('Node'); if(node) { node.innerHTML = JSON.stringify(someResource)); // 定时器也没有清除 } // node、someResource 存储了大量数据 无法回收 }, 1000); ``` 原因:与节点或数据关联的计时器不再需要,node 对象可以删除,整个回调函数也不需要了。可是,计时器回调函数仍然没被回收(计时器停止才会被回收)。同时,someResource 如果存储了大量的数据,也是无法被回收的。 解决方法: 在定时器完成工作的时候,手动清除定时器 3. DOM引用 ```js var refA = document.getElementById('refA'); document.body.removeChild(refA); // dom删除了 console.log(refA, "refA"); // 但是还存在引用 // 能console出整个div 没有被回收 ``` - 原因: 保留了DOM节点的引用,导致GC没有回收 - 解决办法:refA = null; - 注意: 此外还要考虑 DOM 树内部或子节点的引用问题。假如你的 JavaScript 代码中保存了表格某一个 `<td>` 的引用。将来决定删除整个表格的时候,直觉认为 GC 会回收除了已保存的 `<td>` 以外的其它节点。实际情况并非如此:此 `<td>` 是表格的子节点,子元素与父元素是引用关系。由于代码保留了 `<td>` 的引用,导致整个表格仍待在内存中。保存 DOM 元素引用的时候,要小心谨慎。 4. 闭包 ```js var theThing = null; var replaceThing = function () { var originalThing = theThing; var unused = function () { if (originalThing) { console.log("hi"); } }; theThing = { longStr: new Array(1000000).join('*'), someMethod: function () { console.log(someMessage); } }; }; setInterval(replaceThing, 1000); ``` 这是一段糟糕的代码,每次调用 replaceThing ,theThing 得到一个包含一个大数组和一个新闭包(someMethod)的新对象。同时,变量 unused 是一个引用 originalThing 的闭包(先前的 replaceThing 又调用了theThing)。思绪混乱了吗?最重要的事情是,闭包的作用域一旦创建,它们有同样的父级作用域,作用域是共享的。someMethod 可以通过 theThing 使用,someMethod 与 unused 分享闭包作用域,尽管 unused 从未使用,它引用的 originalThing 迫使它保留在内存中(防止被回收)。当这段代码反复运行,就会看到内存占用不断上升,垃圾回收器(GC)并无法降低内存占用。本质上,闭包的链表已经创建,每一个闭包作用域携带一个指向大数组的间接的引用,造成严重的内存泄漏。 <file_sep>/第九天/重写New方法.md ## 编写 _new 方法实现内置的 new xxx 具备的功能 ```js function Dog(name) { this.name = name; } Dog.prototype.bark = function() { console.log('wawawawa'); } Dog.prototype.sayName = function() { console.log('my name is ' + this.name); } /** * */ function _new(Func, ...args) { /* 1. 创建一个实例对象,是一个对象,对象.__proto__ === 类.prototype 2. 当做普通函数执行,this执行实例对象 3. 看一下函数是否存在返回值,不存在或者返回的是基本数据类型,则返回当前实例,如果返回的是引用类型,则返回当前引用对象 */ // 1. 创建一个实例对象,是一个对象,对象.__proto__ === 类.prototype // let obj = {}; // obj.__proto__ = Func.prototype; // __proto__ 在IE中不能使用 /* Object.create(xxx) 创建一个空对象,并且会把传入 xx 作为当前对象的原型链指向 */ let obj = Object.create(Func.prototype); // 创建 Func的空实例对象 // 2. 当做普通函数执行,this指向实例对象 let result = Func.call(obj, ...args); // 3. 看一下函数是否存在返回值,不存在或者返回的是基本数据类型,则返回当前实例,如果返回的是引用类型,则返回当前引用对象 if (result !== null && /^(object|function)$/.test(typeof result)) { return result; } return obj; // 或者 return result instanceof Object ? result : obj; } let sanmao = _new(Dog, '三毛'); sanmao.bark(); // wawawawa sanmao.sayName(); // my name is 三毛 console.log(sanmao instanceof Dog); // true ``` ```js // Object.create 在低版本的浏览器中不兼容 // 重写一个Object.create 方法 // 创建某个类的空实例 Object.create = function create(prototype) { function Func() {}; Func.prototype = prototype; // 原型的重定向 return new Func(); } ```<file_sep>/README.md ## 系统性的学习js基础知识 ### 目录 - [总结题](https://github.com/Shenjieping/blog/blob/master/question.md) - [第一天](https://github.com/Shenjieping/blog/tree/master/第一天) - [第二天](https://github.com/Shenjieping/blog/tree/master/第二天) - [第三天](https://github.com/Shenjieping/blog/tree/master/第三天) - [第四天](https://github.com/Shenjieping/blog/tree/master/第四天) - [第五天](https://github.com/Shenjieping/blog/tree/master/第五天) - [第六天](https://github.com/Shenjieping/blog/tree/master/第六天) - [第七天](https://github.com/Shenjieping/blog/tree/master/第七天) - [第八天](https://github.com/Shenjieping/blog/tree/master/第八天) - [第九天](https://github.com/Shenjieping/blog/tree/master/第九天) - [第十天](https://github.com/Shenjieping/blog/tree/master/第八天)<file_sep>/进阶学习/第六天-数据结构/template.js // 模板引擎 ejs jade underscore let name = 'shenjp'; let age = '18'; let str = "${name}今年${age}岁"; // 实现模板字符串 let res = str.replace(/\$\{([\s\S]+?)\}/g, (...args) => { return eval(args[1]); }); // console.log(res); // 使用ejs模板 /* 原理: 1. with语法 2. new Function() */ let obj = { name: 'shenjp' } with(obj) { // 声明当前作用域下的this console.log(name); } let fn = new Function(`let str = 123; return str;`); // 可以解析字符串并执行 console.log(fn()); <file_sep>/进阶学习/第六天-数据结构/ejs.js // ejs 的使用 // 原理:with 语法, new Function /* let obj = { name: 'shenjp' }; with(obj) { // 声明一个当前作用域下的this console.log(name); } let fn = new Function(`let str = 123; return str;`); // 将字符串转为函数并可以执行 console.log(fn()); */ let fs = require('fs'); let path = require('path'); let ejs = require('ejs'); let resolve = (dir) => { return path.resolve(__dirname, dir); } let str = fs.readFileSync(resolve('./ejs.html'), 'utf8'); // 实现ejs的替换功能 function render(str, renderObj) { /* return str.replace(/<%=([\s\S]+?)%>/g, (...args) => { // 简单替换 return renderObj[args[1].trim()]; }) */ /* 处理循环语法的思路: 将html和js语法用字符串拼接起来 */ let head = 'let str = ""; with(name){\n\rstr = `'; str = str.replace(/<%=([\s\S]+?)%>/g, (...args) => { // 简单替换 return '${' + args[1] + '}'; }) let content = str.replace(/<%([\s\S]+?)%>/g, (...args) => { return '`\r\n' + args[1] + '\r\nstr += `'; }); let tail = '`\n\r}\n\rreturn str;' let res = head + content + tail; return new Function('name', res)(renderObj); } let renderStr = render(str, {name: [1, 2, 3, 4]}); console.log(renderStr); // 将模板中的变量替换 <file_sep>/进阶学习/第一天/promiseResolve.js // Promise.resolve const Promise = require('./promise'); let p = new Promise((resolve, reject) => { resolve(new Promise((resolve, reject) => { setTimeout(() => { resolve(111); }, 1000); })); }); p.then(data => { console.log(data); }) Promise.resolve = function(value) { return new Promise(resolve => { resolve(value); }); } Promise.reject = function(value) { return new Promise((resolve, reject) => { reject(value); }); } // 一上来就创建一个成功的Promise Promise.resolve(new Promise((resolve, reject) => { setTimeout(() => { resolve('1112'); }, 1000); })).then(data => { console.log(data); }); // 作业 Promise.finally<file_sep>/第二天/作业讲解.md ```js let str = 100 + true + 21.2 + null + undefined + 'Tencent' + [] + null + 9 + false // NaNTencentnull9false // 加号,在两边出现字符串(或者对象)的情况下,+ 一定是字符串拼接 // 对象 本身是要转换为数字进行运算,只不过在转为数字的过程中要先转为字符串,而一旦转为字符串后,就会变成字符串拼接了。 // 对象转为字符串,先调用 valueOf 获取原始值(一般为基本类型的值),如果不是则继续调用 toString() // 数组的 toSting() => '' [1, 2].toString() = '1,2' // == 在进行比较时,如果两边的类型不一致,需要先转为一致的数据类型,然后进行比较 // === 绝对相等,两边的类型一致,值也一致相等,才会相等,不会进行类型转换 /* 1. 对象 == 字符串,对象转为字符串,[10] == '10' true null == undefined (三个等号下是不相等的),但是和其他任何类型的值2. 都不相等 0 == null => false 3. NaN和谁(包括自己)都不相等 4. 剩下的情况下都是转换为数字再做比较 */ [] == false; ![] == false; /* [] == false 都是转为数字进行比较 [] 是先通过toString转为字符串'', 再通过 Number 转为 0 flase 转为 0 ![] == false 运算符的优先级,会先计算 ![] ![] 是把 [] 转为布尔值,再进行取反(把其他类型转为布尔值的规律:只有 0/NaN/null/undefined/'' 这个五个值为false,其余的都是 true) [] => 转为布尔值为 true ,再取反为 false 两边类型一致,就直接进行比较 */ {} + 0 ? alert('ok') : alert('no'); 0 + {} ? alert('ok') : alert('no'); // {} 很特殊,可以是对象、代码块(块级作用域 /* {} + 0; 此处把 {} 当做是一个代码块,后面 + 0;最后就是0 +value ,这个是做是数学运算 {} 在运算符前面 1. 在没有使用 ({}) 处理的情况下,不认为是数学运算 2. {} 在运算符后面,认为是数学运算 */ ``` ```js var a = {}, b = '0', c = 0; a[b] = 'shen'; a[c] = 'jp'; console.log(a[b]); //jp var a = {}, b = Symbol('1'), c = Symbol('1'); a[b] = 'shen'; a[c] = 'jp'; console.log(a[b]); // shen var a = {}, b = {n: '1'}, c = {m: '2'}; a[b] = 'shen'; a[c] = 'jp'; console.log(a[b]); // jp /* 考察的是 对象中的属性名是什么格式的 很多人认为属性名只能是 字符串,但是,普通对象的属性名,可以是基本的数据类型值,如果不是基本类型的值,要调用 toString 转为字符串 */ ``` ```js var a = {n: 1}; var b = a; a.x = a = {n: 2}; console.log(a.x); console.log(b); // JS中存在多种作用域(全局,函数私有的,块级私有的),代码之前之前,首先会形成自己的执行上下文,然后把上线文进栈,进栈后,在当前上下文中在依次执行代码 /* 所有的赋值操作: 1. 创建值 2. 创建变量 3. 变量和指针关联 */ /* 1. 先创建一个堆内存,里面存放 {n:1},同时提供一个地址 "0XFF00" 给栈内存中,将该内存地址赋值给 变量a 2. 将a 赋值给b, 此时a和b 指向同一片内存 "0XFF00"; 3. 成员运算符(.) 的优先级比赋值运算符更高,所以,在 地址"0XFF00" 中添加了一个变量 x,此时值为 undefined 3. 执行 a = {n: 2}; 再开辟一个新的内存空间,地址"0XFF11", 此时的 a 的指向发生变化,指向 地址 0XFF11 4. 将内存"0XFF00" 中的x 指向 "0XFF11"地址 最后就是 a = {n:2} */ ``` ```js var x = [12, 23]; function fn(y) { // [12, 23] 此时y和x指向同一片内存地址 y[0] = 100; // [100, 23] y = [100]; // [100] // 此处将y 新开辟了一片地址,y和x失去关联 y[1] = 200; // [100, 200] console.log(y); } fn(x); console.log(x); // [100, 23] /* 函数堆 把函数体的代码当做字符存储到堆中,"代码字符串" => 创建函数,如果不执行,就是一堆字符串,没有意义 函数也是对象,也有自己的键值对,比如 name: fn, length: 1, prototype, __proto__ 创建函数的时候就定义函数的作用域 => 当前创建函数所在的上下文 */ /* 函数执行: 形成一个全新的私有的上下文,供代码执行(进栈执行) */ /* 执行代码之前 初始化作用域链(scopeChain) 初始化 this 指向 初始化实参集合:arguments 给形参赋值 变量提升 代码执行 */ ``` ```js let arr = [1, 2, 3, 4]; arr = arr.map(parseInt); console.log(arr); // [1, NaN, NaN, NaN] /* parseInt(1, 0) // 1 parseInt(2, 1) // NaN parseInt(3, 2) // NaN parseInt(4, 3) // NaN */ ``` ```js console.log(a); // undefined var a = 12; a = 13; console.log(a); // 13 ```<file_sep>/question.md 1. JS中的数据类型 2. 如何检测数据类型 3. var let const 之间的区别 4. 箭头函数和普通函数的区别 5. == 和 === 的区别 6. 写出下面的答案,为什么 ```js [] == false; ![] == false; ``` 7. 写出下面的运行结果 ```js var a = {n: 1}; var b = a; a.x = a = {n: 2}; console.log(a.x); console.log(b); ``` 6. 写出下面的执行结果 ```js let arr = ['1.6px', 2, '10px', 21, 11.22]; arr = arr.map(parseInt); ``` 7. 数组常用方法 8. 如何判断一个字符串是否是属于某个对象的属性,hasOwnProperty is 两个的区别 9. 谈谈你对闭包的理解,以及在项目中的应用 10. ES5的继承有哪些,和ES6的calss有什么区别 11. 编写queryUrlParams 方法, 至少两种方法 ```js let url = 'http://www.baidu.com?lx=10&name=shenjp#app'; console.log(url.queryUrlParams('lx')) // 10 console.log(url.queryUrlParams('name')) // shenjp console.log(url.queryUrlParams('_hash')) // app ``` 12. 编写一个函数实现下面的方法 ```js let res = fn(1, 2)(3); // 6 ``` 11. vue 的响应式原理,vue-router 的原理,两种模式的区别 12. vue3了解吗。谈谈你对vue3的看法 13. 写一个 myNew 方法,实现 new 的功能 ```js function Func(name) { this.name = name; } Dog.prototype.getName() { console.log(`my name is ${this.name}`); } function myNew() { // 实现你的代码 } var fun = myNew(Dog, 'shenjp'); fun.getName(); // my name is shenjp ``` 14. 输出下面的运行结果 ```js let obj = { 2: 3, 3: 4, length: 2, // 这里有没有是一个考点 push: Array.prototype.push } obj.push(1); obj.push(2); console.log(obj); ``` 15. 请用两种方式实现下面的代码 ```js var a = ?; if (a == 1 && a == 2 && a == 3) { console.log('ok'); } ``` 16. 写出下面的执行结果 ```js function Fn(n, m) { n = n || 0; m = m || 0; this.x = n; this.y = m; this.getX = function() { console.log(this.x); } } Fn.prototype.sum = function() { console.log(this.x + this.y); } Fn.prototype = { getX: function() { this.x += 1; console.log(this.x); }, getY: function() { this.y += 1; console.log(this.y); } } let f1 = new Fn(10, 20); let f2 = new Fn; console.log(f1.getX === f2.getX); console.log(f1.getY === f2.getY); console.log(f1.__proto__.getY === Fn.prototype.getY); console.log(Fn.prototype.getX === f2.getX); console.log(f1.constructor); f1.getX(); Fn.prototype.getX(); f2.getY(); Fn.prototype.getY(); f1.sum(); ``` 17. 写出下面的结果 ```js function fn1() { console.log(1); } function fn2() { console.log(2); } fn1.call(fn2); fn1.call.call(fn2); Function.prototype.call(fn1); Function.prototype.call.call(fn1); ``` 18. 写出下面的执行结果 ```js function Foo() { getName = function() { console.log(1); } return this; } Foo.getName = function() { console.log(2); } Foo.prototype.getName = function() { console.log(3); } var getName = function() { console.log(4); } function getName() { console.log(5); } Foo.getName(); getName(); Foo().getName(); getName(); new Foo.getName(); new Foo().getName(); new new Foo().getName(); ``` 19. 当用户在浏览器地址栏输入一个网址,到看到整个页面,中间都经历了哪些事情<file_sep>/第五天/作业讲解.md ```js let arr = [10.18, 0, 10, 25, 23]; arr = arr.map(parseInt); console.log(arr); // [10, NaN, 2, 2, 11] /* parseInt 首先把第一项转为字符串,让后看做某进制(2-36),转为10 进制 parseInt(10.18, 0); // 10 parseInt(0, 1); // NaN parseInt(10, 2); // 2 parseInt(25, 3); // 2 parseInt(23, 4); // 11 */ ``` ```js var a = 10, b = 11, c = 12; function test(a) { a = 1; // 私有的 a = 1; var b = 2; // 局部变量 c = 3; } test(10); console.log(a, b, c); // 10, 11, 3 /* EC(G) 变量提升: var a, b, c => 同时给window中也设置相关的属性 function test(a){ ... } EC(test) 私有上下文 初始化作用域链 <EC(test), EC(G)> 初始化this, arguments 形参赋值:a = 10; [此时a是私有变量] 变量提升 var b [b是私有变量] */ /* 只有在出函数以外的{}中的函数,在不同的浏览器中表现不一致 低版本中是声明加定义,高版本中是只声明(高版本还会把{} 当做块级作用域) */ ``` ```js var a = 4; function b(x, y, a) { /* EC(b) 私有上下文 初始化作用域链<EC(b), EC(G)> 初始化this 初始化arguments,函数内置实参集合(类数组){0: 1, 1: 2, 2: 3, length: 3}; 形参赋值: x = 1, y = 2, a = 3 => 在JS非严格模式下,函数中初始化arguments 和 形参赋完值完成后,浏览器会按照顺序把形参和arguments中的每一项都建立映射机制(一改都改) x -> arguments[0] y -> arguments[1] a -> arguments[2] */ console.log(a); // 3 arguments[2] = 10; console.log(a); // 10 x = 100; console.log(arguments[2]); // 100 } a = b(1, 2, 3); // 把函数执行,把执行后的返回值赋值给a,没有return 默认是undefined console.log(a); // undefined // 函数没有返回值 /* EC(G) 变量提升 var a function b(x, y, a){ ... } [[scope]]:EC(G) */ "use strict"; // => 开启严格模式 var a = 4; function b(x, y, a) { /* 在严格模式下 x/y/a 和 arguments 没有映射机制,是独立的 */ console.log(a); // 3 arguments[2] = 10; // a的值不会变 console.log(a); // 3 a = 100; console.log(arguments[2]); // 10 } a = b(1, 2, 3); console.log(a); // undefined /* --------------------------------- */ function func(x, y, z) { /* 初始化arguments(实参集合,和形参没有关系): {0: 10, 1: 20, length: 2} 形参赋值:x = 10, y = 20, z = undefined ==> 映射关系 x -> arguments[0] y -> arguments[1] z -> arguments中没有索引为2的值,不能建立映射 */ x = 100; console.log(arguments[0]); // 100 arguments[1] = 200; console.log(y); // 200 z = 300; console.log(arguments[2]); // undefined } func(10, 20); ``` ```js { function foo() {} foo = 1; /* 高版本浏览器中 {} 里面的function只是提前声明,不赋值 如果 {} 中有函数/let/const 会形成一个块级作用域 虽然foo是私有的,但是为了兼容ES3,在全局中之前这个foo声明过,浏览器会把运行之前对 foo 的操作映射到全局上一份 下面的代码就是操作私有的变量了 */ } console.log(foo); // fn { function foo() {} foo = 1; function foo() {} // 代码执行到此处,会将之前的代码映射到全局一份,所以全局的foo 变成了1 // 在严格模式下 会报 foo 重复定义 // Uncaught SyntaxError: Identifier 'foo' has already been declared } console.log(foo); // 1 { function foo() {} foo = 1; function foo() {} // 只将这里之前的代码映射到全局一份了 foo = 2; } console.log(foo); // 1 ``` ```js var a = 9; function fn() { a = 0; return function (b) { return b + a++; } } var f = fn(); // a = 0 console.log(f(5)); // b = 5, res = 5, a = 1 console.log(fn()(5)); // b = 5, res = 5 console.log(f(5)); // b = 5, res = 6, a = 2 console.log(a); // a = 2 ``` ```js var test = (function (i) { return function () { alert(i *= 2); } })(2); test(5) /* test = function () { alert(i *= 2) // '4' } */ ``` ![作业讲解](./作业6.png) ```js var x = 5, y = 6; function func() { x += y; func = function(y) { console.log(y + (--x)); } console.log(x, y); } func(4); // 11, 6 // x = 11, y = 6 // func = function(y) {} func(3); // 13 // 私有的 y = 3, x = 11 // 3 + 10 = 13, x = 10 console.log(x, y); // x = 10, y = 6 ``` ![作业讲解](./作业7.png) ```js function fun (n, o) { console.log(o); return { fun: function(m) { return fun(m, n); } } } var c = fun(0).fun(1); // undefined 0 /* fun(0); n = 0; o = undefined; c = { fun: function(m) { return fun(m, n) } } c.fun(1); n = 1, o = 0; c = { fun: function(m) { return fun(m, n) } } */ c.fun(2); // 1 /* m = 2, n = 1; 执行后 n = 2, o = 1; */ c.fun(3); // 1 /* m = 3, n = 1 执行后:n = 3, o = 1 */ ``` ```js (function() { console.log('ok'); arguments.callee(); // 使用此方法可以递归调用当前自执行函数,但是在严格模式下不支持 })() ```<file_sep>/第三天/作业讲解.md ```js let arr = [1, 2, 3, 4]; arr = arr.map(parseInt); console.log(arr); // [1, NaN, NaN, NaN] /* arr.map(function (item, index) { console.log(item, index); }); */ /* parseInt(1, 0) // 1 parseInt(2, 1) // NaN parseInt(3, 2) // NaN parseInt(4, 3) // NaN */ /* parseInt(value, [radix]); radix 在 2 - 36 之间,表示进制,如果radix = 0 或者不传,表示10进制,如果value是0x开头的,默认值是 16 进制。其他情况下返回 NaN 首先把 value 转为字符串,然后把这个value 看做是 radix 进制,转换为10进制的数字 在 value 中,从左往右找,只要有一个不符合条件的,就结束查找 例如 parseInt('23456', 5); 只会吧234当做5进制的数,转为10进制 parseFloat(value) 这个没有进制,只是查找符合float的数,也是找到第一个不符合规则的数就停止查找 */ /* */ ``` ## 数组中常用的迭代方法 - forEach 遍历数组中的每一项 - map 和forEach 类似,只不过map支持返回值。 - find 找一次出现满足结果的项 - filter 返回所有满足所有结果的项,是一个数组 - every 所有都都满足条件的组数,返回true,否则返回false - some 验证只要有一个满足条件的值,返回true,否则返回false - reduce 迭代 ## parseInt 和 parseFloat 的区别 - 默认只传一个值的时候,parseFlot 多支持一个小数点 - parseInt 支持进制,parseFloat 不支持<file_sep>/第七天/闭包的高级应用-惰性函数.md ## 惰性函数 - DOM事件绑定 - DOM 0级事件绑定, xxx.oncick = function() {} - DOM 2级事件绑定, xxx.addEventListener('click', function() {}), 次方法不兼容IE6/7/8,在低版本浏览器中是基于,xxx.attachEvent('onclick', function(){})来实现的 - 兼容所有浏览器 ```js function observerEvent(element, eventType, func) { if (element.addEventListener) { element.addEventListener(type, func); } else if (element.attachEvent) { element.attachEvent('on' + eventType, func); } else { element['on' + eventType] = func; } } /* 这种写法虽然可以实现兼容,但是在相同页面中,每一次执行函数,进来后都要重复的做很多次兼容判断,对性能不好 但是理论上,第一次执行后,我们就知道兼容性了,后期再执行,没必要每一次都判断兼容了。也就是把兼容处理只做一次,就是 懒 函数 */ function observerEvent(element, eventType, func) { // 第一次执行,根据兼容判断,重构了该函数,重构后的小函数就不再需要做兼容处理了 if (element.addEventListener) { observerEvent = function(element, eventType, func) { element.addEventListener(type, func); } } else if (element.attachEvent) { observerEvent = function(element, eventType, func) { element.attachEvent('on' + eventType, func); } } else { observerEvent = function(element, eventType, func) { element['on' + eventType] = func; } } // 第一次也需要执行重构后的方法,来实现时间判断 observerEvent(element, eventType, func); } observerEvent(xxx, 'click', function() {}) ``` ```js // A模块 let weatherModule = (function() { // 此时的 weatherModule 叫 命名空间 let index = 0; /* A模块中有一个方法,在B模块中想要使用 */ function getElement () {} // 想让闭包之外的东西调用方法,可以基于 window.xxx 将其暴露到window上(但是如果全局暴露的东西过多,也会存在冲突的问题) // window.getElement = getElement // 建议使用return return { getElement }; })(); // B模块 let infoModule = (function() { let index = 0; // 在全局下只有一个变量名,或叫命名空间 // 早期的模块化开发思想 weatherModule.getElement(); return { init() { // 在单例模式的基础上,再增加一个命令模式,init 作为当前模块的业务入口 } }; })(); infoModule.init(); // 只需要执行init方法,在init中根据业务需求,把编写的方法依次执行 /* 两个模块下的变量都是私有变量,不会产生冲突 这种也叫单例设计模式,这样设计,就是把描述相同事物(相同版块)中的属性和方法,归纳到相同的命名空间下,实现分组管理 即可以避免全局变量污染,也可以实现模块之间的通信 */ ```<file_sep>/进阶学习/第二天/src/z.js // 这个文件需要整合 x, y 文件,统一导出 /* import {x} from './x'; import {y} from './y'; export { x, y } */ // 简化形式,导入立刻导出 export * from './x'; // 导入导出 x 下的所有变量 export { y } from './y'; // 只导入导出 y 下的 y变量(导出部分类容) // console.log(y); // 这里无法打印。报错<file_sep>/第六天/作业讲解.md ```js /* EC(G) 变量提升: var a, b, c function fn(a) {...} */ console.log(a, b, c); // undefined, undefined, undefined var a = 12, b = 13, c = 14; function fn(a) { console.log(a, b, c); // 10, 13, 14 a = 100; c = 200; console.log(a, b, c); // 100, 13, 200 } b = fn(10); // undefined console.log(a, b, c); // 12, undefined 200 ``` ```js var i = 0; function A() { var i = 10; function x() { console.log(i); } return x; } var y = A(); y(); /* 全局 i = 0; 局部 i = 10; y = function x() { console.log(i); } y(); // 10; */ function B() { var i = 20; y(); // 10 作用域是在创建的时候形成的,和在哪里执行没关系 } B(); ``` ```js var a = 1; var obj = { "name": "tom" }; function fn() { var a2 = a; obj2 = obj; // 相当于 window.obj2 a2 = a; obj2.name = "jack"; } fn(); console.log(a); // 1 console.log(obj); // {name: 'jack'} ``` ```js var a = 1; function fn(a) { /* 变量提升 var a; function a() {...} a = function a() {} */ console.log(a); // fn(); var a = 2; function a() {} // 声明加定义 } fn(a); /* 变量提升 var a, function fn(a){...} */ ``` ```js var a = 1; function fn(a) { /* EC(G) 变量提升 a = function a() {...} */ a(); console.log(a); // f a() {} (2) var a = 2; // 局部的 a = 2 console.log(a); // 2 (3) function a() { /* EC(FN) */ console.log(a); // f a() {} (1) } console.log(a); // 2 (4) } fn(a); ``` ```js console.log(a); // undefined var a =12; function fn() { console.log(a); // undefined var a = 1; } fn(); console.log(a); // 12 console.log(a); // undefined var a = 12; function fn() { console.log(a); // 12 a = 13; } fn(); console.log(a); // 13 console.log(a); // Type Error: a is not defined a = 12; function fn() { console.log(a); a = 13; } fn(); console.log(a); ``` ```js var foo = 'hello'; (function (foo) { // 自执行的函数不会变量提升,创建 + 执行 /* EC(G) 下创建 形参赋值,foo = 'hello' 局部已经有一个 foo 变量了,不会在重复创建 */ console.log(foo); // hello var foo = foo || 'world'; // hello console.log(foo); // hello })(foo); console.log(foo); // hello ``` ```js /* 编写queryUrlParams 方法, 至少两种方法 */ let url = 'http://www.baidu.com?lx=10&name=shenjp#app'; String.prototype.queryUrlParams = function(name) { /* const searchIndex = this.indexOf('?'); let hashIndex = this.indexOf('#'); let searchText = ''; let hashText = ''; hashIndex = !!~hashIndex ? hashIndex : this.length; searchText = this.substring(searchIndex + 1, hashIndex); hashText = this.substring(hashIndex + 1); */ // 使用 a 标签的特性获取对应的属性 let link = document.createElement('a'); link.href = this; let searchText = link.search.substring(1); let hashText = link.hash.substring(1); link = null; const res = {}; if (searchText) { /* const paramsArray = searchText.split('&'); (paramsArray || []).forEach(item => { if (item) { let query = item.split('='); res[query[0]] = decodeURIComponent(query[1]); } }); */ // 正则处理 const paramsArray = searchText.split(/(?:&|=)/g); for (let i = 0; i < paramsArray.length; i += 2) { let key = paramsArray[i]; let value = paramsArray[i + 1]; key ? res[key] = value : null; } } hashText ? res['_SHAH'] = hashText : null; return name ? res[name] : res; } console.log(url.queryUrlParams('lx')) // 10 console.log(url.queryUrlParams('name')) // shenjp /** * queryUrlParams 获取地址栏 ? 参数信息和hash值 * @params * url[String]: 必传,需要解析的url地址 * key[String]: 选传,要获取的属性值,若不传则以对象的形式返回所有的参数 * @return * 获取的结果,可能是对象,也可能是某个具体的值 * @author shenjp * @date 2020-7-15 */ let url = 'http://www.baidu.com?lx=10&name=shenjp#app'; String.prototype.queryUrlParams = function(name) { let obj = {}; this.replace(/([^?&=#]+)=([^?&=#]+)/g, (_, $1, $2) => ($1 ? obj[$1] = $2 : null)); this.replace(/#([^?&=#]+)/g, (_, $1) => ($1 ? obj['_SHAH'] = $1 : null)); return name ? obj[name] : obj; } const lx = url.queryUrlParams('lx'); console.log(lx); ``` ```js function fn(...args1) { return function(...args2) { return [...args1, ...args2].reduce((a, b) => a + b); } } // 或者 const fn = (...args1) => (...args2) => ([...args1, ...args2].reduce((a, b) => a + b)); let res = fn(1, 2)(3); console.log(res); // 6 ``` ```js for (var i = 0; i < 10; i++) { setTimeout(() => { console.log(i); }, 1000) } ``` ```js var b = 10; (function b() { /* 自执行函数本应该是个匿名函数,(函数表达式或者回调函数都是匿名函数),只不过为了编码规范,会给匿名函数 “具名话” 1. 这个名字只能在函数内部被调用,函数外面用不了 2. 这个名字的变量,在函数内部值也是不能修改的 */ b = 20; console.log(b); // f b() {} })(); console.log(b); // 10 /* (function AA() { console.log(AA, arguments.callee); // 函数本身, 这样在递归调用的时候可以使用AA执行,而不用 arguments.callee 反问当前函数,(arguments.callee 在严格模式下不支持) AA = 1000; console.log(AA); // 如果没有重新声明,还是函数本身,无法进行修改 })(); console.log(AA); // AA is not defined */ /* (function AA() { console.log(AA); // 报错 let AA = 100; // 如果是基于 var/let/const/function 等操作处理,会把这个具名化的名字改为正常的私有变量,也就是名字不再代表函数了 console.log(AA); // 100 })() */ /* (function AA() { console.log(AA); // fn AA(){} function AA () {} console.log(AA); // fn AA(){} })() */ ``` ```js var i = 20; function fn() { /* 变量提升: var i; */ i -= 2; // 第一次 i = NaN var i = 10; // 局部 i = 10 return function (n) { console.log((++i) - n); } } var f = fn(); f(1); /* n = 1, i = 10; i = 11; 结果 11 - 1 = 10 */ f(2); /* n = 2; i = 12 结果 12 - 1 = 10; */ fn()(3); // i = 10, n = 3 // 11 - 3 = 8 fn()(4); // 11 - 4 = 7 f(5); // n = 5, i = 12 // 13 - 5 = 8 console.log(i); // 20 ```<file_sep>/进阶学习/第三天-ES6/descurction.js // 解构赋值 ... (剩余运算符,展开运算符) let obj = { name: 'shenjp', age: 10 } let {name, age} = obj; console.log(name, age); let {name: name1} = obj; // 重命名 console.log(name1); let {name2 = 'haha'} = obj; // 赋默认值 console.log(name2); // 数组的解构 let [n, o] = ['shenjp', 18]; console.log(n, o); // 复杂的解构, 两边的解构要一致 let {school: { count }} = {school: {count: 100}}; console.log(count); // 剩余运算符 let [a, ...args] = [1, 2, 3, 4]; console.log(a, args); // 方法传递参数 function sum(...args) { console.log(args); } sum(1, 2, 3, 4, 5); // 合并两个数组 let arr1 = [1, 2, 3]; let arr2 = [4, 5, 6]; console.log([...arr1, ...arr2]); // 作业 mergeoptions function mergeOptions(obj1, obj2) { for (let key in obj2) { if (obj1.hasOwnProperty(key) && typeof obj2[key] === 'object') { mergeOptions(obj1[key], obj2[key]); } else { obj1[key] = obj2[key]; } } return obj1; } let obj1 = { a: 1, b: 2, c: { a: 1, b: { a: 1 } } }; let obj2 = { a: 2, c: { a: 2, b: { c: 2 } }, d: 3 } console.log(mergeOptions(obj1, obj2)); // { a: 2, b: 2, c: { a: 2, b: { a: 1, c: 2 } }, d: 3 } // 对象的展开,数组的展开,是浅拷贝 let arrslice = [1, 2, 3, [4]]; let newArrslice = arrslice.slice(3); newArrslice[0][0] = 100; console.log(arrslice); // [ 1, 2, 3, [ 100 ] ]<file_sep>/第四天/闭包.md ```js let x = 1; function A(y) { let x = 2; function B(z) { console.log(x + y + z); // 7 } return B; } let C = A(2); C(3); ``` - GO 全局对象 window, 在堆内存中,存放的是浏览器内置的一些API - VO(G) 全局变量对象,在全局上下文中创建的变量 - 基于var/function 在全局上下文中声明的变量也会给 GO 赋值一份(映射机制) - ES6中的 let/const 等方式,在全局上下文中创建的全局变量和GO没有关系 ## 函数执行 - 形成私有上下文 - 进栈执行 - 一系列操作(代码执行) - 正常情况下,代码执行完,私有上下文会出栈,出栈好会释放,以此解决栈内存的空间 - 特殊情况下,如果私有上下文中的某个东西(一般是一个堆)被上下文以外的事物占用了,则上下文不会再出栈释放,也就是形成不销毁的上下文 ## 浏览器的垃圾回收机制 - Chrome是基于 引用查找 来今夕垃圾回收的。 + 开辟的堆内存,浏览器默认会在空闲的时候,查找所有内存的引用,把那些不被引用的内存释放 + 开辟的栈内存,一般会在代码执行完就会释放,如果遇到上下文中的东西被外部引用,则不会被释放 + 查找的引用方式如果形参相互引用,也会导致 内存泄漏,但是相对于IE会好很多 - IE 浏览器是基于 计数器 机制来进行内存管理 + 创建的内存被引用一次,则计数 1,再被引用则计数2 ... 移出引用则减去1,当数字为0的时候,浏览器会把内存释放 + 真实项目中某些情况下计数规则会出现问题,造成内存不会被会后,最后导致 内存泄漏 ## 思考:那些情况会导致内存泄漏 JS高级程序设计 第三版 最后章节中有介绍 ```js let a = {name: 'shenjp'}; let b = a; // 此时 {name: 'shenjp'} 的堆内存被 a,和b 同时占用,所以堆内存不会被释放 // 要想释放此堆内存需要: a = null; b = null; // 将 a 和 b 都赋值给空指针,此时的堆内存就没有被任何占用,浏览器会在空闲的时候释放掉此内存 // 在项目中,将不使用的引用变量赋值为 null,一次节约内存 ``` 函数执行后会形成全局的私有上下文,这个上下文可能被释放,也可能不被释放,不论是否被释放,他的作用是: - 保护:划分一个独立的代码执行区域,在这个区域中有自己的私有变量存储空间,而用到的私有变量和其他区域中的变量不会有任何的冲突(防止全局变量污染) - 保存:如果上下文不被销毁,存储的私有变量的值,也不会被销毁,可以被下级上下文中调取使用 > 我们把函数执行,形成私有上下文,来保存和保护的机制,称之为 "闭包" => 他是一种机制而已 > > 市面上认为,只有形成的私有上下文不被释放,才算是闭包(因为,如果一旦释放,之前的东西也就不存在了) > > 还有人认为,只有下一级上下文中用到了此上下文中的东西才算是闭包 ## 作用域链机制 遇到一个变量,先看是不是自己私有的变量,如果不是则按作用域链向上查找,如果也不是,则继续向上查找,直到EC(G) 为止 - 当EC(C)执行完之后,会出栈释放 - EC(C)被释放之后,EC(A)也不会被释放,因为C的全局变量还一直用着A,所以不会被释放 - 如果想要释放EC(A),只需要把C 不再指向当前的地址就行,一般 C = null; 在浏览器空闲的时候会释放 <file_sep>/第十五天/js/ajax的操作.js // 1. 创建Ajax实例对象 let xhr = new XMLHttpRequest(); // 2. 打开url xhr.open('get', './js/data.json', true) // 3. 监听ajax的转态信息 xhr.onreadystatechange = function() { // xhr.readyState ajax状态 0-4 // xhr.status xhr.statusText 服务器返回的网络状态码 2xx/3xx/4xx/5xx if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.response); } } // 4. 发送请求 xhr.send()<file_sep>/进阶学习/第六天-数据结构/queue.js // 队列 class Queue { constructor() { this.arr = []; } enqueue(element) { // 入队列 this.arr.push(element); } unqueue() { // 出队列 return this.arr.shift() } } let queue = new Queue(); // 增删改查的方法 queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); queue.enqueue(4); console.log(queue.arr); console.log(queue.unqueue()); console.log(queue.arr);<file_sep>/进阶学习/第五天-类的继承/ES6/src/main.js // 装饰器 @log @log1('1111') class Animal { static a = 1; // es7语法,给类增加一个属性 @readonly b = 1; // 不是给原型增加 @before say() { console.log('say'); } } let animal = new Animal(); console.log(Animal.a); // 如何查看一个属性是实例上的还是原型上的属性 console.log(animal.hasOwnProperty('b')); // 装饰器 @ // @ 可以装饰类,类中的属性和方法 function log(target) { // 如果写到类的上面,第一个参数就是当前的类 // 可以在类上新增一些属性,可以多次装饰 console.log(target); } function log1(value) { console.log('给修饰符函数的参数:', value); // 需要返回一个函数,供修饰符调用 return function (target) { console.log('修饰函数::', target); } } function readonly(proto, key, descriptor) { // 如果修饰的不是类,参数是类的原型 // descriptor 属性描述器 console.log('属性:', proto, key, descriptor) descriptor.writable = false; } // animal.b = 100; // Uncaught TypeError: Cannot assign to read only property 'b' of object function before (proto, key, descriptor) { console.log('类的方法::', proto, key, descriptor) let old = descriptor.value; // 先存起来 descriptor.value = function() { console.log('before'); old.call(proto); } } animal.say();<file_sep>/第九天/练习题.md ## 作业1 ```js function C1(name) { if (name) { this.name = name; } } function C2(name) { this.name = name; } function C3(name) { this.name = name || 'join'; } C1.prototype.name = 'Tom'; C2.prototype.name = 'Tom'; C3.prototype.name = 'Tom'; alert((new C1().name) + (new C2().name) + (new C3().name)); // Tom + undefined + join ``` ## 作业2 ```js function Fn() { let a = 1; this.a = a; } Fn.prototype.say = function() { this.a = 2; } /* 原来的Fn.prototype: say: function... __proto__: Function.prototype */ Fn.prototype = new Fn(); /* 新的Fn.prototype: a: 1, b: function... __proto__: 原来的Fn.prototype */ let f1 = new Fn(); /* f1: a: 1 __proto__: 新的Fn.prototype */ Fn.prototype.b = function() { this.a = 3; } console.log(f1.a); // 1 console.log(f1.prototype); // undefined,只有函数才有prototype属性 console.log(f1.b); // fn函数 console.log(f1.hasOwnProperty('b')); // false console.log('b' in f1); // true console.log(f1.constructor == Fn); // true ``` ![作业2画图](./作业2.png) ## 作业3 ```js function Fn(n, m) { n = n || 0; m = m || 0; this.x = n; this.y = m; this.getX = function() { console.log(this.x); } } /* Fn.prototype: sum: function... __proto__: Function.prototype */ Fn.prototype.sum = function() { console.log(this.x + this.y); } /* // 被覆盖了,原来的prototype在空闲时被释放 Fn.prototype: getX: function... getY: function... __proto__: Object.prototype */ Fn.prototype = { getX: function() { this.x += 1; console.log(this.x); }, getY: function() { this.y += 1; console.log(this.y); } } let f1 = new Fn(10, 20); /* f1: x: 10, y: 20, getX: function... __proto__: Fn.prototype */ let f2 = new Fn; /* f2: x: 0, y: 0, getX: function... __proto__: Fn.prototype */ console.log(f1.getX === f2.getX); // false console.log(f1.getY === f2.getY); // true console.log(f1.__proto__.getY === Fn.prototype.getY); // true console.log(Fn.prototype.getX === f2.getX); // false console.log(f1.constructor); // Object f1.getX(); // 10 Fn.prototype.getX(); // NaN f2.getY(); // 1 Fn.prototype.getY(); // NaN f1.sum(); // 报错 ``` ![作业3讲解](./作业3.png)<file_sep>/第七天/面向对象.md ## 面向对象编程 (OOP) - 对象,类,实例 - JS本身就是基于面向对象研发出来的编程语言,内置类: - 数据类型,每一个数据类型,都有一个对应的类别 - DOM元素对象 - div -> HTMLDivElement -> HTMLElement -> Element -> Node -> EventTarget -> Object - a -> HTMLAnchorElement -> HTMLElement... - document HTMLDocument -> Document -> Node ... - window -> Window - 元素集合 -> HTMLCollection -> Object - ... ## new 执行的原理 ```js // 自定义类 // 类名的第一个首字母都要大写 function Func() {} // var f = Func() // 把它当做普通函数执行(形成私有上下文,作用域链,this, arguments, 形参赋值,变量提升,代码执行...), f 是函数执行后的返回结果 let f = new Func(); // 构造函数执行,当做类来执行,而不是当做普通函数了,此时 Func 被称为类,返回的结果 f 是类的一个实例,是一个实例对象 console.log(f); // Func {} ``` ## 构造函数执行,和普通函数执行的区别 ```js function Func(x, y) { let num = x + y; this.x = x; // 给当前实例对象设置值 this.y = y; } let f1 = Func(10, 20); let f2 = new Func(10, 20); // {x: 10, y: 20} /* 构造函数执行: 1. 和普通函数执行,基本上是一样的(具备普通函数执行的一面) 2. 和普通函数的区别:首先默认创建一个对象,这个对象就是当前类的实例。让上下文中的 this 指向这个对象 3. 区别:在函数没有返回值的情况下,默认会把创建的实例对象返回,如果函数中自己写了return ,如果返回的基本类型的值,还是会返回创建的实例,如果返回的是引用类型的值,自己写的返回值会覆盖创建的实例 */ function Func(x, y) { let num = x + y; // num 只是一个私有变量,和实例没有关系,只有 this 是实例对象 this.x = x; this.y = y; return num; // 返回基本类型的值,f2依然是当前实例对象 return { name: 'xxx' }; // 如果返回的是一个引用类型的值,一切都以自己返回的为主,此时的 f2 = {name: 'xxx'} ,不再是当前实例了 } let f2 = new Func(10, 20); // {x: 10, y: 20} ``` ## 基于instancesof 可以检测当前对象是否为某个类的实例 ```js function Func(x, y) { let num = x + y; this.x = x; this.y = y; // return { name: 'xxx' }; } let f2 = new Func(10, 20); // {x: 10, y: 20} console.log(f2 instanceof Func); // 如果 Func 没有返回值,Func 的实例就是 f2, 如果有返回,则不再是它的实例 ``` 每一个对象(包含实例对象)都有很多属性和方法,在自己内存中存储的是私有的属性方法,基于 `__proto__` 原型链查找类原型上的都是共有属性方法 检测属性是当前对象私有的还是公有的? 1. 对象.hasOwnProperty(属性), 检测是否为私有属性,只有私有属性才会返回ture,如果有公有的属性,也会返回 false 2. 属性 in 对象,检测是否为他的属性(不论公有还是私有的都是可以) ```js function Func(x, y) { let num = x + y; this.x = x; this.y = y; } let f2 = new Func(10, 20); console.log('x' in f2); // true console.log(f2.hasOwnproperty('x')); // true console.log('toString' in f2); // true console.log(f2.hasOwnproperty('toString')); // false 此方法是原型上的公有方法 ``` ![面向对象基础](./普通函数和构造函数执行的区别.png)<file_sep>/进阶学习/第五天-类的继承/reduce.js // reduce 收敛,把一个数组转换成一个值 let arr = [1, 2, 3, 4, 5]; // 如果不传第二个参数,数组不能为空,否则会报错 let res = arr.reduce((prev, next) => { return prev + next; }); // console.log(res); let res1 = [ { count: 3, price: 5 }, { count: 3, price: 5 }, { count: 3, price: 5 } ].reduce((prev, next) => { return prev + (next.count * next.price) }, 0); // 指定reduce的第一项初始值 console.log(res1); // 作业, 将下面的数字扁平化 let arr2 = [1, [2, [3, [4, 5]]]]; function flat2 (arr) { return arr.reduce((prve, next) => { return prve.concat(Array.isArray(next) ? flat2(next) : next); }, []); } function flat(arr, res = []) { arr.forEach(item => { if (Array.isArray(item)) { flat(item, res); } else { res.push(item); } }); return res; } let res2 = flat2(arr2); // console.log('......', res2); // compose 组合函数,把多个函数组合在一起 function sum(a, b) { return a + b; } function len(str) { return str.length; } function addCurrency(str) { return '$' + str; } // let res = addCurrency(len(sum('shen', 'jp'))); // console.log(res); /* function compose(...fns) { return function(...args) { let lastFnRes = fns.pop(); return fns.reduceRight((prev, next) => { return next(prev); }, lastFnRes(...args)); } } */ // 正序执行 redux 中的redux /* function compose(...fns) { return fns.reduce((prev, next) => { return function (...args) { return prev(next(...args)); } }) } */ // 简化 let compose = (...fns) => fns.reduce((a, b) => (...args) => a(b(...args))); let res = compose(addCurrency, len, sum)('shen', 'jp'); console.log(res); // 实现一个reduce方法 <file_sep>/进阶学习/第一天/高阶函数.md ## 什么叫高阶函数 1. 如果一个函数的参数是一个函数(回调函数也是一个高阶函数) 2. 如果一个函数返回另一个函数,这个函数就叫高阶函数 ## 判断类型 1. typeof 无法判断对象类型 2. constructor 谁构造出来的 3. instanceof 判断谁是谁的实例 __proto__ 4. Object.prototype.toString.call() ```js function isType(type) { return function(content) { return Object.prototype.toString.call(content) === `[object ${type}]` }; } // 高阶函数实现了第一个功能,保存变量(闭包) let isString = isType('String'); console.log(isString('123')); ``` ## 实现函数的柯理化,函数的反柯理化 ## 对某些函数进行扩展,面向切片编程 ```js function say(who) { console.log(who + 'say'); } // 在这个函数执行之前做一些事 // say(); // 装饰器 Function.prototype.before = function(callback) { // 统一扩展了公共方法 let _this = this; return function(...args) { // 或者使用箭头函数 callback(); _this(...args); } } let newSay = say.before(function() { console.log('hehe'); }); newSay('my'); ```<file_sep>/进阶学习/第六天-数据结构/set.js // set 集合 // 特点不重复 class Set { constructor() { this.obj = {}; } hasOwn(element) { return this.obj.hasOwnProperty(element); } set(element) { if (!this.hasOwn(element)) { this.obj[element] = element; } } } let set = new Set(); set.set(1); set.set(1); set.set(3); console.log(set);<file_sep>/进阶学习/第七天-eventloop-commonjs/module/a.js module.exports = 'hello'; console.log('aaa'); /* module.exports 和 exports 有什么区别?为什么不直接用exports 其实module.exports 和 exports 是一个东西 源码中定义的是 let exports = module.exports = {} 返回的结果是 module.exports 所以不能直接更改 exports 的值 可以写 exports.a = xxx; 如果两个都写了,只能识别 module.exports 的值 */ /* 每个函数都会传入 module exports require, __filename, __dirname 全局变量 */<file_sep>/进阶学习/第三天-ES6/map.js // map 也叫hash表 或者散列 // key 不能重复,key 可以是对象 let map = new Map(); map.set('a', '123'); map.set('b', '456'); map.set('c', 123); map.set({a: 1}, 123); map.set({a: 1}, 456); console.log(map); console.log(map.get('b')); // map WeakMap(key 只能是对象) function MyFn() {} let fn = new MyFn(); let map = new Map(); map.set(fn, '123') fn = null; // 这样 MyFn 不能被销毁 <file_sep>/第七天/闭包的高级应用-compose.md ## compose函数 ```js /* 在函数式变成中有一个很重要的概念就是组合函数,实际上就是把处理的函数像管道一样链接起来,然后让数据穿过广告得到最终的结果,例如: */ const add1 = (x) => x + 1; const mul3 = (x) => x * 3; const div2 = (x) => x / 2; div2(mul3(add1(add1(0)))) // 3 /* 这种写法的可读性太差了,我们可以构建一个compose 函数,它接受任意多个函数作为参数(这些函数都只接受一个参数),然后compose 返回的也是一个函数,达到如下效果: */ const operate = compose(div2, mule3, add1, add1); operate(0); // => 相当于 div(mul3(add1(add1(0)))) operate(2);// => 相当于 div(mul3(add1(add1(2)))) /* 简单说,就是 compose 可以把类似于 f(g(h(x))) 这种写法简化成 compose(f, g, h)(x); */ ``` ```js const add1 = (x) => x + 1; const mul3 = (x) => x * 3; const div2 = (x) => x / 2; function compose(...funcs) { return function anonymous(val) { // val是第一个函数执行的实参 let len = funcs.length; if (len === 0) { return val; } if (len === 1) { return funcs[0](val); } return funcs.reverse().reduce((N, item) => { // 或者 reduceRight // return typeof N === 'function' ? item(N(val)) : item(N); return item(N); }, val) } } const operate = compose(div2, mul3, add1, add1); console.log(operate(0)); ``` ```js // redux compose function compose(...funcs) { if (funcs.length === 0) { return arg => arg; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce((a, b) => (...args) => a(b(...args))); } ``` ```js // 递归调用的方式 function compose(...funcs) { function inner(...args) { let total = funcs.pop()(...args); return funcs.length > 0 ? inner(total) : total; } return funcs.length === 0 ? arg => arg : inner; } ```<file_sep>/进阶学习/第三天-ES6/observer.js let obj = { name: 'shenjp', age: { // 如果是对象要递归给他加上get/set a: 100 } }; /* proxy 不需要重写对象的 set/get 如果属性不存在,defineProperty 无法监控到,proxy可以解决 defineProperty数组的方法无法监控,proxy也可以解决 */ function update() { console.log('跟新数据'); } function observer(obj) { if (typeof obj !== 'object' || obj === null) { return; } for(let key in obj) { defineReactive(obj, key, obj[key]); } } function defineReactive(obj, key, value) { observer(value); // 递归增加get/set Object.defineProperty(obj, key, { enumerable: true, configurable: false, get() { return value; }, set(newValue) { if (typeof obj === 'object' && obj !== null) { observer(newValue); // 如果增加的是对象,也要添加get/set } update(); value = newValue; } }); } observer(obj); obj.age = {b: 1}; obj.age.b = 100; console.log(obj.age); // 如果数据类型是数组,是无法监控到变化的 // 他的原理就是将 push, pop 等方法重写<file_sep>/进阶学习/第三天-ES6/let-const.js /* 为什么要有let 和const var 缺陷 1. 会污染全局变量(常见的作用域:window(全局),function,with) 2. 变量提升 3. 可以重复定义 4. var 不能声明常量 5. var 默认不会产生作用域 let优势 1. 不会污染全局变量 2. 不存在变量提升 3. 在同一个作用域下不能被重复定义 */ /* console.log(a); var a = 1; */ /* let a = 10; { // 暂时性死区 console.log(a); // ReferenceError: Cannot access 'a' before initialization let a = 2; } */<file_sep>/进阶学习/第三天-ES6/note.md ## es6 -> es7 语法 ## es6特性 - let & const - 常见的解构 - 箭头函数 - Object.defineProperty Reflect proxy - 数组的用法<file_sep>/第八天/原型上的扩展方法.md ```js function fun() { this.a = 0; this.b = function() { console.log(this.a); } } fun.prototype = { b: function() { this.a = 20; console.log(this.a); }, c: function() { this.a = 30; console.log(this.a); } } /* EC(G): a = 0; b = function() {...} func.prototype b = function() {} c = function() {} */ var my_fun = new fun(); my_fun.b(); // 0 my_fun.c(); // 30 ``` ![讲解](./原型链题1.png) ## 基于内置类的原型扩展方法 1. 内置类的原型上会存在很多常用的方法 `Array.prototype/Object.prototype` 这些方法实例都可以调用,但是内置的方法不能满足需求,需要自己扩展一些方法 2. 向原型上扩展方法调用起来比较方便,方法中的this就是当前处理的实例 - 自己写的方法最好加个前缀,比如 My_xxx,防止自己扩展的方法覆盖内置的方法 - this 的结果一定是对象类型的值,所以在基本数据类型的原型上扩展方法的时候,方法在执行的时候,方法中的this,不再是基本类型, 还是按照原始的类型处理即可(在运算的时候会默认调用对象的valueOf 方法,返回他的原始值,就是之前的基本值) - 如果返回的结果依然是当前类的实例,还可以继续调用当前类原型上的其他方法(如果不是自己类的实例,可以调用其他原型上的方法 =》 链式写法) 3. 对于一个对象来说,它的属性方法(私有/公有)存在枚举的特点,在for in 循环的时候是否可以遍历到,能遍历到的就是可枚举的,不能遍历则不可枚举。内置类型上自己扩展的方法是可枚举的 ```js let n = 10; (function() { // 私有方法,handleNum 只能在内部使用 function handleNum(num) { // 更加严谨的写法 num = Number(num); return isNaN(num) ? 0 : num; } Number.prototype.plus = function plus(num) { // 如果传入的不是 number 类型的值,就调不了此方法 console.log(this); // Number {10} return this + handleNum(num); } Number.prototype.minus = function minus(num) { return this - handleNum(num); } })() let m = n.plus(10).minus(5); console.log(m) // 10 + 10 - 5 = 15; ``` ```js // obj.__proto__ = Object.prototype /* 内置原型上的方法是不可枚举的 */ let obj = { name: 's', age: 10 }; Object.prototype.aa = function() { console.log(this) } // 原型上的自己扩展的属性和方法,是可以被枚举的,所以一般会加一个 hasOwnProperty 来过滤原型上的方法 for (let key in obj) { // 将原型上扩展的公共属性或者方法过滤掉 if (!obj.hasOwnPorperty(key)) { break; } console.log(key); // name age } ``` <file_sep>/第十三天/事件对象和时间传播机制.md ## 事件的传播机制 - Event.prototype: + AT_TARGET: 2 => 目标阶段 + BUBBLING_PHASE: 3 => 冒泡阶段 + CAPTURING_PHASE: 1 => 捕获阶段 - 当前元素的某个事件被触发,一定会经历三个阶段: + 捕获阶段:从最外层容器一直向里层查找,知道找到当前触发的事件源为止,查找的目的,建立起当前元素未来冒泡传播的路线 + 目标阶段:把当前元素的相关事件行为触发,如果绑定了方法则把方法执行 + 冒泡阶段:不仅当前元素的相关事件行为会被触发,而且,在捕获阶段获取的路径中的每一个元素的相关事件行为也会触发(顺序从里向外)(其父级所有的相关事件行为也会被触发),如果也对应绑定了方法,方法也会被触发执行 ![事件传播](./事件传播.png) ```html <!-- 事件传播 --> <div id="outer"> <div id="inner"> <div id="center"></div> </div> </div> <script> document.body.onclick = function(e) { console.log('body:', e) } outer.onclick = function(e) { console.log('outer:', e) } inner.onclick = function(e) { console.log('inner:', e) } center.onclick = function(e) { e.stopPropagation(); // 阻止冒泡 console.log('center:', e) } </script> ```<file_sep>/进阶学习/第三天-ES6/defineProperty.js // Object.defineProperty // 定义属性 Object.freeze()冻结 let obj = {name: '123'}; let val = 'shenjp' Object.freeze(obj); // 用了此方法,这个对象不能被添加 get/set方法 Object.getOwnPropertyDescriptor(obj, 'name'); // 可以用来提示vue的性能 Object.defineProperty(obj, 'name', { configurable: true, // 这个属性是否可以被删除 // value: 123, // 不常用 enumerable: true, // 是否可枚举,也就是是否可以被 for...in 循环 get() { // 取值 return val; }, set(newValue) { newValue = val; } }); <file_sep>/进阶学习/第二天-模块化/src/a.js /* export let a = 1; // 表示把 a 导出 export let b = 2; */ let a = 1; let b = 2; export { // 这不是一个对象,意思就是导出一个列表,导出的是变量 a, b } // 默认导出, export default {a: 3, b: 4} // 他只是导出的值 /* export 和 export default的区别 1. export 导出的是变量,export default 导出的是具体的值 2. export 可以导出多次,export default 只能导出一个值 */
97b4d965df692c01bda4e631e47b4ac4fb35f8d7
[ "JavaScript", "Markdown" ]
82
JavaScript
Shenjieping/blog
c5d6a6a3c391d585e67322049152be72d3c6d859
a52d13310cac53e3cf3d6b4be811c158a36b639e
refs/heads/master
<repo_name>xiwenAndlejian/springboot-template<file_sep>/src/main/java/com/dekuofa/model/entity/SysLogInfo.java package com.dekuofa.model.entity; import com.dekuofa.model.NormalUserInfo; import com.dekuofa.model.UserInfo; import io.github.biezhi.anima.Model; import io.github.biezhi.anima.annotation.Column; import io.github.biezhi.anima.annotation.Table; import lombok.Data; import lombok.EqualsAndHashCode; /** * @author dekuofa <br> * @date 2018-08-29 <br> */ @EqualsAndHashCode(callSuper = false) @Table(name = "t_log") @Data public class SysLogInfo extends Model { private Integer id; private Long createTime; private Integer userId; @Column(name = "user_name") private String username; private String action; private boolean success; private String message; private String params; public boolean getSuccess() { return this.success; } public SysLogInfo(boolean success) { this.success = success; } public SysLogInfo createTime(Long createTime) { this.createTime = createTime; return this; } public SysLogInfo username(String username) { this.username = username; return this; } public SysLogInfo action(String action) { this.action = action; return this; } public SysLogInfo success(boolean success) { this.success = success; return this; } public SysLogInfo message(String message) { this.message = message; return this; } public SysLogInfo params(String params) { this.params = params; return this; } public SysLogInfo userInfo(UserInfo userInfo) { this.username = userInfo.getNickName(); this.userId = userInfo.getUserId(); return this; } public static SysLogInfo ok() { return new SysLogInfo(true); } public static SysLogInfo ok(String message) { return ok().message(message); } public static SysLogInfo ok(String message, String params) { return ok(message).params(params); } public static SysLogInfo fail() { return new SysLogInfo(false); } public static SysLogInfo fail(String message) { return fail().message(message); } public static SysLogInfo fail(String message, String params) { return fail(message).params(params); } } <file_sep>/src/main/java/com/dekuofa/controller/AuthController.java package com.dekuofa.controller; import com.dekuofa.annotation.SysLog; import com.dekuofa.manager.RoleManager; import com.dekuofa.manager.UserManager; import com.dekuofa.model.NormalUserInfo; import com.dekuofa.model.UserInfo; import com.dekuofa.model.entity.SysRole; import com.dekuofa.model.entity.User; import com.dekuofa.model.enums.UserType; import com.dekuofa.model.param.LoginParam; import com.dekuofa.model.response.LoginResponse; import com.dekuofa.model.response.RestResponse; import com.dekuofa.model.response.UserInfoResponse; import com.dekuofa.utils.JwtUtil; import com.dekuofa.utils.ShaUtil; import io.swagger.annotations.ApiParam; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authz.UnauthorizedException; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.util.Collection; import java.util.stream.Collectors; /** * @author dekuofa <br> * @date 2018-08-14 <br> */ @RestController @Slf4j public class AuthController implements BaseController { private UserManager userManager; private RoleManager roleManager; @Autowired public AuthController(UserManager userManager, RoleManager roleManager) { this.userManager = userManager; this.roleManager = roleManager; } @SysLog(action = "登陆") @PostMapping("/login") public RestResponse<?> login(@RequestBody LoginParam param, @ApiIgnore @ModelAttribute("ip") String ip, @ApiIgnore HttpServletResponse response) { if (param == null || param.getUsername() == null) { throw new UnauthorizedException("用户名或密码不能为空"); } log.debug("用户登陆ip:" + ip); User user = userManager.findByUsername(param.getUsername()); // 加密后的密码 String encodePwd = ShaUtil.sha512Encode(param.getPassword()); if (user != null && user.getPassword().equals(encodePwd)) { UserInfo userInfo = new NormalUserInfo(user.getId(), user.getUsername(), user.getNickName(), UserType.ADMIN); // 生成token String token = JwtUtil.sign(userInfo, encodePwd); if (token == null) { return RestResponse.fail("生成token失败"); } // 记录登陆成功,修改最后一次登录时间 userManager.login(user.getId(), ip); // 组装返回数据 LoginResponse responseData = new LoginResponse(userInfo, token, user.getPermissions()); // cookie设置 Cookie cookie = new Cookie("token", token); cookie.setHttpOnly(true); response.addCookie(cookie); return RestResponse.ok(responseData); } return RestResponse.fail("用户名或密码错误"); } @PostMapping("/user/logout") public RestResponse<?> logout(@ApiParam(hidden = true) UserInfo userInfo) { log.info("用户: {} 已下线", userInfo.getNickName()); return RestResponse.ok(); } @RequiresAuthentication @GetMapping("/user/info") public RestResponse<?> getUserInfo(@ApiParam(hidden = true) UserInfo userInfo, Model model) { if (userInfo == null) { return RestResponse.fail("token校验失败"); } Integer userId = userInfo.getUserId(); User user = userManager.findById(userId); Collection<String> roles = roleManager.roles(userId) .stream().map(SysRole::getName) .collect(Collectors.toList()); UserInfoResponse response = new UserInfoResponse().name(userInfo.getNickName()).roles(roles).id(userId) .avatar(user.getAvatar()); return RestResponse.ok(response); } @RequestMapping(value = "/401") public RestResponse<?> unAuth() { return RestResponse.fail("登陆失败"); } } <file_sep>/src/main/java/com/dekuofa/manager/impl/FileManagerImpl.java package com.dekuofa.manager.impl; import com.dekuofa.constant.Constants; import com.dekuofa.exception.TipException; import com.dekuofa.manager.FileManager; import com.dekuofa.model.NormalUserInfo; import com.dekuofa.model.UserInfo; import com.dekuofa.model.entity.FileInfo; import com.dekuofa.model.enums.BaseStatus; import com.dekuofa.model.param.PageParam; import com.dekuofa.service.FileService; import com.dekuofa.utils.DateUtil; import com.dekuofa.utils.FileUtil; import com.dekuofa.utils.UuidUtil; import io.github.biezhi.anima.page.Page; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import static com.dekuofa.utils.DateUtil.newUnixMilliSecond; /** * @author dekuofa <br> * @date 2018-09-03 <br> */ @Component @Slf4j public class FileManagerImpl implements FileManager { @Value("${file.upload.path}") private String fileUploadPath; private FileService fileService; @Autowired public FileManagerImpl(FileService fileService) { this.fileService = fileService; } @Override public FileInfo upload(MultipartFile fileUpload, String fileName, UserInfo userInfo) { // 获取当前日期 String day = DateUtil.newDate(); // 如果获取不到,则使用默认文件类型 String fileType = FileUtil.getFileType(fileUpload).orElse(Constants.DEFAULT_FILE_TYPE); // 根据当前日期创建文件夹 File dir = FileUtil.createDir(fileUploadPath, day) .orElseThrow(() -> new TipException("上传文件失败:创建文件夹失败,请联系管理员!")); // 文件实际存储名称uuid String uuid = UuidUtil.getRandomUUIDString(); // 创建文件对象 File file = new File(dir.getPath() + "/" + uuid); try { // 写入硬盘 FileUtils.writeByteArrayToFile( file, fileUpload.getBytes() ); } catch (IOException e) { e.printStackTrace(); throw new TipException("文件写入失败"); } Double size = FileUtil.getFileSizeOfMB(fileUpload); // 文件路径 String url = "/" + day + "/" + uuid; FileInfo fileInfo = new FileInfo(fileName, uuid, url, size, fileType, BaseStatus.NORMAL); Long now = newUnixMilliSecond(); fileInfo.setModifyInfo(userInfo, now) .setCreateInfo(userInfo, now); fileService.save(fileInfo); // 日志打印 log.debug("文件名:" + fileName); log.debug("文件路径:" + dir.getPath()); log.debug("uuid:" + uuid); log.debug("文件大小:" + size + "MB"); log.debug("文件类型:" + fileType); return fileInfo; } @Override public Page<FileInfo> query(PageParam pageParam, String keyword) { return fileService.query(pageParam, keyword); } } <file_sep>/src/main/java/com/dekuofa/model/response/FileUploadResponse.java package com.dekuofa.model.response; import lombok.Data; import lombok.NoArgsConstructor; /** * @author dekuofa <br> * @date 2018-09-03 <br> */ @Data @NoArgsConstructor public class FileUploadResponse { private Integer fileId; private String url; public FileUploadResponse fileId(Integer fileId) { this.fileId = fileId; return this; } public FileUploadResponse url(String url) { this.url = url; return this; } } <file_sep>/src/main/java/com/dekuofa/utils/ShaUtil.java package com.dekuofa.utils; import org.apache.shiro.crypto.hash.Sha256Hash; import org.apache.shiro.crypto.hash.Sha512Hash; /** * @author :gx <br> * 时间:2018年07月14日 21:12<br> * 标题:SHA64Encoder<br> * 功能:<br> */ public class ShaUtil { /** * SHA64加密字符串 * * @param str 被加密的字符串 * @return SHA64加密的字符串 */ public static String sha256Encode(String str) { return new Sha256Hash(str).toHex(); } /** * SHA64加密字符串 * * @param str 被加密的字符串 * @return SHA64加密的字符串 */ public static String sha512Encode(String str) { return new Sha512Hash(str).toHex(); } } <file_sep>/src/main/java/com/dekuofa/model/relation/UserRole.java package com.dekuofa.model.relation; import io.github.biezhi.anima.Model; import io.github.biezhi.anima.annotation.Table; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; /** * @author dekuofa <br> * @date 2018-08-28 <br> */ @EqualsAndHashCode(callSuper = false) @Data @Table(name = "user_role") @NoArgsConstructor @AllArgsConstructor public class UserRole extends Model { private Integer userId; private Integer roleId; } <file_sep>/src/main/java/com/dekuofa/service/PermissionService.java package com.dekuofa.service; import com.dekuofa.model.entity.Permission; import com.dekuofa.model.entity.SysRole; import com.dekuofa.model.param.PageParam; import com.dekuofa.model.relation.RolePermission; import io.github.biezhi.anima.page.Page; import java.util.Collection; import java.util.List; import java.util.Set; /** * @author dekuofa <br> * @date 2018-08-20 <br> */ public interface PermissionService { Set<Permission> getPermissions(Collection<SysRole> roles); Page<Permission> list(PageParam pageParam); List<Permission> permissions(Integer roleId); void changePermissions(List<RolePermission> permissions, Integer roleId); } <file_sep>/src/main/java/com/dekuofa/utils/BeanKit.java package com.dekuofa.utils; import com.dekuofa.model.common.BeanMethod; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.function.Function; /** * @author dekuofa <br> * @date 2018-08-21 <br> */ public class BeanKit { public static <T, R> void injectProperty(BeanMethod<T, R> bean, Object object, T param) { Class<?> clazz = bean.getClazz(); try { Method method = clazz.getDeclaredMethod(bean.getMethod(), bean.getPropertyType()); method.setAccessible(true); Function<T, R> action = bean.getFunction(); method.invoke(object, action.apply(param)); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); System.out.println("更新修改信息失败"); } } } <file_sep>/src/main/java/com/dekuofa/exception/TipException.java package com.dekuofa.exception; import lombok.Getter; import lombok.Setter; /** * @author ganxiang <br> * 时间:2018年04月24日 09:36<br> * 标题:TipException<br> * 功能:提示exception<br> */ @Getter @Setter public class TipException extends RuntimeException { private Integer code = 1; public TipException() { } public TipException(String message) { super(message); } public TipException(Integer code, String message) { super(message); this.code = code; } public TipException(String message, Throwable cause) { super(message, cause); } public TipException(Throwable cause) { super(cause); } } <file_sep>/src/main/java/com/dekuofa/model/param/SysRoleParam.java package com.dekuofa.model.param; import lombok.Data; /** * @author dekuofa <br> * @date 2018-08-28 <br> */ @Data public class SysRoleParam { private String name; } <file_sep>/src/test/java/com/dekuofa/ExceptionTest.java package com.dekuofa; import com.dekuofa.model.entity.User; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.springframework.util.Assert; /** * @author dekuofa <br> * @date 2018-08-17 <br> */ public class ExceptionTest { @Test public void jsonIgnoreSerialization() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); User user = new User(); user.setPassword("<PASSWORD>"); String serialized = objectMapper.writeValueAsString(user); System.out.println(serialized); } public static void main(String[] args) { try { a(); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getCause()); } } public static void a() throws Exception { b(); } public static void b() throws Exception { throw new Exception("exception"); } } <file_sep>/src/main/java/com/dekuofa/controller/LogController.java package com.dekuofa.controller; import com.dekuofa.manager.LogManager; import com.dekuofa.model.param.PageParam; import com.dekuofa.model.response.RestResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author dekuofa <br> * @date 2018-08-30 <br> */ @RestController public class LogController implements BaseController { private LogManager logManager; @Autowired public LogController(LogManager logManager) { this.logManager = logManager; } @GetMapping("/log") public RestResponse<?> query(PageParam pageParam) { return RestResponse.ok(logManager.query(pageParam)); } } <file_sep>/src/main/java/com/dekuofa/service/impl/FileServiceImpl.java package com.dekuofa.service.impl; import com.dekuofa.exception.TipException; import com.dekuofa.model.entity.FileInfo; import com.dekuofa.model.param.PageParam; import com.dekuofa.service.FileService; import io.github.biezhi.anima.core.AnimaQuery; import io.github.biezhi.anima.page.Page; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.beans.Transient; import static io.github.biezhi.anima.Anima.select; /** * @author dekuofa <br> * @date 2018-09-03 <br> */ @Service public class FileServiceImpl implements FileService { @Transient @Override public Integer save(FileInfo fileInfo) { Integer id = fileInfo.save().asInt(); if (id == null) { throw new TipException("主键获取失败"); } return id; } @Override public Page<FileInfo> query(PageParam pageParam, String keyword) { AnimaQuery<FileInfo> query = select().from(FileInfo.class); if (!StringUtils.isEmpty(keyword)) { query.where(FileInfo::getName).like("%" + keyword + "%"); } return query.page(pageParam.getPage(), pageParam.getLimit()); } @Override public void modify(FileInfo fileInfo) { //todo 修改文件信息(状态,名称) } } <file_sep>/src/main/java/com/dekuofa/model/UserInfo.java package com.dekuofa.model; import com.dekuofa.model.enums.UserType; /** * fixme 自定义handler处理接口, * * @author dekuofa <br> * @date 2018-08-21 <br> */ public interface UserInfo { String getUsername(); String getNickName(); UserType getUserType(); Integer getUserId(); boolean isEmpty(); boolean isCurrentUser(Integer userId); } <file_sep>/src/test/java/com/dekuofa/service/RoleServiceTest.java package com.dekuofa.service; import com.dekuofa.BaseTest; import com.dekuofa.model.NormalUserInfo; import com.dekuofa.model.UserInfo; import com.dekuofa.model.entity.SysRole; import com.dekuofa.model.enums.UserType; import com.dekuofa.model.relation.UserRole; import com.dekuofa.utils.DateUtil; import io.github.biezhi.anima.Anima; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.StringUtils; import org.sql2o.converters.Converter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static com.dekuofa.utils.DateUtil.newUnixMilliSecond; /** * @author dekuofa <br> * @date 2018-08-28 <br> */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest @Slf4j public class RoleServiceTest extends BaseTest { @Autowired private RoleService roleService; @Autowired private Environment env; /** * 创建 anima bean, 类似于dataSource */ // @Before // @Bean // public Anima anima() { // String url = env.getProperty("spring.datasource.url"); // String username = env.getProperty("spring.datasource.username"); // String password = env.getProperty("spring.datasource.password"); // assert !StringUtils.isEmpty(url); // assert !StringUtils.isEmpty(username); // assert !StringUtils.isEmpty(password); // // return Anima.open(url, username, password); // } @Test public void test() { List<UserRole> userRoles = new ArrayList<>(); userRoles.add(new UserRole(1, 1)); userRoles.add(new UserRole(1, 2)); List<Integer> deleteIds = Arrays.asList(1, 2); roleService.changeUserRoles(1, userRoles, deleteIds); } @Test public void test_1() { SysRole role = new SysRole(); UserInfo userInfo = getUserInfo(); Long current = getTime(); role.setName("editor"); role.setDesc("编辑者"); role.setCreateInfo(userInfo, current).setModifyInfo(userInfo, current); roleService.addRole(role); log.info("roleId:" + role.getId()); // (ConnectionImpl) anima.getSql2o().open(); } } <file_sep>/src/main/java/com/dekuofa/controller/FileController.java package com.dekuofa.controller; import com.dekuofa.annotation.SysLog; import com.dekuofa.manager.FileManager; import com.dekuofa.model.NormalUserInfo; import com.dekuofa.model.UserInfo; import com.dekuofa.model.entity.FileInfo; import com.dekuofa.model.param.PageParam; import com.dekuofa.model.response.RestResponse; import io.github.biezhi.anima.page.Page; import io.swagger.annotations.ApiParam; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; /** * 处理文件上传&下载 * * @author dekuofa <br> * @date 2018-09-03 <br> */ @RestController @Slf4j public class FileController implements BaseController{ private FileManager fileManager; @Autowired public FileController(FileManager fileManager) { this.fileManager = fileManager; } @SysLog(action = "文件上传") @PostMapping("/upload") public RestResponse<?> upload( @ApiParam(hidden = true) UserInfo userInfo, @RequestParam("file_name") String fileName, MultipartFile file) { log.debug("当前用户:" + userInfo); if (file == null) { return RestResponse.fail("文件上传失败:上传文件不能为空"); } try { FileInfo fileInfo = fileManager.upload(file, fileName, userInfo); return RestResponse.ok(fileInfo.toUploadResponse()); } catch (Exception e) { String msg = getErrorMessage(e); return RestResponse.fail("文件上传失败:" + msg); } } @GetMapping("/fileInfo") public RestResponse<?> query(String keyword, PageParam pageParam) { try { Page<FileInfo> payload = fileManager.query(pageParam, keyword); return RestResponse.ok(payload); } catch (Exception e) { String msg = getErrorMessage(e); return RestResponse.fail("查询失败:" + msg); } } } <file_sep>/src/main/java/com/dekuofa/model/enums/Gender.java package com.dekuofa.model.enums; import io.github.biezhi.anima.annotation.EnumMapping; import lombok.AllArgsConstructor; import lombok.Getter; /** * @author dekuofa <br> * @date 2018-11-06 <br> */ @Getter @EnumMapping("code") @AllArgsConstructor public enum Gender implements BaseCodeEnum { MALE(1, "男"), FEMALE(2, "女"), NULL(0, "暂未设置") ; private Integer code; private String desc; } <file_sep>/build.gradle buildscript { repositories { //本地maven mavenLocal() jcenter() } dependencies { classpath 'com.bluepapa32:gradle-watch-plugin:0.1.5' } } plugins { id "org.springframework.boot" version "2.0.4.RELEASE" } group = "com.shuda" version = "0.0.1" allprojects { repositories { mavenLocal() jcenter() mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots" } maven { url "https://mvnrepository.com/artifact" } } } apply plugin: 'idea' apply plugin: 'java' //编译版本 sourceCompatibility = 1.8 //打包版本 targetCompatibility = 1.8 // 自定义变量 ext { jjwtVersion = "0.9.0" springVersion = "2.0.0.RELEASE" lombokVersion = "1.18.4" mysqlVersion = "5.1.47" // animaVersion = "0.2.5-SNAPSHOT" animaVersion = "0.2.4" animaBetaVersion = "0.2.5-BETA" shiroVersion = "shiro-spring:1.4.0" thumbnailatorVersion = "0.4.8" swaggerVerion = "2.9.2" } sourceSets { main.java.srcDir "src/main/java" main.resources.srcDir "src/main/resources" // test.java.srcDir "src/test/java" // test.resources.srcDir "src/test/resources" } dependencies { compile("org.projectlombok:lombok:${lombokVersion}") compile("org.springframework.boot:spring-boot-starter-web:${springVersion}") compile("org.springframework.boot:spring-boot-starter-aop:${springVersion}") // 热部署 compile("org.springframework.boot:spring-boot-devtools:${springVersion}") // 数据库 compile ("io.github.biezhi:anima:${animaVersion}") // shiro权限框架 compile("org.apache.shiro:${shiroVersion}") compile("io.jsonwebtoken:jjwt:${jjwtVersion}") compile("com.auth0:java-jwt:3.3.0") compile group: 'org.xbib', name: 'jsr-305', version: '1.0.0' // 文件上传 compile("commons-fileupload:commons-fileupload:1.3.1") compile("commons-io:commons-io:2.3") compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.7' // 缩略图 compile group: 'net.coobird', name: 'thumbnailator', version: thumbnailatorVersion compile("io.springfox:springfox-swagger2:${swaggerVerion}") compile("io.springfox:springfox-swagger-ui:${swaggerVerion}") runtime("mysql:mysql-connector-java:${mysqlVersion}") testCompile group: 'junit', name: 'junit', version: '4.11' testCompile("org.springframework.boot:spring-boot-starter-test:${springVersion}") }<file_sep>/src/main/java/com/dekuofa/service/ScrollImageService.java package com.dekuofa.service; import com.dekuofa.model.entity.ScrollImage; import com.dekuofa.model.enums.BaseStatus; import com.dekuofa.model.param.PageParam; import io.github.biezhi.anima.page.Page; /** * @author dekuofa <br> * @date 2018-09-04 <br> */ public interface ScrollImageService extends BaseService<ScrollImage, Integer> { Page<ScrollImage> query(PageParam pageParam, BaseStatus... status); int countById(Integer id); } <file_sep>/src/main/java/com/dekuofa/model/entity/SysRole.java package com.dekuofa.model.entity; import com.dekuofa.model.BaseEntity; import com.dekuofa.model.param.SysRoleParam; import io.github.biezhi.anima.Model; import io.github.biezhi.anima.annotation.Column; import io.github.biezhi.anima.annotation.Table; import lombok.*; /** * @author dekuofa <br> * @date 2018-08-14 <br> */ @Data @EqualsAndHashCode(callSuper = false) @NoArgsConstructor @Table(name = "t_role") public class SysRole extends Model implements BaseEntity { private Integer id; private String name; @Column(name = "`desc`") private String desc; private Long createTime; private Long modifyTime; private Integer creatorId; private String creatorName; private Integer modifierId; private String modifierName; public SysRole(String name) { this.name = name; } public SysRole(SysRoleParam param) { this(param.getName()); } } <file_sep>/src/test/java/com/dekuofa/ArrayBuilder.java package com.dekuofa; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author dekuofa <br> * @date 2018-11-10 <br> */ public class ArrayBuilder { public static <T> void addToList(List<T> listArg, T... elements) { for (T x : elements) { listArg.add(x); } } public static void faultyMethod(List<String>... l) { Object[] objectArray = l; // Valid objectArray[0] = Arrays.asList(42); String s = l[0].get(0); // ClassCastException thrown here Object[] strings = new String[2]; strings[0] = "hi";// ok strings[1] = 100; } } <file_sep>/src/main/java/com/dekuofa/manager/LogManager.java package com.dekuofa.manager; import com.dekuofa.model.entity.SysLogInfo; import com.dekuofa.model.param.PageParam; import io.github.biezhi.anima.page.Page; /** * @author dekuofa <br> * @date 2018-08-29 <br> */ public interface LogManager { void save(SysLogInfo logInfo); Page<SysLogInfo> query(PageParam pageParam); } <file_sep>/src/main/java/com/dekuofa/utils/UuidUtil.java package com.dekuofa.utils; import java.util.UUID; /** * @author dekuofa <br> * @date 2018-09-03 <br> */ public class UuidUtil { public static String getRandomUUIDString() { return UUID.randomUUID().toString(); } } <file_sep>/src/main/java/com/dekuofa/service/ImageCardService.java package com.dekuofa.service; import com.dekuofa.model.entity.ImageCard; import com.dekuofa.model.param.PageParam; import io.github.biezhi.anima.page.Page; /** * @author dekuofa <br> * @date 2018-09-11 <br> */ public interface ImageCardService extends BaseService<ImageCard, Integer> { Page<ImageCard> query(PageParam pageParam); } <file_sep>/src/test/java/com/dekuofa/MyNode.java package com.dekuofa; /** * @author dekuofa <br> * @date 2018-11-10 <br> */ public class MyNode extends Node<Integer> { public MyNode(Integer data) { super(data); } public void setData(Integer data) { System.out.println("MyNode.setData"); super.setData(data); } } <file_sep>/src/main/java/com/dekuofa/utils/FileUtil.java package com.dekuofa.utils; import com.dekuofa.constant.Constants; import lombok.extern.slf4j.Slf4j; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.math.BigDecimal; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author dekuofa <br> * @date 2018-09-03 <br> */ @Slf4j public class FileUtil { /** * 文件类型 */ private static String FILE_TYPE_REGEX = ".(\\w+)$"; public static Optional<File> createDir(String path, String dirName) { final String dirPath = path + "/" + dirName; File dir = new File(dirPath); if (!dir.exists()) { boolean isSuccess = dir.mkdir(); if (!isSuccess) { log.error("创建文件夹失败:" + dirPath); return Optional.empty(); } } return Optional.of(dir); } public static Double getFileSizeOfMB(MultipartFile file) { Long size = file.getSize(); return new BigDecimal(size) .setScale(2) .divide(new BigDecimal(Constants.SIZE_OF_MB), BigDecimal.ROUND_UP) .doubleValue(); } public static Optional<String> getFileType(MultipartFile file) { String fileName = file.getOriginalFilename(); Pattern pattern = Pattern.compile(FILE_TYPE_REGEX); Matcher matcher = pattern.matcher(fileName); if (matcher.find()) { return Optional.of(matcher.group(1)); } return Optional.empty(); } } <file_sep>/src/main/java/com/dekuofa/manager/FileManager.java package com.dekuofa.manager; import com.dekuofa.model.NormalUserInfo; import com.dekuofa.model.UserInfo; import com.dekuofa.model.entity.FileInfo; import com.dekuofa.model.param.PageParam; import io.github.biezhi.anima.page.Page; import org.springframework.web.multipart.MultipartFile; /** * @author dekuofa <br> * @date 2018-09-03 <br> */ public interface FileManager { FileInfo upload(MultipartFile file, String fileName, UserInfo userInfo); Page<FileInfo> query(PageParam pageParam, String keyword); } <file_sep>/src/main/java/com/dekuofa/config/DataBaseConfig.java package com.dekuofa.config; import com.dekuofa.utils.BaseCodeEnumConverterFactory; import io.github.biezhi.anima.Anima; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; import org.sql2o.converters.Converter; import java.util.ArrayList; import java.util.List; /** * @author dekuofa <br> * @date 2018-08-08 <br> */ @Configuration public class DataBaseConfig { private Environment env; @Autowired public DataBaseConfig(Environment environment) { env = environment; } // todo convert 泛型增加优化 @Bean public Converter[] converters() { List<Converter<?>> converters = new ArrayList<>(); converters.add(BaseCodeEnumConverterFactory.newBaseCodeConverter()); converters.add(BaseCodeEnumConverterFactory.newGenderConvert()); converters.add(BaseCodeEnumConverterFactory.newUserTypeConvert()); return converters.toArray(new Converter[]{}); } /** * 创建 anima bean, 类似于dataSource */ @Bean public Anima anima(Converter[] converters) { String url = env.getProperty("spring.datasource.url"); String username = env.getProperty("spring.datasource.username"); String password = env.getProperty("spring.datasource.password"); assert !StringUtils.isEmpty(url); assert !StringUtils.isEmpty(username); assert !StringUtils.isEmpty(password); return Anima.open(url, username, password).addConverter(converters); } } <file_sep>/src/main/java/com/dekuofa/controller/PermissionController.java package com.dekuofa.controller; import com.dekuofa.manager.PermissionManager; import com.dekuofa.model.NormalUserInfo; import com.dekuofa.model.UserInfo; import com.dekuofa.model.param.PageParam; import com.dekuofa.model.response.RestResponse; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import java.util.List; /** * @author dekuofa <br> * @date 2018-08-28 <br> */ @RestController public class PermissionController implements BaseController { private PermissionManager permissionManager; @Autowired public PermissionController(PermissionManager permissionManager) { this.permissionManager = permissionManager; } @GetMapping("/permission") public RestResponse<?> list(PageParam pageParam) { return RestResponse.ok(permissionManager.list(pageParam)); } @RequiresAuthentication @PutMapping("/role/{id}/permission") public RestResponse<?> changePermission(@ApiIgnore UserInfo userInfo, @PathVariable("id") Integer id, @RequestParam("permissionIds") List<Integer> permissionIds) { try { permissionManager.changePermissions(id, permissionIds); return RestResponse.ok(); } catch (Exception e) { String msg = getErrorMessage(e); return RestResponse.fail(msg); } } } <file_sep>/src/main/java/com/dekuofa/model/response/LoginResponse.java package com.dekuofa.model.response; import com.dekuofa.model.UserInfo; import com.dekuofa.model.entity.Permission; import lombok.AllArgsConstructor; import lombok.Data; import java.util.Collection; /** * @author dekuofa <br> * @date 2018-08-22 <br> */ @Data @AllArgsConstructor public class LoginResponse { private UserInfo userInfo; private String token; private Collection<Permission> permissions; } <file_sep>/src/main/java/com/dekuofa/model/relation/RolePermission.java package com.dekuofa.model.relation; import io.github.biezhi.anima.Model; import lombok.Data; import lombok.EqualsAndHashCode; /** * @author dekuofa <br> * @date 2018-08-28 <br> */ @EqualsAndHashCode(callSuper = false) @Data public class RolePermission extends Model { private Integer roleId; private Integer permissionId; } <file_sep>/src/main/java/com/dekuofa/config/SwaggerConfig.java package com.dekuofa.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author dekuofa <br> * @date 2018-08-23 <br> */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Value("${swagger.host}") private String host; @Value("${swagger.path}") private String path; @Bean public Docket api(ApiInfo apiInfo) { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo) .host(host) .pathMapping(path) .securitySchemes(Collections.singletonList(apiKey())) .securityContexts(securityContexts()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } // swagger2 全局使用 jwt 配置 参照 http://fish119.site/2018/01/04/Swagger2-%E9%9D%9E%E5%85%A8%E5%B1%80Header%E5%8F%82%E6%95%B0%EF%BC%88Token%EF%BC%89%E9%85%8D%E7%BD%AE/ private List<SecurityContext> securityContexts() { return Collections.singletonList( SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("^(?!/?login).*$")) .build() ); } private List<SecurityReference> defaultAuth() { List<AuthorizationScope> authorizationScopes = new ArrayList<>(); authorizationScopes.add(new AuthorizationScope("global", "accessEverything")); return Collections.singletonList( new SecurityReference("Authorization", authorizationScopes.toArray(new AuthorizationScope[0]))); } private ApiKey apiKey() { return new ApiKey("Authorization", "Authorization", "header"); } @Bean public ApiInfo apiInfo(Contact contact) { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2构建RESTful API") .description("rest api 文档构建利器") .termsOfServiceUrl("http://blog.csdn.net/itguangit") .contact(contact) .version("1.0") .build(); } @Bean public Contact contact() { return new Contact("dekuofa", null, "<EMAIL>"); } } <file_sep>/src/main/java/com/dekuofa/model/response/UserInfoResponse.java package com.dekuofa.model.response; import lombok.Data; import java.util.Collection; /** * @author dekuofa <br> * @date 2018-09-07 <br> */ @Data public class UserInfoResponse { private Integer id; private String name; // 头像 private String avatar; private Collection<String> roles; public UserInfoResponse() { } public UserInfoResponse(String name, String avatar) { this.name = name; this.avatar = avatar; } public UserInfoResponse name(String name) { this.name = name; return this; } public UserInfoResponse avatar(String avatar) { this.avatar = avatar; return this; } public UserInfoResponse roles(Collection<String> roles) { this.roles = roles; return this; } public UserInfoResponse id(Integer id) { this.id = id; return this; } } <file_sep>/src/test/java/com/dekuofa/GenericTest.java package com.dekuofa; import com.dekuofa.utils.BaseCodeEnumConverterFactory; import org.sql2o.converters.Converter; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * 泛型测试 * * @author dekuofa <br> * @date 2018-11-07 <br> */ public class GenericTest { public static void main(String[] args) { Object[] objects = new Object[]{ // BaseCodeEnumConverterFactory.newCodeConverter(), BaseCodeEnumConverterFactory.newBaseCodeConverter(), new Node<>(5) }; for (Object o : objects) { Type[] types = o.getClass().getGenericInterfaces(); Type[] params = ((ParameterizedType) types[0]).getActualTypeArguments(); Class<?> type = (Class) params[0]; System.out.println(type.getName()); } } } <file_sep>/src/main/java/com/dekuofa/model/param/ScrollImageParam.java package com.dekuofa.model.param; import com.dekuofa.model.enums.BaseStatus; import io.swagger.annotations.ApiParam; import lombok.Data; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; /** * @author dekuofa <br> * @date 2018-09-04 <br> */ @Data public class ScrollImageParam { @NotEmpty(message = "图片url不能为空") private String url; @NotEmpty(message = "文件id不能为空") private Integer fileId; @NotEmpty(message = "图片类型不能为空") private String type; /** * 超链接 */ private String hyperlinks; /** * 排序 */ @NotNull(message = "排序值不能为空") private Integer order; @ApiParam(allowEmptyValue = true) private BaseStatus status; } <file_sep>/src/main/java/com/dekuofa/config/MvcControllerAdvice.java package com.dekuofa.config; import com.dekuofa.constant.Constants; import com.dekuofa.utils.IpKit; import com.dekuofa.utils.SecurityUtil; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import javax.servlet.http.HttpServletRequest; /** * @author dekuofa <br> * @date 2018-08-22 <br> */ @ControllerAdvice public class MvcControllerAdvice { @ModelAttribute public void addAttributed(Model model, HttpServletRequest request) { String token = request.getHeader(Constants.TOKEN_KEY); if (!StringUtils.isEmpty(token)) { SecurityUtil.getCurrentUserInfo() .ifPresent(userInfo -> model.addAttribute("userInfo", userInfo)); } String ip = IpKit.getClientIpAddress(request); model.addAttribute("ip", ip); } } <file_sep>/src/test/java/com/dekuofa/Parent.java package com.dekuofa; /** * @author dekuofa <br> * @date 2018-11-07 <br> */ public class Parent<T> { T data; public Parent(T data) { this.data = data; } public void setData(T data) { System.out.println("Parent setData"); this.data = data; } } <file_sep>/src/main/java/com/dekuofa/model/enums/UserType.java package com.dekuofa.model.enums; import lombok.AllArgsConstructor; import lombok.Getter; /** * @author ganxiang <br> * 时间:2018年06月11日 13:38<br> * 标题:CreatorType<br> * 功能:创建者枚举<br> */ @Getter @AllArgsConstructor public enum UserType implements BaseCodeEnum { /** * 后台用户 */ ADMIN(0, "后台用户"), /** * 前台用户 */ USER(1, "前台用户"); private Integer code; private String desc; public static UserType getByCode(Integer code) { UserType[] values = UserType.values(); for (UserType type : values) { if (type.getCode().equals(code)) { return type; } } return null; } } <file_sep>/src/main/java/com/dekuofa/model/entity/ScrollImage.java package com.dekuofa.model.entity; import com.dekuofa.model.BaseEntity; import com.dekuofa.model.enums.BaseStatus; import com.dekuofa.model.param.ScrollImageParam; import io.github.biezhi.anima.Model; import io.github.biezhi.anima.annotation.EnumMapping; import io.github.biezhi.anima.annotation.Table; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiParam; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.util.StringUtils; /** * 滚动图 * * @author dekuofa <br> * @date 2018-09-04 <br> */ @EqualsAndHashCode(callSuper = false) @Data @Table(name = "t_scroll_image") public class ScrollImage extends Model implements BaseEntity { private Integer id; /** * 图片地址 */ private String url; private Integer fileId; private String type; /** * 超链接 */ private String hyperlinks; /** * 排序 */ private Integer order; /** * 状态 normal=正常,deleted=已删除 */ private BaseStatus status; private Long createTime; private Long modifyTime; private Integer creatorId; private String creatorName; private Integer modifierId; private String modifierName; public ScrollImage() { } public ScrollImage(ScrollImageParam param) { this.type = param.getType(); this.order = param.getOrder(); this.fileId = param.getFileId(); this.hyperlinks = param.getHyperlinks(); } } <file_sep>/src/main/java/com/dekuofa/utils/JwtUtil.java package com.dekuofa.utils; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.dekuofa.constant.Constants; import com.dekuofa.exception.TipException; import com.dekuofa.model.UserInfo; import com.dekuofa.model.NormalUserInfo; import com.dekuofa.model.enums.UserType; import lombok.extern.log4j.Log4j2; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Optional; /** * @author ganxiang <br> * 时间:2018年05月03日 15:31<br> * 标题:JWTUtil<br> * 功能:json web token 工具类<br> */ @Log4j2 public class JwtUtil { /** * 设置过期时间,单位毫秒 * todo 目前token时间延长至12,需要想办法半小时过期如何处理 */ private static final long EXPIRE_TIME = 12 * 60 * 60 * 1000; /** * token前缀 */ private static final String TOKEN_HEAD = Constants.TOKEN_HEAD; /** * 校验token * * @param token 令牌 * @param userInfo 用户信息 * @param secret 用户密码 * @return 验证结果:true/false */ public static boolean verify(String token, UserInfo userInfo, String secret) { try { //根据token的信息构建解析方法 JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)) .withClaim("username", userInfo.getUsername()) .withClaim("userId", userInfo.getUserId()) .withClaim("userType", userInfo.getUserType().getCode()) .withClaim("nickName", userInfo.getNickName()) .build(); //如果验证失败会报错 verifier.verify(token); return true; } catch (UnsupportedEncodingException e1) { log.error("无法进行token编码"); // return false; } catch (SignatureVerificationException e2) { log.error("token已过期"); } catch (JWTVerificationException e3) { log.error("权限验证异常"); } return false; } /** * 从token中获取用户名 * * @param token 令牌 * @return token中的用户名 */ public static Optional<UserInfo> getUserInfo(String token) { try { DecodedJWT jwt = JWT.decode(token); Integer userId = jwt.getClaim("userId").asInt(); String username = jwt.getClaim("username").asString(); String nickName = jwt.getClaim("nickName").asString(); UserType userType = jwt.getClaim("userType").as(UserType.class); return Optional.of( new NormalUserInfo(userId, username, nickName, userType)); } catch (JWTDecodeException e) { log.error("jwt解析失败:" + e.getCause()); return Optional.empty(); } } /** * 生成token * * @param password 密码(<PASSWORD>) * @return token令牌,String */ public static String sign(UserInfo userInfo, String password) { try { Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); return // TOKEN_HEAD + JWT.create() .withClaim("username", userInfo.getUsername()) .withClaim("userId", userInfo.getUserId()) .withClaim("userType", userInfo.getUserType().getCode()) .withClaim("nickName", userInfo.getNickName()) .withExpiresAt(date) // 密码加盐 .sign(Algorithm.HMAC256(password)); } catch (UnsupportedEncodingException e) { log.error("生成token失败:" + e.getCause()); return null; } } public static String getToken(String secret) { if (secret == null || !secret.startsWith(TOKEN_HEAD)) { throw new TipException("token格式异常"); } final String token = secret.substring(TOKEN_HEAD.length()); return token; } } <file_sep>/src/main/java/com/dekuofa/controller/ImageCardController.java package com.dekuofa.controller; import com.dekuofa.manager.ImageCardManager; import com.dekuofa.model.UserInfo; import com.dekuofa.model.entity.ImageCard; import com.dekuofa.model.enums.BaseStatus; import com.dekuofa.model.param.ImageCardParam; import com.dekuofa.model.param.PageParam; import com.dekuofa.model.response.RestResponse; import io.github.biezhi.anima.page.Page; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; import static com.dekuofa.utils.DateUtil.newUnixMilliSecond; /** * @author dekuofa <br> * @date 2018-09-11 <br> */ @RestController public class ImageCardController implements BaseController { private ImageCardManager imageCardManager; @Autowired public ImageCardController(ImageCardManager imageCardManager) { this.imageCardManager = imageCardManager; } @PostMapping("/imageCard") public RestResponse<?> save(@Valid @RequestBody ImageCardParam param, @ApiParam(hidden = true) UserInfo userInfo) { ImageCard imageCard = new ImageCard(param); imageCard.setStatus(BaseStatus.INIT); Long now = newUnixMilliSecond(); imageCard.setCreateInfo(userInfo, now) .setModifyInfo(userInfo, now); try { Integer id = imageCardManager.save(imageCard); return RestResponse.ok(id); } catch (Exception e) { String msg = getErrorMessage(e); return RestResponse.fail(msg); } } @GetMapping("/imageCard") public RestResponse<?> query(PageParam param) { try { Page<ImageCard> result = imageCardManager.query(param); return RestResponse.ok(result); } catch (Exception e) { String msg = getErrorMessage(e); return RestResponse.fail(msg); } } @GetMapping("/imageCard/list") public RestResponse<?> list() { try { List<ImageCard> result = imageCardManager.list(); return RestResponse.ok(result); } catch (Exception e) { String msg = getErrorMessage(e); return RestResponse.fail(msg); } } @PutMapping("/imageCard/{id}") public RestResponse<?> modify(@PathVariable @ApiParam(hidden = true) Integer id, @ApiParam(hidden = true) UserInfo userInfo, @Valid @RequestBody ImageCardParam param) { try { ImageCard imageCard = new ImageCard(param); imageCard.setModifyInfo(userInfo, newUnixMilliSecond()); imageCard.setId(id); imageCardManager.modify(imageCard); return RestResponse.ok(); } catch (Exception e) { String msg = getErrorMessage(e); return RestResponse.fail(msg); } } } <file_sep>/src/main/java/com/dekuofa/utils/CommonValidator.java package com.dekuofa.utils; import com.dekuofa.constant.Constants; import com.dekuofa.exception.TipException; import com.dekuofa.exception.ValidateException; import com.dekuofa.model.param.PasswdParam; import com.dekuofa.model.param.SysRoleParam; import com.dekuofa.model.param.UserParam; import org.springframework.util.StringUtils; import static com.dekuofa.constant.Constants.*; /** * @author dekuofa <br> * @date 2018-08-28 <br> */ public class CommonValidator { public static void validate(SysRoleParam roleParam) throws TipException { if (roleParam == null) { throw new ValidateException("角色参数不能为空"); } if (StringUtils.isEmpty(roleParam.getName())) { throw new ValidateException("角色名不能为空"); } } public static void validate(PasswdParam param) throws TipException { String oldPasswd = param.getOldPasswd(); String newPasswd = param.getNewPasswd(); if (StringUtils.isEmpty(oldPasswd)) { throw new TipException("旧密码不能为空"); } if (StringUtils.isEmpty(newPasswd)) { throw new TipException("新密码不能为空"); } // todo 条件校验 1.包含小写字母、特殊符号、数字、大写字母其中三种,2.最小长度&最大长度 if (newPasswd.length() < Constants.MIN_OF_PASSWD) { throw new TipException("密码长度不能小于" + Constants.MIN_OF_PASSWD + "位"); } if (newPasswd.length() > Constants.MAX_OF_PASSWD) { throw new TipException("密码长度不能大于" + Constants.MIN_OF_PASSWD + "位"); } } public static void validate(UserParam param) { String username = param.getUsername(); String nickName = param.getNickName(); String[] roles = param.getRoles(); if (StringUtils.isEmpty(username)) { throw new TipException("用户名不能为空"); } if (StringUtils.isEmpty(nickName)) { throw new TipException("昵称不能为空"); } if (roles.length < 1) { throw new TipException("至少为用户分配一个角色"); } if (username.length() > MAX_OF_USERNAME || username.length() < MIN_OF_USERNAME) { throw new TipException("用户名长度:" + MIN_OF_USERNAME + " ~ " + MAX_OF_USERNAME); } if (nickName.length() > MAX_OF_NICK_NAME || nickName.length() < MIN_OF_NICK_NAME) { throw new TipException("昵称长度:" + MIN_OF_NICK_NAME + " ~ " + MAX_OF_NICK_NAME); } } } <file_sep>/README.md # springboot-template #### 项目介绍 springboot框架模板,用于快速搭建一个后台 `REST` 框架的模板项目 **todoList** - [ ] 部分属性存放至数据库中 #### 软件架构 1. Spring Boot(Spring + SpringMVC) 2. [shiro](https://shiro.apache.org/documentation.html):Apache 的安全框架 3. [anima](https://github.com/biezhi/anima):国人开发的轻量级数据库操作库,简单易用且优美(~~吹爆~~) 待补充... #### 编码约定 1. Controller 层:处理参数的基本校验(满足格式、必填、用户登录以及权限信息)& 参数组装,以及调用 Manager 的方法,处理下层异常,禁止抛出异常 2. Manager 层:处理业务逻辑类的校验(唯一性、数据状态是否能被修改等),以及调用 Service 的方法并处理异常以及抛出部分异常 3. Service 层:处理与数据库的交互(sql相关),并抛出异常 注意:以上三层,同层之间不能互相调用,仅能通过上层来调用。 ##### 例1:用户权限查询 禁止如下写法: ```java // RoleService.java public List<Permission> getUserPermission(Integer userId) { ... List<Role> roles = roleDao.findByUserId(userId); // 不应该在 roleService 中使用 permissionService 的方法,因为他们同属 Service return permissionService.getPermissions(roles); } // PermissionService.java public List<Permission> getPermissions(List<Role> roles) { ... return permissionDao.getPermissions(roles); } ``` 规范写法: ```java // RoleService.java public List<Role> getRoles(Integer userId) { ... return roleDao.findByUserId(userId); } // PermissionService.java public List<Permission> getPermissions(List<Role> roles) { ... return permissionDao.getPermissions(roles); } // UserManager.java public List<Permission> getUserPermissions(Integer userId) { List<Role> roles = roleService.getRoles(userId); List<Permission> permissions = permissionService.getPermission(roles); return permissions; } ``` #### 安装教程 待补充... #### 使用说明 待补充... #### 相关开发博客 待补充... <file_sep>/src/main/java/com/dekuofa/controller/RoleController.java package com.dekuofa.controller; import com.dekuofa.annotation.SysLog; import com.dekuofa.manager.RoleManager; import com.dekuofa.model.NormalUserInfo; import com.dekuofa.model.UserInfo; import com.dekuofa.model.entity.SysRole; import com.dekuofa.model.param.SysRoleParam; import com.dekuofa.model.response.RestResponse; import com.dekuofa.utils.DateUtil; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import java.util.Collection; import static com.dekuofa.utils.CommonValidator.validate; import static com.dekuofa.utils.DateUtil.newUnixMilliSecond; /** * @author dekuofa <br> * @date 2018-08-28 <br> */ @RestController public class RoleController implements BaseController { private RoleManager roleManager; @Autowired public RoleController(RoleManager roleManager) { this.roleManager = roleManager; } @SysLog(action = "新增角色") @RequiresAuthentication @PostMapping("/role") public RestResponse<?> add(@RequestBody SysRoleParam param, @ApiIgnore UserInfo userInfo) { validate(param); SysRole role = new SysRole(param); if (roleManager.isExist(role)) { return RestResponse.fail("新增失败:角色名已存在"); } Long now = newUnixMilliSecond(); role.setCreateInfo(userInfo, now).setModifyInfo(userInfo, now); Integer id = roleManager.addRole(role); return RestResponse.ok(id); } @SysLog(action = "修改角色信息") @RequiresAuthentication @PutMapping("/role/{id}") public RestResponse<?> modify(@PathVariable("id") Integer id, @RequestBody SysRoleParam param, @ApiIgnore UserInfo userInfo) { if (id == null) { RestResponse.fail("修改失败:角色id不能为空"); } SysRole role = new SysRole(param); if (roleManager.isExist(role)) { return RestResponse.fail("修改失败:角色名已存在"); } role.setModifyInfo(userInfo, newUnixMilliSecond()); role.setId(id); roleManager.modify(role); return RestResponse.ok(id); } @GetMapping("/role") public RestResponse<?> list() { Collection<SysRole> roles = roleManager.list(); return RestResponse.ok().payload(roles); } } <file_sep>/src/main/java/com/dekuofa/constant/Constants.java package com.dekuofa.constant; /** * @author ganxiang <br> * 时间:2018年06月04日 11:07<br> * 标题:Constant<br> * 功能:常量<br> */ public interface Constants { /** * MB单位 */ Long SIZE_OF_MB = 1024 * 1024L; /** * 富文本最大长度5000 */ int MAX_OF_CONTENT = 5000; /** * 最大用户名长度 */ int MAX_OF_USERNAME = 30; int MIN_OF_USERNAME = 6; /** * 最大昵称长度 */ int MAX_OF_NICK_NAME = 30; int MIN_OF_NICK_NAME = 4; /** * 最大密码长度 */ int MAX_OF_PASSWD = 64; int MIN_OF_PASSWD = 8; /** * init password */ String INIT_PASSWD = "<PASSWORD>"; /** * 默认分页页数大小 */ int DEFAULT_PAGE_SIZE = 10; /** * 默认分页,当前页数 */ int DEFAULT_PAGE_NUM = 1; int FIRST_PAGE_NUM = 1; /** * 默认分页页数大小 */ int DEFAULT_MAX_PAGE_SIZE = 500; String DEFAULT_FILE_TYPE = ".file"; /** * token key */ String TOKEN_KEY = "Authorization"; String TOKEN_HEAD = "Bearer "; /** * 默认头像地址 */ String DEFAULT_USER_AVATAR = "/user.png"; /** * 手机号校验正则biaodashu */ String REGEX_OF_MOBILE = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$"; /** * 异常信息 */ String ERROR_MESSAGE = "服务异常"; } <file_sep>/src/main/java/com/dekuofa/service/FileService.java package com.dekuofa.service; import com.dekuofa.model.entity.FileInfo; import com.dekuofa.model.param.PageParam; import io.github.biezhi.anima.page.Page; /** * @author dekuofa <br> * @date 2018-09-03 <br> */ public interface FileService { Integer save(FileInfo fileInfo); Page<FileInfo> query(PageParam pageParam, String keyword); void modify(FileInfo fileInfo); } <file_sep>/src/main/java/com/dekuofa/model/param/ImageCardParam.java package com.dekuofa.model.param; import com.dekuofa.model.enums.BaseStatus; import io.swagger.annotations.ApiParam; import lombok.Data; import org.hibernate.validator.constraints.URL; import javax.validation.constraints.NotEmpty; /** * @author dekuofa <br> * @date 2018-09-06 <br> */ @Data public class ImageCardParam { @URL(message = "超链接格式异常") private String hyperlinks; private String name; private String desc; @NotEmpty(message = "图片地址不能为空") private String url; @ApiParam(allowEmptyValue = true) private BaseStatus status; } <file_sep>/src/main/java/com/dekuofa/model/param/LoginParam.java package com.dekuofa.model.param; import lombok.Data; /** * @author dekuofa <br> * @date 2018-08-22 <br> */ @Data public class LoginParam { private String username; private String password; } <file_sep>/src/main/java/com/dekuofa/service/RoleService.java package com.dekuofa.service; import com.dekuofa.model.entity.SysRole; import com.dekuofa.model.param.SysRoleParam; import com.dekuofa.model.relation.UserRole; import io.swagger.models.auth.In; import java.util.Collection; import java.util.List; import java.util.Set; /** * @author dekuofa <br> * @date 2018-08-20 <br> */ public interface RoleService { Set<SysRole> getRoles(Integer userId); Integer addRole(SysRole role); List<Integer> getRoleIds(String[] roles); void modify(SysRole role); Collection<SysRole> list(); boolean isExist(String roleName); void addUserRoles(Integer userId, List<Integer> roleIds); void changeUserRoles(Integer userId, List<UserRole> addRoleIds, List<Integer> deleteIds); } <file_sep>/src/main/java/com/dekuofa/model/NormalUserInfo.java package com.dekuofa.model; import com.dekuofa.model.enums.UserType; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author dekuofa <br> * @date 2018-08-21 <br> */ @Data @AllArgsConstructor @NoArgsConstructor public class NormalUserInfo implements UserInfo { private Integer userId; private String username; private String nickName; private UserType userType; @Override public boolean isEmpty() { return userId == null || username == null || nickName == null; } @Override public boolean isCurrentUser(Integer userId) { return userId != null && userId.equals(this.userId); } } <file_sep>/src/main/java/com/dekuofa/service/impl/RoleServiceImpl.java package com.dekuofa.service.impl; import com.dekuofa.exception.TipException; import com.dekuofa.model.entity.SysRole; import com.dekuofa.model.relation.UserRole; import com.dekuofa.service.RoleService; import org.springframework.stereotype.Service; import java.beans.Transient; import java.util.*; import java.util.stream.Collectors; import static io.github.biezhi.anima.Anima.*; import static java.util.stream.Collectors.toList; /** * @author dekuofa <br> * @date 2018-08-14 <br> */ @Service public class RoleServiceImpl implements RoleService { @Override public Set<SysRole> getRoles(Integer userId) { List<SysRole> sysRoles = select() .bySQL(SysRole.class, "select r.id, r.name from t_role r\n" + "right join user_role ur\n" + " on r.id = ur.role_id\n" + "where ur.user_id = ?", userId).all(); return new HashSet<>(sysRoles); } @Transient @Override public Integer addRole(SysRole role) { Integer id = save(role).asInt(); if (id == null) { throw new TipException("服务器异常:新增用户失败"); } return id; } @Override public List<Integer> getRoleIds(String[] roles) { List<SysRole> roleList = select("id") .from(SysRole.class) .in(SysRole::getName, (Object[]) roles).all(); return roleList.stream().map(SysRole::getId).collect(toList()); } @Override public void modify(SysRole role) { role.update(); } @Override public Collection<SysRole> list() { return select().from(SysRole.class).all(); } @Override public boolean isExist(String roleName) { long count = select().from(SysRole.class) .where("name", roleName) .count(); return count >= 1; } @Override public void addUserRoles(Integer userId, List<Integer> roleIds) { List<UserRole> userRoles = roleIds.stream() .map(roleId -> new UserRole(userId, roleId)) .collect(toList()); saveBatch(userRoles); } @Transient @Override public void changeUserRoles(Integer userId, List<UserRole> addRoleIds, List<Integer> deleteIds) { if (deleteIds != null && deleteIds.size() != 0) { delete().from(UserRole.class) .where("user_id", userId) .in("role_id", deleteIds).execute(); } if (addRoleIds != null && addRoleIds.size() != 0) { saveBatch(addRoleIds); } } } <file_sep>/src/main/java/com/dekuofa/model/response/RestResponse.java package com.dekuofa.model.response; import com.dekuofa.utils.DateUtil; import lombok.Data; import static com.dekuofa.utils.DateUtil.newUnixMilliSecond; /** * @author dekuofa <br> * @date 2018-08-08 <br> */ @Data public class RestResponse<T> { /** * 返回的信息 */ private T payload; /** * 错误代码 */ private int code = 0; /** * 错误信息 */ private String msg; /** * 是否成功 */ private boolean success; /** * 时间戳 */ private Long timestamp; public RestResponse() { this.timestamp = newUnixMilliSecond(); } public RestResponse(boolean success) { this.timestamp = newUnixMilliSecond(); this.success = success; } public RestResponse(boolean success, T payload) { this.timestamp = newUnixMilliSecond(); this.payload = payload; this.success = success; } public RestResponse<T> success(boolean success) { this.success = success; return this; } public RestResponse<T> payload(T payload) { this.payload = payload; return this; } public RestResponse<T> code(int code) { this.code = code; return this; } public RestResponse<T> message(String msg) { this.msg = msg; return this; } public static <T> RestResponse<T> ok() { return new RestResponse<T>().success(true); } public static <T> RestResponse<T> ok(T payload) { return new RestResponse<T>().success(true).payload(payload); } public static <T> RestResponse ok(T payload, int code) { return new RestResponse<T>().success(true).payload(payload).code(code); } public static <T> RestResponse<T> fail() { return new RestResponse<T>().success(false); } public static <T> RestResponse<T> fail(String message) { return new RestResponse<T>().success(false).code(1).message(message); } public static <T> RestResponse fail(int code, String message) { return new RestResponse<T>().success(false).message(message).code(code); } }
989ee4fbde1b2091244945e289f27831d5d5980e
[ "Markdown", "Java", "Gradle" ]
52
Java
xiwenAndlejian/springboot-template
fe7bc818192f93888dea62d70d7bc9e08995cfb0
9ec5a04437bafc9e8cb711c93b3b75ef135200a7
refs/heads/master
<repo_name>obastemur/esp32s<file_sep>/esp-azure/main/iothub_client_sample_mqtt.c // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdio.h> #include <stdlib.h> #include "esp_system.h" #include "iothub_client.h" #include "iothub_message.h" #include "azure_c_shared_utility/threadapi.h" #include "azure_c_shared_utility/crt_abstractions.h" #include "azure_c_shared_utility/platform.h" #include "iothubtransportmqtt.h" #include "iothub_client_version.h" #include "iothub_device_client_ll.h" #include "iothub_client_options.h" #include "azure_prov_client/prov_device_ll_client.h" #include "azure_prov_client/prov_security_factory.h" #include "azure_prov_client/prov_transport_mqtt_client.h" #ifdef MBED_BUILD_TIMESTAMP #include "certs.h" #endif // MBED_BUILD_TIMESTAMP static int callbackCounter; static char msgText[1024]; static char propText[1024]; static bool g_continueRunning; #define MESSAGE_COUNT 0 // Number of telemetry messages to send before exiting, or 0 to keep sending forever #define DOWORK_LOOP_NUM 3 typedef struct EVENT_INSTANCE_TAG { IOTHUB_MESSAGE_HANDLE messageHandle; size_t messageTrackingId; // For tracking the messages within the user callback. } EVENT_INSTANCE; DEFINE_ENUM_STRINGS(PROV_DEVICE_RESULT, PROV_DEVICE_RESULT_VALUE); DEFINE_ENUM_STRINGS(PROV_DEVICE_REG_STATUS, PROV_DEVICE_REG_STATUS_VALUES); static const char* global_prov_uri = "global.azure-devices-provisioning.net"; static char* g_access_key = "PRIMARY OR SECONDARY KEY HERE"; static const char* scope_id = "SCOPE ID HERE"; static const char* reg_id = "DEVICE ID HERE"; static char* conn_str = NULL; static bool g_use_proxy = false; static const char* PROXY_ADDRESS = "127.0.0.1"; #define PROXY_PORT 8888 #define MESSAGES_TO_SEND 2 #define TIME_BETWEEN_MESSAGES 2 typedef struct CLIENT_SAMPLE_INFO_TAG { unsigned int sleep_time; char* iothub_uri; char* access_key_name; char* device_key; char* device_id; int registration_complete; } CLIENT_SAMPLE_INFO; typedef struct IOTHUB_CLIENT_SAMPLE_INFO_TAG { int connected; int stop_running; } IOTHUB_CLIENT_SAMPLE_INFO; static IOTHUBMESSAGE_DISPOSITION_RESULT receive_msg_callback(IOTHUB_MESSAGE_HANDLE message, void* user_context) { IOTHUB_CLIENT_SAMPLE_INFO* iothub_info = (IOTHUB_CLIENT_SAMPLE_INFO*)user_context; printf("Stop message recieved from IoTHub\r\n"); iothub_info->stop_running = 1; return IOTHUBMESSAGE_ACCEPTED; } static void registation_status_callback(PROV_DEVICE_REG_STATUS reg_status, void* user_context) { printf("."); } static void iothub_connection_status(IOTHUB_CLIENT_CONNECTION_STATUS result, IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason, void* user_context) { if (user_context == NULL) { printf("iothub_connection_status user_context is NULL\r\n"); } else { IOTHUB_CLIENT_SAMPLE_INFO* iothub_info = (IOTHUB_CLIENT_SAMPLE_INFO*)user_context; if (result == IOTHUB_CLIENT_CONNECTION_AUTHENTICATED) { iothub_info->connected = 1; } else { iothub_info->connected = 0; iothub_info->stop_running = 1; } } } static void register_device_callback(PROV_DEVICE_RESULT register_result, const char* iothub_uri, const char* device_id, void* user_context) { if (user_context == NULL) { printf("user_context is NULL\r\n"); } else { CLIENT_SAMPLE_INFO* user_ctx = (CLIENT_SAMPLE_INFO*)user_context; if (register_result == PROV_DEVICE_RESULT_OK) { printf("\nRegistration Information received from service: %s!\r\n", iothub_uri); mallocAndStrcpy_s(&user_ctx->iothub_uri, iothub_uri); mallocAndStrcpy_s(&user_ctx->device_id, device_id); user_ctx->registration_complete = 1; size_t len = snprintf(NULL, 0, "HostName=%s;DeviceId=%s;SharedAccessKey=%s", iothub_uri, device_id, g_access_key); conn_str = (char*) malloc(len + 2); if (conn_str == NULL) { printf("OOM while creating connection string\n"); exit(1); } int pos = snprintf(conn_str, len + 1, "HostName=%s;DeviceId=%s;SharedAccessKey=%s", iothub_uri, device_id, g_access_key); conn_str[pos] = 0; } else { printf("Failure encountered on registration %s\r\n", ENUM_TO_STRING(PROV_DEVICE_RESULT, register_result) ); user_ctx->registration_complete = 2; } } } bool getConnectionString() { prov_dev_set_symmetric_key_info(reg_id, g_access_key); bool traceOn = false; prov_dev_security_init(SECURE_DEVICE_TYPE_SYMMETRIC_KEY); HTTP_PROXY_OPTIONS http_proxy; CLIENT_SAMPLE_INFO user_ctx; memset(&http_proxy, 0, sizeof(HTTP_PROXY_OPTIONS)); memset(&user_ctx, 0, sizeof(CLIENT_SAMPLE_INFO)); user_ctx.registration_complete = 0; user_ctx.sleep_time = 10; if (g_use_proxy) { http_proxy.host_address = PROXY_ADDRESS; http_proxy.port = PROXY_PORT; } PROV_DEVICE_LL_HANDLE handle; if ((handle = Prov_Device_LL_Create(global_prov_uri, scope_id, Prov_Device_MQTT_Protocol)) == NULL) { printf("failed calling Prov_Device_LL_Create\r\n"); } else { if (http_proxy.host_address != NULL) { Prov_Device_LL_SetOption(handle, OPTION_HTTP_PROXY, &http_proxy); } Prov_Device_LL_SetOption(handle, PROV_OPTION_LOG_TRACE, &traceOn); if (Prov_Device_LL_Register_Device(handle, register_device_callback, &user_ctx, registation_status_callback, &user_ctx) != PROV_DEVICE_RESULT_OK) { printf("failed calling Prov_Device_LL_Register_Device\r\n"); } else { do { Prov_Device_LL_DoWork(handle); ThreadAPI_Sleep(user_ctx.sleep_time); } while (user_ctx.registration_complete == 0); } Prov_Device_LL_Destroy(handle); } if (user_ctx.registration_complete != 1) { printf("error: registration failed!\r\n"); } else { IOTHUB_CLIENT_TRANSPORT_PROVIDER iothub_transport; iothub_transport = MQTT_Protocol; IOTHUB_DEVICE_CLIENT_LL_HANDLE device_ll_handle; if ((device_ll_handle = IoTHubDeviceClient_LL_CreateFromDeviceAuth(user_ctx.iothub_uri, user_ctx.device_id, iothub_transport) ) == NULL) { printf("failed create IoTHub client from connection string %s!\r\n", user_ctx.iothub_uri); return false; } else { IOTHUB_CLIENT_SAMPLE_INFO iothub_info; iothub_info.stop_running = 0; iothub_info.connected = 0; IoTHubDeviceClient_LL_SetConnectionStatusCallback(device_ll_handle, iothub_connection_status, &iothub_info); IoTHubDeviceClient_LL_Destroy(device_ll_handle); } } free(user_ctx.iothub_uri); free(user_ctx.device_id); return true; } static unsigned char* bytearray_to_str(const unsigned char *buffer, size_t len) { unsigned char* ret = (unsigned char*)malloc(len+1); memcpy(ret, buffer, len); ret[len] = '\0'; return ret; } static IOTHUBMESSAGE_DISPOSITION_RESULT ReceiveMessageCallback(IOTHUB_MESSAGE_HANDLE message, void* userContextCallback) { int* counter = (int*)userContextCallback; const char* buffer; size_t size; if (IoTHubMessage_GetByteArray(message, (const unsigned char**)&buffer, &size) != IOTHUB_MESSAGE_OK) { printf("unable to retrieve the message data\r\n"); } else { unsigned char* message_string = bytearray_to_str((const unsigned char *)buffer, size); printf("IoTHubMessage_GetByteArray received message: \"%s\" \n", message_string); free(message_string); // If we receive the word 'quit' then we stop running if (size == (strlen("quit") * sizeof(char)) && memcmp(buffer, "quit", size) == 0) { g_continueRunning = false; } } // Retrieve properties from the message MAP_HANDLE mapProperties = IoTHubMessage_Properties(message); if (mapProperties != NULL) { const char*const* keys; const char*const* values; size_t propertyCount = 0; if (Map_GetInternals(mapProperties, &keys, &values, &propertyCount) == MAP_OK) { if (propertyCount > 0) { size_t index = 0; for (index = 0; index < propertyCount; index++) { //(void)printf("\tKey: %s Value: %s\r\n", keys[index], values[index]); } //(void)printf("\r\n"); } } } /* Some device specific action code goes here... */ (*counter)++; return IOTHUBMESSAGE_ACCEPTED; } static void SendConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback) { EVENT_INSTANCE* eventInstance = (EVENT_INSTANCE*)userContextCallback; size_t id = eventInstance->messageTrackingId; printf("Confirmation[%d] received for message tracking id = %d with result = %s\r\n", callbackCounter, (int)id, ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result)); /* Some device specific action code goes here... */ callbackCounter++; IoTHubMessage_Destroy(eventInstance->messageHandle); } void iothub_client_sample_mqtt_run(void) { printf("\nFile:%s Compile Time:%s %s\n",__FILE__,__DATE__,__TIME__); IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle; EVENT_INSTANCE messages[MESSAGE_COUNT || 1]; g_continueRunning = true; srand((unsigned int)time(NULL)); double avgWindSpeed = 10.0; callbackCounter = 0; int receiveContext = 0; if (platform_init() != 0) { printf("Failed to initialize the platform.\r\n"); } else { if (!getConnectionString()) return; if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(conn_str, MQTT_Protocol)) == NULL) { printf("ERROR: iotHubClientHandle is NULL!\r\n"); } else { bool traceOn = true; IoTHubClient_LL_SetOption(iotHubClientHandle, "logtrace", &traceOn); #ifdef MBED_BUILD_TIMESTAMP // For mbed add the certificate information if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) { printf("failure to set option \"TrustedCerts\"\r\n"); } #endif // MBED_BUILD_TIMESTAMP /* Setting Message call back, so we can receive Commands. */ if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK) { printf("ERROR: IoTHubClient_LL_SetMessageCallback..........FAILED!\r\n"); } else { printf("IoTHubClient_LL_SetMessageCallback...successful.\r\n"); /* Now that we are ready to receive commands, let's send some messages */ size_t iterator = 0; do { if ((!MESSAGE_COUNT || (iterator < MESSAGE_COUNT)) && (iterator<= callbackCounter)) { EVENT_INSTANCE *thisMessage = &messages[MESSAGE_COUNT ? iterator : 0]; sprintf_s(msgText, sizeof(msgText), "{\"temp\":%d}", (int) (avgWindSpeed + (rand() % 4 + 2))); printf("Ready to Send String:%s\n",(const char*)msgText); if ((thisMessage->messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)msgText, strlen(msgText))) == NULL) { printf("ERROR: iotHubMessageHandle is NULL!\r\n"); } else { thisMessage->messageTrackingId = iterator; MAP_HANDLE propMap = IoTHubMessage_Properties(thisMessage->messageHandle); sprintf_s(propText, sizeof(propText), "PropMsg_%zu", iterator); if (Map_AddOrUpdate(propMap, "PropName", propText) != MAP_OK) { printf("ERROR: Map_AddOrUpdate Failed!\r\n"); } if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, thisMessage->messageHandle, SendConfirmationCallback, thisMessage) != IOTHUB_CLIENT_OK) { printf("ERROR: IoTHubClient_LL_SendEventAsync..........FAILED!\r\n"); } else { printf("IoTHubClient_LL_SendEventAsync accepted message [%d] for transmission to IoT Hub.\r\n", (int)iterator); } } iterator++; } IoTHubClient_LL_DoWork(iotHubClientHandle); printf("Sleeping for 5\n"); ThreadAPI_Sleep(5000); // if (callbackCounter>=MESSAGE_COUNT){ // printf("done sending...\n"); // break; // } } while (g_continueRunning); printf("iothub_client_sample_mqtt has gotten quit message, call DoWork %d more time to complete final sending...\r\n", DOWORK_LOOP_NUM); size_t index = 0; for (index = 0; index < DOWORK_LOOP_NUM; index++) { IoTHubClient_LL_DoWork(iotHubClientHandle); ThreadAPI_Sleep(1); } } IoTHubClient_LL_Destroy(iotHubClientHandle); } platform_deinit(); } } int main(void) { iothub_client_sample_mqtt_run(); return 0; } <file_sep>/esp-azure/doc/iothub_explorer.md # iothub-explorer usage ## login [any operation should login first] ``` iothub-explorer login "HostName=chenwu-ms-lot-hub.azure-devices.cn;SharedAccessKeyName=iothubowner;SharedAccessKey=<KEY> ``` ## list all device ``` iothub-explorer list ``` ## get special device detail info ``` iothub-explorer get myFirstNodeDevice --connection-string ``` ## create one device ``` iothub-explorer create AirConditionDevice_001 --connection-string ``` ## delete one device ``` iothub-explorer delete myFirstNodeDevice ``` ## monitor your device ``` iothub-explorer monitor-events AirConditionDevice_001 --login 'HostName=chenwu-ms-lot-hub.azure-devices.cn;SharedAccessKeyName=iothubowner;SharedAccessKey=<KEY> ``` ## send message to device ``` iothub-explorer send AirConditionDevice_001 "hello,my friends!" ``` ``` iothub-explorer send AirConditionDevice_001 quit ``` <file_sep>/esp-azure/README.md # A MQTT Demo that Connects ESP device to Azure Cloud # Table of Contents - [Introduction](#introduction) - [Preparation](#preparation) - [Configuring and Building](#configuring-and-building) - [Checking Result](#checking-result) - [Troubleshooting](#troubleshooting) ## Introduction <a name="Introduction"></a> Espressif offers a wide range of fully-certified Wi-Fi & BT modules powered by our own advanced SoCs. For more details, see [Espressif Modules](https://www.espressif.com/en/products/hardware/modules). Azure cloud is one of the most wonderful clouds that collects data from lots of devices or pushes data to IoT devices. For more details, see [Azure IoT Hub](https://www.azure.cn/en-us/home/features/iot-hub/). This demo demonstrates how to firstly connect your device (ESP devices or IoT devices with ESP devices inside) to Azure, using MQTT protocol, then send data to Azure as well as receive message from Azure. Main workflow: ![esp-azure-workflow](doc/_static/esp-azure-workflow.png) ## Preparation <a name="preparation"></a> ### 1. Hardware - An **ubuntu environment** should be set up to build your demo; - Any **[ESP device](https://www.espressif.com/en/products/hardware/modules)** can be used to run your demo. ### 2. Azure IoT Hub - [Get iothub connection string (primary key)](https://www.azure.cn/en-us/pricing/1rmb-trial-full/?form-type=identityauth) from the Azure IoT Hub, which will be used later. An example can be seen below: ``` HostName=yourname-ms-lot-hub.azure-devices.cn;SharedAccessKeyName=iothubowner;SharedAccessKey=<KEY> ``` - For step-by-step instructions, please click [here](doc/IoT_Suite.md). ### 3. iothub-explorer - Install [Node.js](https://nodejs.org/en/); - Install [iothub-explorer](https://www.npmjs.com/package/iothub-explorer) with command line `npm install -g iothub-explorer`. - If failed, please check [here](http://thinglabs.io/workshop/esp8266/setup-azure-iot-hub/) for more information. - If succeeded, please check the version information with the command lines below: ``` $ node -v v6.9.5 $ iothub-explorer -V 1.1.6 ``` After that, you should be able to use iothub-explorer to manage your iot-device. ### 4. Device Connection String - login with the **iothub connection string (primary key)** you got earlier with command lines; - create your device, and get a **device connection string**. An example can be seen: ``` "HostName=esp-hub.azure-devices.net;DeviceId=yourdevice;SharedAccessKey=<KEY>; ``` For detailed instruction, please click [Here](doc/iothub_explorer.md). ### 5. SDK - [AZURE-SDK](https://github.com/espressif/esp-azure) can be implemented to connect your ESP devices to Azure, using MQTT protocol. - Espressif SDK - For ESP32 platform: [ESP-IDF](https://github.com/espressif/esp-idf) - For ESP8266 platform: [ESP8266_RTOS_SDK](https://github.com/espressif/ESP8266_RTOS_SDK) ### 6. Compiler - For ESP32 platform: [Here](https://github.com/espressif/esp-idf/blob/master/README.md) - For ESP8266 platform: [Here](https://github.com/espressif/ESP8266_RTOS_SDK/blob/master/README.md) ## Configuring and Building <a name="Configuring_and_Building"></a> ### 1. Cloning Git submodules This repo uses [Git Submodules](https://git-scm.com/book/en/v2/Git-Tools-Submodules) for its dependancies. To successfully clone these other repositories, after cloning this repo, use the following command in the root: ``` bash git submodule update --init --recursive ``` ### 2. Configuring your Azure IOT Hub Device Connection String, Wi-Fi and serial port - Go to `make menuconfig` -> `Example configuration` to configure your Azure IOT Hub Device Connection String, Wi-Fi SSID and Password; - Go to `make menuconfig` -> `Serial flasher config` to configure you serial port. ### 3. Building your demo and flash to ESP device with `$make flash`. If failed, please: - make sure your ESP device had connected to PC with serial port; - make sure you have selected the corrected serial port; - command `> sudo usermod -a -G dialout $USER` can also be used. To monitor the device output while running, run ``` bash make monitor ``` To exit the monitor, hit Control-] You can also run the build and monitor in onte step and run with multiple compiler threads: ``` bash make -j4 flash monitor ``` This will build with four concurrent build processes to take advantage of more cores on your workstation. ## Checking Result <a name="Checking_Result"></a> Please check results on both the iothub and device side: - iothub: log into iothub-explorer, and monitor events with command `iothub-explorer monitor-events yourdevice --login 'yourprimarykey'` - ESP device: monitor events with command `make monitor` ESP device would send data to the Azure cloud, and then you would be able to receive data at the iothub side. ## Troubleshooting <a name="Troubleshooting"></a> 1. Some common problems can be fixed by disabling the firewall. 2. You can try with the followings, if your build fails: - git submodule init - git submodule update - export your compiler path - export your IDF path - get start from [Here](https://www.espressif.com/en/support/download/documents) 3. Make sure the device connection string you are using, which you get from Azure IoT Hub, is correct. <file_sep>/esp-azure/doc/IoT_Suite.md ## Applying an Azure Trail Account 1. Go to [Azure IoT Suite](https://www.azure.cn/en-us/home/features/iot-suite/) and click on 1RMB Trail. ![](_static/IoT_Suite.png) 2. Enter you phone number and complete the verification process. ![](_static/phone_number.png) 3. Enter basic information and complete the real name authentication. ![](_static/basic_information.png) 4. Register ![](_static/about_you.png) 5. Pay 1 RMB to complete the register ![](_static/purchase.png) ## Obtaining Connection String 1. Go to [Azure IoT Portal](https://portal.azure.cn). ![](_static/portal.png) 2. Click on "All services", and choose "IoT Hub". ![](_static/all_service.png) 3. Create a new IoT hub. ![](_static/new_iot_hub.png) 4. Name your new hub. ![](_static/name_iot_hub.png) 5. Obtain your connection string as instructed in the figure below: ![](_static/connection_string.png)
f034e209d74d909618a64c15addb6d223c26c121
[ "Markdown", "C" ]
4
C
obastemur/esp32s
3ad413b90f6d0cdb8413fa99a6cfa16bb2f1fce6
e5158fe34b583f94697457a9746c16d77635b1fb
refs/heads/master
<repo_name>weilking/Wifi_PM_Test1<file_sep>/Wifi_PM_Test1.ino #include <Wire.h> #include <LiquidCrystal_I2C.h> #define Device_yeelink 2321 #define Sensor_PM1_yeelink 3213 #define Sensor_PM25_yeelink 3248 #define API_Key_yeelink "<KEY>" int pin = 10; unsigned long duration; unsigned long duration2; unsigned long starttime; unsigned long sampletime_ms = 30000; unsigned long lowpulseoccupancy = 0; unsigned long lowpulseoccupancy2 = 0; float ratio = 0; float concentration = 0; float ratio2 = 0; float concentration2 = 0; int flag1 = 0; float average_con = 0.0; float average_con2 = 0.0; float con[120]; float con2[120]; int flag = -119; int flag2 = -119; float sum=0.0; float sum2=0.0; int temp = 0; LiquidCrystal_I2C lcd(0x20,16,2); // set the LCD address to 0x20 for a 16 chars and 2 line display void setup() { Serial.begin(57600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } pinMode(10,INPUT); pinMode(7,INPUT); starttime = millis(); //Initialize LCD lcd.init(); lcd.setCursor(0,1); lcd.print("PM1.0: , POOR"); } void loop() { duration = pulseIn(10, LOW); duration2 = pulseIn(7, LOW); lowpulseoccupancy = lowpulseoccupancy+duration; lowpulseoccupancy2 = lowpulseoccupancy2+duration2; if ((millis()-starttime) > sampletime_ms) { ratio = lowpulseoccupancy/(sampletime_ms*10.0); // Integer percentage 0=>100 concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62; // using spec sheet curve ratio2 = lowpulseoccupancy2/(sampletime_ms*10.0); // Integer percentage 0=>100 concentration2 = 1.1*pow(ratio2,3)-3.8*pow(ratio2,2)+520*ratio2+0.62; // using spec sheet curve average_con = low_pass_average_hour(con, &flag, concentration, &sum); average_con2 = low_pass_average_hour(con2, &flag2, concentration2, &sum2); lowpulseoccupancy = 0; lowpulseoccupancy2 = 0; wifi_update_yeelink(average_con,Device_yeelink,Sensor_PM1_yeelink,API_Key_yeelink); LCD_Print(average_con); starttime = millis(); while((millis()-starttime) < 6000) { temp++; } temp = 0; wifi_update_yeelink(average_con2,Device_yeelink,Sensor_PM25_yeelink,API_Key_yeelink); starttime = millis(); } } float low_pass_average_hour(float* con, int* flag, float concentration,float* sum) { float average = 0.0; if( (*flag) < 0) { con[119+(*flag)] = concentration; (*sum) = (*sum) + concentration; (*flag) += 1; average = (*sum)/((*flag)+119); return average; } else { *sum = *sum - con[(*flag)]; con[(*flag)] = concentration; *sum = *sum + concentration; *flag = *flag + 1; if(*flag > 119) { (*flag) = 0; } average = (*sum)/120; return average; } } void wifi_update_yeelink(float concentration,int device,int sensor,char* api_key) { Serial.print("POST /v1.0/device/"); Serial.print(device); Serial.print("/sensor/"); Serial.print(sensor); Serial.print("/datapoints"); Serial.println(" HTTP/1.1"); Serial.println("Host: api.yeelink.net"); Serial.print("Accept: *"); Serial.print("/"); Serial.println("*"); Serial.print("U-ApiKey: "); Serial.println(API_Key_yeelink); Serial.print("Content-Length: "); // calculate the length of the sensor reading in bytes: // 8 bytes for {"value":} + number of digits of the data: int thisLength = 10 + getLength(concentration); Serial.println(thisLength); Serial.println("Content-Type: application/x-www-form-urlencoded"); Serial.println("Connection: close"); Serial.println(); // here's the actual content of the PUT request: Serial.print("{\"value\":"); Serial.print(concentration); Serial.println("}"); } int getLength(float num) { int i=0; num = num*100; while(num>=10) { num/=10; i++; } i=i+2; return i; } void LCD_Print(float PM) { lcd.setCursor(6,1); if(PM<1000) { lcd.print(" "); if(PM<100) { lcd.print(" "); if(PM<10) { lcd.print(" "); } } } lcd.print((int)PM); lcd.setCursor(11,1); if(PM>0 && PM<75) { lcd.print("VGood"); lcd.noBacklight(); } else if(PM<150) { lcd.print(" Good"); lcd.noBacklight(); } else if(PM<300) { lcd.print(" OK"); lcd.noBacklight(); } else if(PM<1050) { lcd.print(" Poor"); lcd.noBacklight(); } else { lcd.print("VPoor"); lcd.backlight(); } }
cce66e9bc5544e665aae2b9037c5e9a02b10e40e
[ "C++" ]
1
C++
weilking/Wifi_PM_Test1
11848b2561edab5850f7392956789aa6dd84da78
3cd2020724670811adf38d36e8678b591df7bfcc
refs/heads/main
<repo_name>UTH-maureenBarahona/reforzamientoW1<file_sep>/js/funciones.js var names = document.getElementsByName("name[]"); //Solo permite introducir numeros. function soloNumeros(e) { try { var key = window.event ? e.which : e.keyCode; if (key < 48 || key > 57) { e.preventDefault(); } } catch (error) { document.getElementById("error").innerHTML = err.message; } } function limpiarFormulario() { try { document.getElementById("rellenar").reset(); } catch (error) { document.getElementById("error").innerHTML = err.message; } } function imprimir() { try { window.print(); } catch (error) { document.getElementById("error").innerHTML = err.message; } } function calcularEdad() { try { var fecha = document.getElementById("fNacimiento").value; console.log(fecha); var hoy = new Date(); var cumpleanos = new Date(fecha); var edad = hoy.getFullYear() - cumpleanos.getFullYear(); var m = hoy.getMonth() - cumpleanos.getMonth(); if (m < 0 || (m === 0 && hoy.getDate() < cumpleanos.getDate())) { edad--; } document.rellenar.edad.value = edad; return edad; } catch (error) { document.getElementById("error").innerHTML = error.message; } } function validateDecimal(valor) { try { var RE = /^\d*(\.\d{1})?\d{0,1}$/; if (RE.test(valor)) { return true; } else { return false; } } catch (error) { document.getElementById("error").innerHTML = error.message; } } function concatenarNombres() { try { var PNombre = document.getElementById("pNombre"); var SNombre = document.getElementById("sNombre"); var Apellido = document.getElementById("apellidos"); var completo = PNombre.value + " " + SNombre.value + " " + Apellido.value; document.rellenar.nCompleto.value = completo; } catch (error) { document.getElementById("error").innerHTML = error.message; } } function calculos() { /*Deducciones por ahorro (10% del sueldo base). iii. Bonificación (15% sueldo base). iv. Bono navideño (si es administrativo es de L. 250.00, si es conductor es de L. 300.00). Seguro privado (3.5% de (sueldo base – deducciones por ahorro)). vi. Seguro social (4% del sueldo base). vii. Sueldo Neto (sueldo base – deducciones por ahorro – seguros + bonificación). */ try { var SBase = document.getElementById("sBase"); var DAhorro = Math.floor(SBase.value * 10) / 100; document.rellenar.dAhorro.value = DAhorro; var Bonificacion = Math.floor(SBase.value * 15) / 100; document.rellenar.bonificacion.value = Bonificacion; var Puesto = document.getElementById("puesto"); var ValBonoNav; if (Puesto.value == 1) { ValBonoNav = 250; } else { ValBonoNav = 300; } document.rellenar.bNavidad.value = ValBonoNav; //seguro privado var SPrivado = SBase.value - DAhorro; var ValSeguroPrivado = Math.floor(SPrivado * 3.5) / 100; document.rellenar.sPrivado.value = ValSeguroPrivado; //Seguro Social var SSocial = Math.floor(SBase.value * 4) / 100; document.rellenar.sSocial.value = SSocial; var SueldoNeto = SBase.value - DAhorro - (ValSeguroPrivado + SSocial) + (Bonificacion + ValBonoNav); document.rellenar.sNeto.value = SueldoNeto; } catch (error) { document.getElementById("error").innerHTML = error.message; } } function validateEmpty() { var t = document.getElementById("numId"); t.addEventListener("input", function(){ t.style.backgroundColor = t.value === "" ? "#f00" : "#0f0"; }); } function InsertIntoTable() { try { var TableRow = "<tr></tr>"; for (key = 0; key < names.length; key++) TableRow = TableRow.substring(0, TableRow.length - 5) + "<td>" + names[key].value + "</td>" + TableRow.substring(TableRow.length - 5); var TrElement = document.createElement("tr"); TrElement.innerHTML = TableRow; document.getElementById("TableBody").appendChild(TrElement); } catch (error) { document.getElementById("error").innerHTML = error.message; } } function almacenar() { calcularEdad(); concatenarNombres(); calculos(); InsertIntoTable(); }
aabb7c569e6ffc7f3d158c9d83173143ce1be812
[ "JavaScript" ]
1
JavaScript
UTH-maureenBarahona/reforzamientoW1
7e7bddd2c9a603a6563f04a2e4a3b84af94c1d2c
5b19cd70448bebef66073c1913df465d79a43c42
refs/heads/master
<repo_name>Raj0697/Java-<file_sep>/displayy.java public class displayy { public static void main(String[] args) { System.out.println("Enter your name: <NAME>"); System.out.println("Enter your dob: 16.06.1997"); System.out.println("Enter your mobile number: 987642822"); } } <file_sep>/boxdemo.java class boxdemo { public double width,height,depth; boxdemo(int a,int b,int c) { width=a; height=b; depth=c; } double volume() { return(width*height*depth); } public static void main(String args[]) { boxdemo mybox1 = new boxdemo(1,2,3); boxdemo mybox2 = new boxdemo(5,6,7); //compute volume of 1st box System.out.println("volume is" + mybox1.volume()); //compute volume of 2nd box System.out.println("volume is" + mybox2.volume()); } } <file_sep>/README.md # Java Problemsheet This project contains basic, moderate and advanced problems and oops problems. <file_sep>/MemberInner2.java class MemberInn { class Inner { void msg() { System.out.println("Inside Member Inner class's method"); } } } class MemberInner2 { public static void main(String args[]) { MemberInn outObj=new MemberInn(); MemberInn.Inner inObj=outObj.new Inner(); inObj.msg(); } } <file_sep>/statica.java public class statica { static int x; static int a; static void printa() { System.out.println(a); System.out.println(x); } public static void main(String[] args) { a=10; printa(); } } <file_sep>/Thread5.java //Java code for thread creation by implementing the Runnable interface class MyThreadR implements Runnable { public void run() { try {// Displaying the thread that is running System.out.println("Thread "+Thread.currentThread().getId()+" is running"); } catch (Exception e) {// Throwing an exception System.out.println ("Exception is caught"); } } } //Main Class public class Thread5 {public static void main(String[] args) { int n = 5; // Number of threads for (int i=0; i<n; i++) { MyThreadR mtr = new MyThreadR(); Thread t1 = new Thread(mtr); t1.start(); } } } <file_sep>/currencyconversion.java import java.util.Scanner; public class currencyconversion { public static void main(String args[]) { System.out.print("Enter the amount in dollars : "); Scanner r = new Scanner(System.in); int dollars = r.nextInt(); int rupees = 63 * dollars; System.out.println("Amount in dollars : " + dollars); System.out.println("Amount in rupees : " + rupees); r.close(); } } <file_sep>/dicountcalculator.java import java.util.Scanner; public class dicountcalculator { public static void main(String args[]) { double amt,dis=0,net; System.out.println(" DISCOUNT CALCULATOR "); Scanner my = new Scanner (System.in); System.out.println("Enter the amount : "); amt = my.nextInt(); System.out.println("The Discount is : "); if(amt>=501 && amt<=1000) { dis=0.05*amt; } else if(amt>=1001 && amt<=5000) { dis=0.1*amt; } else if(amt>=5001 && amt<=10000) { dis=0.12*amt; } else if(amt>10000) { dis=0.15*amt; } else if(amt<500) { dis=0; } net=amt-dis; System.out.println(dis); System.out.println("The net amount is : " + net); my.close(); } } <file_sep>/inheritance.java import java.util.Scanner; class book { String bookname; String authorname; String publication; int publicationyear; int price; Scanner s=new Scanner(System.in); void accept() { System.out.println("Enter the book name : "); bookname=s.next(); System.out.println("Enter the author name : "); authorname=s.next(); System.out.println("Enter the publication name : "); publication=s.next(); System.out.println("Enter the publication year : "); publicationyear=s.nextInt(); System.out.println("Enter the price : "); price=s.nextInt(); } void display() { System.out.println("The book name is " +bookname); System.out.println("The author name is " +authorname); System.out.println("The publication name is " +publication); System.out.println("The publication year is " +publicationyear); System.out.println("The price is " +price); } } class library_book extends book { int bookcode; String availability; int totalbooks; void accept() { super.accept(); System.out.println("Enter the book code : "); bookcode=s.nextInt(); System.out.println("Enter the availability of the book : "); availability=s.next(); System.out.println("Enter the total books : "); totalbooks=s.nextInt(); } void display() { super.display(); System.out.println("The book code is : "+bookcode); System.out.println("The availability of the book is : "+availability); System.out.println("The total books is :"+totalbooks); } String issuebook() { String a; System.out.println("Enter the issue date : "); a=s.next(); totalbooks -=1; return a; } String returnbook() { String b; System.out.println("Enter the return date : "); b=s.next(); totalbooks +=1; return b; } String checkavailability() { System.out.println("Current availability of the book : "+totalbooks); return availability; } } class test { public static void main(String args[]) { book bk; book b = new book(); library_book lb = new library_book(); bk = b; bk.accept(); bk.display(); bk=lb; lb.accept(); lb.display(); lb.issuebook(); lb.checkavailability(); lb.returnbook(); lb.checkavailability(); } } <file_sep>/methodoverloading.java import java.util.Scanner; public class methodoverloading { static int add(int a,int b) { return(a+b); } static double add(double a,double b) { return(a+b); } static int add(int a,int b,int c) { return(a+b+c); } public static void main(String args[]) { int a,b,c,e; double p,q,r; Scanner s=new Scanner(System.in); System.out.println("Enter a value"); a=s.nextInt(); System.out.println("Enter b value"); b=s.nextInt(); c=(int)add(a,b); System.out.println("ADDITION="+c); System.out.println("Enter p value"); p=s.nextDouble(); System.out.println("Enter q value"); q=s.nextDouble(); r=(double)add(p,q); System.out.println("ADDITION="+r); System.out.println("Enter the a value"); a=s.nextInt(); System.out.println("Enter the b value"); b=s.nextInt(); System.out.println("Enter the c value"); c=s.nextInt(); e=(int)add(a,b,c); System.out.println("ADDITION="+e); s.close(); } } <file_sep>/vehicle.java import java.util.Scanner; public interface vehicle { void passenger(); void engine(); void weight(); void wheel(); Scanner s = new Scanner(System.in); } class car implements vehicle { public void passenger() { System.out.println("Enter the no of passenger : "); int a=s.nextInt(); System.out.println("The no of passenger is : "+a); } public void engine() { System.out.println("Enter the engine name : "); String a=s.next(); System.out.println("The engine name is : "+a); } public void weight() { System.out.println("Enter the weight of car : "); int a=s.nextInt(); System.out.println("The weight of the car is : "+a+"kg"); } public void wheel() { System.out.println("Enter the no of wheels : "); int a=s.nextInt(); System.out.println("The no of wheels is : "+a); } } class auto implements vehicle { public void passenger() { System.out.println("Enter the no of passenger : "); int a=s.nextInt(); System.out.println("The no of passenger is : "+a); } public void engine() { System.out.println("Enter the engine name : "); String a=s.next(); System.out.println("The engine name is : "+a); } public void weight() { System.out.println("Enter the weight of auto : "); int a=s.nextInt(); System.out.println("The weight of the auto is : "+a+"kg"); } public void wheel() { System.out.println("Enter the no of wheels : "); int a=s.nextInt(); System.out.println("The no of wheels is : "+a); } } class cycle implements vehicle { public void passenger() { System.out.println("Enter the no of passenger : "); int a=s.nextInt(); System.out.println("The no of passenger is : "+a); } public void engine() { System.out.println("Enter the engine name : "); String a=s.next(); System.out.println("The engine name is : "+a); } public void weight() { System.out.println("Enter the weight of cycle : "); int a=s.nextInt(); System.out.println("The weight of the cycle is : "+a+"kg"); } public void wheel() { System.out.println("Enter the no of wheels : "); int a=s.nextInt(); System.out.println("The no of wheels is : "+a); } } class ship implements vehicle { public void passenger() { System.out.println("Enter the no of passenger : "); int a=s.nextInt(); System.out.println("The no of passenger is : "+a); } public void engine() { System.out.println("Enter the engine name : "); String a=s.next(); System.out.println("The engine name is : "+a); } public void weight() { System.out.println("Enter the weight of ship : "); int a=s.nextInt(); System.out.println("The weight of the ship is : "+a+"kg"); } public void wheel() { System.out.println("Enter the no of wheels : "); int a=s.nextInt(); System.out.println("The no of wheels is : "+a); } } class test3 { public static void main(String args[]) { System.out.println("\n---------INTERFACE----------\n"); System.out.println("\n--------------CAR DETAILS-------------\n"); car c=new car(); c.passenger(); c.engine(); c.weight(); c.wheel(); System.out.println("\n----------------AUTO DETAILS-------------\n"); auto a=new auto(); a.passenger(); a.engine(); a.weight(); a.wheel(); System.out.println("\n------------CYCLE DETAILS-------------\n"); cycle b=new cycle(); b.passenger(); b.engine(); b.weight(); b.wheel(); System.out.println("\n------------SHIP DETAILS------------"); ship d=new ship(); d.passenger(); d.engine(); d.weight(); d.wheel(); } } <file_sep>/Thread9.java //example of java synchronized method class Operations { synchronized void printSync(int n) {//synchronized method. When one thread is using it another cannot use it for(int i=1;i<=5;i++) { System.out.println("Printing Multiplications "+n*i); try{Thread.sleep(400);}catch(Exception e){System.out.println(e);} } } void printNonSync(int n) { for(int i = n; i<=n*n; i = i+2) { System.out.println("Printing numbers "+i); try {Thread.sleep(100);} catch(Exception e) {System.out.println(e);} } } } class MyThread10 extends Thread { Operations t; // Resource to be used for this thread MyThread10(Operations t){this.t=t;} public void run() { t.printSync(4); t.printNonSync(3); t.printSync(2); } } class MyThread11 extends Thread { Operations t; // Resource to be used for this thread MyThread11(Operations t) { this.t=t; } public void run() { t.printSync(7); t.printNonSync(6); t.printSync(5); } } public class Thread9 { public static void main(String args[]) { Operations opr = new Operations(); // This object is used for both the threads MyThread10 th1 = new MyThread10(opr); MyThread11 th2 = new MyThread11(opr); th1.start(); th2.start(); } } /* One Possible Output: Printing Multiplications 4 Printing Multiplications 8 Printing Multiplications 12 Printing Multiplications 16 Printing Multiplications 20 Printing Multiplications 7 Printing numbers 3 Printing numbers 5 Printing numbers 7 Printing numbers 9 Printing Multiplications 14 Printing Multiplications 21 Printing Multiplications 28 Printing Multiplications 35 Printing Multiplications 2 Printing numbers 6 Printing numbers 8 Printing numbers 10 Printing numbers 12 Printing Multiplications 4 Printing numbers 14 Printing numbers 16 Printing numbers 18 Printing numbers 20 Printing Multiplications 6 Printing numbers 22 Printing numbers 24 Printing numbers 26 Printing numbers 28 Printing Multiplications 8 Printing numbers 30 Printing numbers 32 Printing numbers 34 Printing Multiplications 10 Printing numbers 36 Printing Multiplications 5 Printing Multiplications 10 Printing Multiplications 15 Printing Multiplications 20 Printing Multiplications 25 */<file_sep>/Thread3.java class MyThread4 extends Thread { public void run() { try { for(int i = 1; i<200; i=i+2) {System.out.println("MyThread4 "+i+" is ODD"); Thread.sleep(100); } } catch (Exception e) { System.out.println ("Exception is caught"); } } } class MyThread5 extends Thread { public void run() { try { for(int i = 0; i<1000; i=i+10) System.out.println("MyThread5 "+i+" is Divisible by 10"); //Thread.sleep(100); } catch (Exception e) { System.out.println ("Exception is caught"); } } } //Main Class public class Thread3 {public static void main(String[] args) { MyThread4 th1 = new MyThread4(); MyThread5 th2 = new MyThread5(); th1.start(); th2.start(); } } <file_sep>/sam.java public class sam { public double width,height,depth; sam(int a,int b,int c) { width=a; height=b; depth=c; } double volume() { return(width*height*depth); } public static void main(String args[]) { sam mybox1 = new sam(10,20,30); sam mybox2 = new sam(50,60,70); System.out.println("volume is " + mybox1.volume()); System.out.println("volume is " + mybox2.volume()); } } <file_sep>/program.java import java.util.Scanner; class book { String bookname; String authorname; String publication; int publicationyear; int price; Scanner s=new Scanner(System.in); void accept() { System.out.println("Enter the book name : "); bookname=s.next(); System.out.println("Enter the author name : "); authorname=s.next(); System.out.println("Enter the publication name : "); publication=s.next(); System.out.println("Enter the publication year : "); publicationyear=s.nextInt(); System.out.println("Enter the price : "); price=s.nextInt(); } void display() { System.out.println("\nThe book name is : " +bookname); System.out.println("\nThe author name is : " +authorname); System.out.println("\nThe publication name is : " +publication); System.out.println("\nThe publication year is : " +publicationyear); System.out.println("\nThe price is : " +price); } } class library_book extends book { int bookcode; String availability; int totalbooks; void accept() { super.accept(); System.out.println("Enter the book code : "); bookcode=s.nextInt(); System.out.println("Enter the availability of the book : "); availability=s.next(); System.out.println("Enter the total books : "); totalbooks=s.nextInt(); } void display() { super.display(); System.out.println("\nThe book code is : "+bookcode); System.out.println("\nThe availability of the book is : "+availability); System.out.println("\nThe total books is : "+totalbooks); } void issuebook() { { System.out.println("Enter the issue date : "); s.next(); totalbooks -=1; } } void returnbook() { { System.out.println("Enter the return date : "); s.next(); totalbooks +=1; } } void checkavailability() { System.out.println("Current availability of the book : "+totalbooks); } } class test { public static void main(String args[]) { book bk; book b = new book(); library_book lb = new library_book(); System.out.println("\n---------------------BOOK--------------------\n"); bk = b; bk.accept(); bk.display(); System.out.println("\n---------------LIBRARY BOOKS-------------\n"); bk=lb; lb.accept(); lb.display(); lb.issuebook(); lb.checkavailability(); lb.returnbook(); lb.checkavailability(); } } <file_sep>/exception.java public class exception { public static void main(String args[]) throws ArithmeticException { int a,b,c; a=10;b=0; try { if(b==0)throw new ArithmeticException("divide by zero"); else c=a/b; } catch(ArithmeticException e) { System.out.println("e"); System.out.println(((Object) e).set message()); throw e; } System.out.println("End of program"); } } <file_sep>/even.java public class even { public static void main(String[] args) { int i=5; if(i%2==0) System.out.println("i is even"); else System.out.println("i is odd"); } } <file_sep>/program15.java import java.util.Scanner; class person { Scanner s=new Scanner(System.in); String name; int age=0; void accept() { System.out.println("Enter the name: "); name = s.next(); System.out.println("Enter the age: "); age = s.nextInt(); } void display() { System.out.println("The name is"+name); System.out.println("The age is"+age); } void helloname() { System.out.println("Hello,"+name+"! Have a nice day"); } } class student extends person { int rollno; int[] marks=new int[6]; int totalmarks=0; void accept() { super.accept(); System.out.println("Enter the name: "); name=s.next(); System.out.println("Enter the rollno: "); rollno=s.nextInt(); System.out.println("Enter the mark: "); for(int i=0;i<6;i++) { System.out.println("Enter the mark"+(i+1)); marks[i]=s.nextInt(); } System.out.println("Enter totalmarks: "); for(int i=0;i<6;i++) { totalmarks=totalmarks+marks[i]; } System.out.println(totalmarks); } void display() { super.display(); System.out.println("The name is"+name); System.out.println("The rollno is"+rollno); System.out.println("The mark is"); for(int i=0;i<6;i++) { System.out.println("The mark "+(i+1)+ " is "+marks[i]); } System.out.println("The totalmark is"+totalmarks); } } class employee extends person { int empId; String designation; String organizationname; int salary; void accept() { super.accept(); System.out.println("Enter the empId: "); empId=s.nextInt(); System.out.println("Enter the designaton: "); designation=s.next(); System.out.println("Enter the organizatonname: "); organizationname=s.next(); System.out.println("Enter the salary: "); salary=s.nextInt(); } void display() { super.display(); System.out.println("The empId is"+empId); System.out.println("The designation is"+designation); System.out.println("The organization name is"+organizationname); System.out.println("The salary is"+salary); } } class worker extends person { String companyname; int dailywagesrate; int noofdaysworked; int salary; void accept() { super.accept(); System.out.println("Enter the companyname: "); companyname=s.next(); System.out.println("Enter the dailywagesrate: "); dailywagesrate=s.nextInt(); System.out.println("Enter the noofdaysworked: "); noofdaysworked=s.nextInt(); System.out.println("Enter the salary: "); salary=s.nextInt(); } void display() { super.display(); System.out.println("The company name is"+companyname); System.out.println("The daily wages rate is"+dailywagesrate); System.out.println("The no of days worked is"+noofdaysworked); System.out.println("The salary is"+salary); } } class PGstudent extends student { String coursename; int percentageofmarks; void accept() { super.accept(); System.out.println("Enter the coursename: "); coursename=s.next(); System.out.println("Enter the percentageofmarks: "); percentageofmarks=s.nextInt(); } void display() { super.display(); System.out.println("The course name is"+coursename); System.out.println("The percentage of marks is"+percentageofmarks); } } class manager extends employee { int noofworkers; void accept() { super.accept(); System.out.println("Enter the noofworkers: "); noofworkers=s.nextInt(); } void display() { super.display(); System.out.println("The no of workers is"+noofworkers); } } class seniorworker extends worker { int yearsofexperience; void accept() { super.accept(); System.out.println("Enter the years of experience: "); yearsofexperience=s.nextInt(); } void display() { System.out.println("The years of experience is"+yearsofexperience); } } class program15 { public static void main(String args[]) { person pr; person p1=new person(); student s1=new student(); employee e1=new employee(); worker w1=new worker(); PGstudent PG1=new PGstudent(); manager m1=new manager(); seniorworker sw1=new seniorworker(); pr=p1; pr.accept(); pr.display(); pr=s1; pr.accept(); pr.display(); pr=e1; pr.accept(); pr.display(); pr=w1; pr.accept(); pr.display(); pr=PG1; pr.accept(); pr.display(); pr=m1; pr.accept(); pr.display(); pr=sw1; pr.accept(); pr.display(); } } <file_sep>/add.java public class add { static int add(int x,int y) { return(x+y); } public static void main(String[] args) { int i=5,j=6; System.out.println(add(i,j)); } } <file_sep>/objects.java public class objects { int a;static int count=0; A(){a=10;count++;} A(int a){this.a=a;count++;} A add(A ap) { A ad=new A(); } public static void main(String args[]) { A a1=new A(); A a2=new A(2); A a3=new A(); a3=a1.add(a2); System.out.println("Total no of objects created"+A.count); B b1=new B(); System.out.println("Total no of objects created"+(A.count + B.count)); } } <file_sep>/Thread2.java class MyThread2 extends Thread { public void run() { System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getId()); for(int i = 1; i<20; i=i+2) System.out.println("MyThread2 "+i+" is ODD"); } } class MyThread3 extends Thread { public void run() { System.out.println(Thread.currentThread().getName()); System.out.println(Thread.currentThread().getId()); for(int i = 0; i<100; i=i+10) System.out.println("MyThread3 "+i+" is Divisible by 10"); } } public class Thread2 {public static void main(String[] args) { MyThread2 th1 = new MyThread2(); MyThread3 th2 = new MyThread3(); System.out.println("Sending run messages to threads"); th1.run(); th2.run(); System.out.println("\n\nSending start messages to threads"); th1.start(); th2.start(); } } <file_sep>/MemberInner4.java class MemberInner4 { private int data=30; class Inner { void msg() { System.out.println("data is "+data); } } public static void main(String args[]) { MemberInner obj=new MemberInner(); MemberInner.Inner in=obj.new Inner(); in.msg(); } }
5602d1ed13b036b01b1bb7d65965b926e68316a2
[ "Markdown", "Java" ]
22
Java
Raj0697/Java-
b113690dd49b276a403487411d9ce721c4371ad0
9486a062b483be9fa8fd64bb5b5913f6fbd60a15
refs/heads/main
<repo_name>edzer/trajectories<file_sep>/tests/tracks.R Sys.setenv(TZ = "Europe/Berlin") # Load required libraries. library(sp) library(spacetime) library(trajectories) # Create test objects. Do not change! Changes to the test objects are likely to # have an impact on the test results. It is primarily validated against class # and dimension. However, the test functions check for the first dimension only, # since, in the majority of cases, a deviation of the second is not necessarily # associated with a regression. # t0 = as.POSIXct(as.Date("2013-09-30", tz = "CET")) t0 = as.POSIXct("2013-09-30 02:00:00", tz = "Europe/Berlin") set.seed(13531) # make sure rbind generates identical sequences on reproduction # Person A, track 1. x = c(7, 6, 5, 5, 4, 3, 3) y = c(7, 7, 6, 5, 5, 6, 7) n = length(x) t = t0 + cumsum(runif(n) * 60) crs = CRS("+proj=longlat +datum=WGS84") stidf = STIDF(SpatialPoints(cbind(x, y), crs), t, data.frame(co2 = rnorm(n))) A1 = Track(stidf) # Person A, track 2. x = c(7, 6, 6, 7, 7) y = c(6, 5, 4, 4, 3) n = length(x) t = max(t) + cumsum(runif(n) * 60) stidf = STIDF(SpatialPoints(cbind(x, y), crs), t, data.frame(co2 = rnorm(n))) A2 = Track(stidf) # Tracks for person A. A = Tracks(list(A1 = A1, A2 = A2)) # Person B, track 1. x = c(2, 2, 1, 1, 2, 3) y = c(5, 4, 3, 2, 2, 3) n = length(x) t = max(t) + cumsum(runif(n) * 60) stidf = STIDF(SpatialPoints(cbind(x, y), crs), t, data.frame(co2 = rnorm(n))) B1 = Track(stidf) # Person B, track 2. x = c(3, 3, 4, 3, 3, 4) y = c(5, 4, 3, 2, 1, 1) n = length(x) t = max(t) + cumsum(runif(n) * 60) stidf = STIDF(SpatialPoints(cbind(x, y), crs), t, data.frame(co2 = rnorm(n))) B2 = Track(stidf) # Tracks for person B. B = Tracks(list(B1 = B1, B2 = B2)) # Tracks collection. Tr = TracksCollection(list(A = A, B = B)) all = list(A1, A2, B1, B2, A, B, Tr) # Test methods. checkClass = function(list, class) { stopifnot(all(sapply(list, function(x) class(x)[1] == class))) } checkDim = function(list, dim) { for(i in seq_along(list)) { element = list[[i]] if(class(element)[1] %in% c("data.frame", "xts", "STIDF", "SpatialPointsDataFrame")) stopifnot(dim(element)[1] == dim[i]) else if(class(element)[1] == "Line") stopifnot(dim(element@coords)[1] == dim[i]) else if(class(element)[1] == "Lines") # For simplification purposes, the number of Line elements (= number # of Tracks) is validated. stopifnot(length(element@Lines) == dim[i]) else if(class(element)[1] %in% c("SpatialLines", "SpatialLinesDataFrame")) # For simplification purposes, the sum of the number of Line # elements (= total number of Tracks) is validated. stopifnot(sum(sapply(element@lines, function(x) length(x@Lines))) == dim[i]) else warning(paste("Validation against dimension of class '", class(element)[1], "' is not yet supported.", sep = "")) } } # Check coercion to segments. res = lapply(all, function(x) as(x, "segments")) checkClass(res, "data.frame") dim = c(6, 4, 5, 5, 10, 10, 20) checkDim(res, dim) # Check coercion to data frame. res = lapply(all, function(x) as(x, "data.frame")) checkClass(res, "data.frame") dim = c(7, 5, 6, 6, 14, 14, 28) checkDim(res, dim) # Check coercion to Line, Lines, SpatialLines and SpatialLinesDataFrame. res = lapply(all[1:4], function(x) as(x, "Line")) checkClass(res, "Line") dim = c(7, 5, 6, 6) checkDim(res, dim) res = lapply(all[1:6], function(x) as(x, "Lines")) checkClass(res, "Lines") dim = c(1, 1, 1, 1, 2, 2) checkDim(res, dim) res = lapply(all, function(x) as(x, "SpatialLines")) checkClass(res, "SpatialLines") dim = c(1, 1, 1, 1, 2, 2, 4) checkDim(res, dim) res = lapply(all[5:length(all)], function(x) as(x, "SpatialLinesDataFrame")) checkClass(res, "SpatialLinesDataFrame") dim = c(2, 2, 4) checkDim(res, dim) # Check coercion to xts. res = lapply(all, function(x) as(x, "xts")) checkClass(res, "xts") dim = c(7, 5, 6, 6, 12, 12, 24) checkDim(res, dim) # Check coercion to STIDF. res = lapply(all, function(x) as(x, "STIDF")) checkClass(res, "STIDF") dim = c(7, 5, 6, 6, 12, 12, 24) checkDim(res, dim) # Check coercion to SpatialPointsDataFrame. res = lapply(all, function(x) as(x, "SpatialPointsDataFrame")) checkClass(res, "SpatialPointsDataFrame") dim = c(7, 5, 6, 6, 12, 12, 24) checkDim(res, dim) # Check proj4string methods. # stopifnot(all(sapply(all, function(x) proj4string(x) == "+proj=longlat +ellps=WGS84"))) # Check coordnames methods. stopifnot(all(sapply(all, function(x) coordnames(x) == c("x", "y")))) # Check stbox methods. lapply(all, function(x) stbox(x)) # Check generalize methods. if (require(sf)) { lapply(all, function(x) generalize(x, max, timeInterval = "2 min")) lapply(all, function(x) generalize(x, distance = 200)) lapply(all, function(x) generalize(x, min, n = 2)) lapply(all, function(x) generalize(x, timeInterval = "3 min", tol = 2)) lapply(all, function(x) generalize(x, n = 3, toPoints = TRUE)) } # Check selection methods. stopifnot(class(Tr[1:2])[1] == "TracksCollection") stopifnot(class(Tr[2])[1] == "Tracks") stopifnot(class(Tr[2][1])[1] == "Track") stopifnot(class(Tr[list(1:2, 2:3)])[1] == "TracksCollection") stopifnot(class(Tr[list(integer(0), 2:3)])[1] == "Tracks") stopifnot(class(Tr[list(integer(0), 2)])[1] == "Track") stopifnot(class(Tr[list(1:2, 2:3), drop = FALSE])[1] == "TracksCollection") stopifnot(class(Tr[list(integer(0), 2:3), drop = FALSE])[1] == "TracksCollection") stopifnot(class(Tr[list(integer(0), 2), drop = FALSE])[1] == "TracksCollection") stopifnot(class(Tr[, "distance"]) == "TracksCollection") lapply(all, function(x) x[["co2"]]) lapply(all, function(x) x[["co2"]] = x[["co2"]] / 1000) lapply(all, function(x) x$distance) lapply(all, function(x) x$distance = x$distance * 1000) <file_sep>/man/print.TracksCollection.Rd \name{print.TracksCollection} \alias{print.TracksCollection} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "TracksCollection" } \description{ method to print an object of class "TracksCollection"} \usage{ \method{print}{TracksCollection}(x, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "TracksCollection" } \item{...}{ ignored } } \author{ <NAME> <<EMAIL>> } <file_sep>/man/rtrack.Rd \name{rTrack} \alias{rTrack} \alias{rTracks} \alias{rTracksCollection} \title{Generate random \code{Track}, \code{Tracks} or \code{TracksCollection} objects} \description{Generate random \code{Track}, \code{Tracks} or \code{TracksCollection} objects} \usage{ rTrack(n = 100, origin = c(0,0), start = as.POSIXct("1970-01-01"), ar = .8, step = 60, sd0 = 1, bbox = bbox, transform = FALSE, nrandom = FALSE, ...) rTracks(m = 20, start = as.POSIXct("1970-01-01"), delta = 7200, sd1 = 0, origin = c(0,0), ...) rTracksCollection(p = 10, sd2 = 0, ...) } \arguments{ \item{n}{number of points per Track} \item{origin}{numeric, length two, indicating the origin of the Track} \item{start}{POSIXct, indicating the start time of the Track} \item{ar}{numeric vector, indicating the amound of correlation in the Track} \item{step}{ numeric; time step(s) in seconds between Track fixes } \item{sd0}{standard deviation of the random steps in a Track} \item{sd1}{standard deviation of the consecutive Track origin values (using rnorm)} \item{sd2}{standard deviation of the consecutive Tracks origin values (using rnorm)} \item{bbox}{bbox object FIXME:fill in} \item{transform}{logical; FIXME:fill in } \item{nrandom}{logical; if \code{TRUE}, draw \code{n} from \code{rpois(n)}} \item{...}{rTrack: arguments passed on to \link{arima.sim}, rTracks: arguments passed on to rTrack; rTracksCollection: arguments passed on to rTracks} \item{m}{ number of Track objects to simulate} \item{delta}{ time difference between consecutive Track start times} \item{p}{ number of IDs with Tracks to generate} } \details{\code{ar} is passed on to \link{arima.sim} as \code{ar} element, and may contain multiple AR coefficients. The generated track is a \link{cumsum} over the simulated AR values, for each dimension. In case it has length 1 and value 0, random walk is created using \link{rnorm}. If bbox is given, the generated track will be transformed to bbox. If transform is TRUE and no bbox is given, it transforms the track to a unit box. If nrandom is TRUE, it generates a random number using \link{rpois} with parameter n as the number of locations per track.} \value{An object of class \code{Track}, \code{Tracks} or \code{TracksCollection}.} \author{ <NAME> <<EMAIL>>, <NAME> <<EMAIL>> } \examples{ x = rTrack() dim(x) plot(x) # x = rTracks(sd1 = 120) # dim(x) # plot(as(x, "SpatialLines"), col = 1:dim(x)[1], axes=TRUE) # x = rTracksCollection() # star # dim(x) # plot(x) x = rTracksCollection(sd2 = 200,p=4,m=10) plot(x, col=1:dim(x)[1]) } \keyword{random} <file_sep>/man/unique.Track.Rd \name{unique.Track} \alias{unique.Track} %- Also NEED an '\alias' for EACH other topic documented here. \title{ unique.Track } \description{ Removing duplicated points in a track} \usage{ \method{unique}{Track}(x,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "Track" } \item{...}{passed to arguments of unique} } \details{ This function removes duplicated points in an object of class "Track".} \value{ An object of class Track with no duplicated point.} \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{rTrack}, \link{rTracks}, \link{rTracksCollection}, \link{unique} } \examples{ x <- rTrack() unique(x) } <file_sep>/man/as.Track.Rd \name{as.Track} \alias{as.Track} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Converts data to an object of class "Track" } \description{ Function as.Track accepts converts x,y coordinates and thier corresponding time/date to an object of class Track. It can also accepts covariates for the corresponding locations, covariates must be a dataframe with some columns and length of each column is equal to length of x,y,t. } \usage{ as.Track(x,y,t,covariate) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ x coordinate. } \item{y}{ y coordinate. } \item{t}{ corresponding time and date of x,y. } \item{covariate}{ additional information. } } \details{ An object of class "Track" can be created by some geographical locations and corresponding time/dates. Function as.Track converts locations and dates/times to an object of class "Track". time/date should be from class "POSIXct" "POSIXt". See example below. } \value{ An object of class "Track".} \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{Track}, \link{as.POSIXct} } \examples{ x <- runif(10,0,1) y <- runif(10,0,1) date <- seq(as.POSIXct("2015-1-1 0:00"), as.POSIXct("2015-1-1 9:00"), by = "hour") Z <- as.Track(x,y,date) plot(Z) } <file_sep>/man/generalize.Rd \name{generalize} \alias{generalize} \alias{generalize,Track-method} \alias{generalize,Tracks-method} \alias{generalize,TracksCollection-method} \title{Generalize objects of class \code{Track}, \code{Tracks} and \code{TracksCollection}} \description{Generalize objects of class \code{Track}, \code{Tracks} and \code{TracksCollection}.} \usage{% \S4method{generalize}{Track}(t, FUN = mean, ..., timeInterval, distance, n, tol, toPoints) \S4method{generalize}{Tracks}(t, FUN = mean, ...) \S4method{generalize}{TracksCollection}(t, FUN = mean, ...)} \arguments{ \item{t}{An object of class \code{Track}, \code{Tracks} or \code{TracksCollection}.} \item{FUN}{The generalization method to be applied. Defaults to \code{mean} if none is passed.} \item{timeInterval}{ (lower limit) time interval to split Track into segments } \item{distance}{ (lower limit) distance to split Track into segments } \item{n}{ number of points to form segments } \item{tol}{ tolerance passed on to \link[sf:geos_unary]{st_simplify}, to generalize segments using the Douglas-Peucker algorithm. } \item{toPoints}{ keep mid point rather than forming \link{SpatialLines} segments } \item{...}{Additional arguments passed to FUN} } \value{An object of class \code{Track}, \code{Tracks} or \code{TracksCollection}.} \keyword{generalize} <file_sep>/man/compare.Rd \name{compare} \docType{methods} \alias{compare} \alias{compare,Track-method} \title{Compares objects of class \code{Track}} \description{ Calculates distances between two tracks for the overlapping time interval. } \usage{% \S4method{compare}{Track}(tr1, tr2) } \arguments{ \item{tr1}{An object of class \code{Track}.} \item{tr2}{An object of class \code{Track}.} } \value{A difftrack object. Includes both tracks extended with additional points for the timestamps of the other track. Also includes SpatialLines representing the distances between the tracks.} \examples{ ## example tracks library(sp) library(xts) data(A3) track2 <- A3 index(track2@time) <- index(track2@time) + 32 track2@sp@coords <- track2@sp@coords + 0.003 ## compare and plot difftrack <- compare(A3, track2) plot(difftrack) } \author{ <NAME> <<EMAIL>> } \keyword{compare} <file_sep>/man/print.ArimaTrack.Rd \name{print.ArimaTrack} \alias{print.ArimaTrack} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "ArimaTrack" } \description{ print method.} \usage{ \method{print}{ArimaTrack}(x, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "ArimaTrack" } \item{...}{ignored} } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ <file_sep>/man/difftrack-class.Rd \name{difftrack-class} \Rdversion{1.1} \docType{class} \alias{difftrack-class} \alias{difftrack} \alias{plot,difftrack,ANY-method} \title{Class "difftrack"} \description{ Class that represents differences between two \link{Track} objects. } \section{Objects from the Class}{ Objects can be created by calls of the form \code{new("difftrack", ...)}. Objects of class \code{difftrack} contain 2 objects of class \link{Track} extended with points for timestamps of the other track and 2 \link{SpatialLinesDataFrame} conataining the the lines and distances between tracks. } \section{Slots}{ \describe{ \item{\code{track1}:}{Extended track1} \item{\code{track2}:}{Extended track2} \item{\code{conns1}:}{Lines between the original track1 and the new points on track2} \item{\code{conns2}:}{Lines between the original track2 and the new points on track1} } } \section{Methods}{ \describe{ \item{plot}{\code{signature(x = "difftrack", y = "missing")}: plot a difftrack} } } \author{ <NAME> <<EMAIL>> } \examples{ showClass("difftrack") ## example tracks library(sp) library(xts) data(A3) track2 <- A3 index(track2@time) <- index(track2@time) + 32 track2@sp@coords <- track2@sp@coords + 0.003 ## compare and plot difftrack <- compare(A3, track2) plot(difftrack) ## space-time cube of the difftrack \dontrun{ stcube(difftrack) } } \keyword{classes} <file_sep>/man/auto.arima.Track.Rd \name{auto.arima.Track} \alias{auto.arima.Track} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Fitting arima model to a track } \description{ Fit arima models to objects of class "Track".} \usage{ auto.arima.Track(X, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ an object of class "Track"} \item{...}{ passed to arguments of \link[forecast]{auto.arima}} } \details{ This fita arima models to the x,y locations of objects of class "Track".} \value{ an object of class "ArimaTrack" } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{rTrack}, \link[forecast]{auto.arima} } \examples{ if (require(forecast)) { X <- rTrack() auto.arima.Track(X) } } <file_sep>/man/print.arwlen.Rd \name{print.arwlen} \alias{print.arwlen} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "arwlen" } \description{ to print an object of class "arwlen".} \usage{ \method{print}{arwlen}(x,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "arqlen" } \item{...}{ignored} } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ <file_sep>/man/A3.Rd \name{A3} \alias{A3} \title{Trajectory} \description{Trajectory, locally stored, from envirocar.org, see example below how it was imported} \usage{ data(A3) } \keyword{datasets} \examples{ library(spacetime) data(A3) dim(A3) # see demo(A3) to see how A3 was fetched, and created from the web service } <file_sep>/man/density.list.Rd \name{density.list} \alias{density.list} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Kernel estimate of intensity of trajectory pattern } \description{ Estimating the intensity of a list of tracks. } \usage{ \method{density}{list}(x, timestamp,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ a list of "Track" objects, an object of class "Tracks" or "TracksCollection" } \item{timestamp}{based on secs, mins, ...} \item{...}{passed to arguments of density.ppp} } \details{ This estimate the average intensity function of moving objects over time. Bandwidth selection methods such as bw.diggle, bw.scott and bw.ppl can be passed to this density.list. } \value{ an image of class "im". } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{rTrack}, \link[spatstat.explore]{density.ppp} } \examples{ if (require(spatstat.explore)) { X <- list() for(i in 1:10){ m <- matrix(c(0,10,0,10),nrow=2,byrow = TRUE) X[[i]] <- rTrack(bbox = m,transform = TRUE) } density(X, timestamp = "180 secs") } } <file_sep>/demo/enviroCaR.R ## Shows how to se the enviroCaR R package to import enviroCar tracks. if (!require(devtools)) stop("install devtools first") if (!require(enviroCaR)) { devtools::install_github("enviroCar/enviroCaR"); library(enviroCaR) } ## get all track ids ids <- getTrackIDs("https://envirocar.org/api/stable") ## get ids using a bounding box and a time interval ## bounding box bbox <- matrix(c(7.318136,51.802163, 7.928939,52.105665), nrow=2, ncol=2) ## time interval: 96 hours t2 <- as.POSIXct("2015-01-20 10:11:20 CEST") t1 <- t2 - as.difftime(96, unit="hours") ## get ids ids <- getTrackIDs("https://envirocar.org/api/stable", bbox, list(first.time = t1, last.time = t2)) ## import tracks, returns a TracksCollection trcol <- importEnviroCar("https://envirocar.org/api/stable", ids) ## import single track, returns a Tracks object track <- importSingleTrack("https://envirocar.org/api/stable", ids[1]) <file_sep>/man/print.KTrack.Rd \name{print.KTrack} \alias{print.KTrack} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "KTrack" } \description{ Methods for class "KTrack" } \usage{ \method{print}{KTrack}(x,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "KTrack" } \item{...}{ ignored } } \details{ to print an object of class "KTrack".} \author{ <NAME> <<EMAIL>> } <file_sep>/man/cut.Rd \name{cut} \alias{cut} \alias{cut.Track} \alias{cut.Tracks} \alias{cut.TracksCollection} \title{ obtain ranges of space and time coordinates } \description{ obtain ranges of space and time coordinates } \usage{ \method{cut}{Track}(x, breaks, ..., include.lowest = TRUE, touch = TRUE) \method{cut}{Tracks}(x, breaks, ...) \method{cut}{TracksCollection}(x, breaks, ...) } \arguments{ \item{x}{ object of class \code{Track}, \code{Tracks} or \code{TracksCollection}} \item{breaks}{ define the breaks; see \link{cut}} \item{...}{ passed down to Tracks and Track methods, then to \link{cut}} \item{include.lowest}{ see \link{cut}} \item{touch}{ logical; if FALSE, Track objects will be formed from unique sets of points, meaning that gaps between two consecutive Track objects will arise; if FALSE, the first point from each next track is copied, meaning that sets of Track are seamless.} } \value{ The \code{cut} method applied to a \code{Track} object cuts the track in pieces, and hence returns a \code{Tracks} object. \code{cut.Tracks} returns a \code{Tracks} object, \code{cut.TracksCollection} returns a \code{TracksCollection}. } \details{ sub-trajectories can be invalid, if they have only one point, and are ignored. This can happen at the start only if \code{touch=FALSE}, and at the end in any case. } \examples{ \donttest{ # example might take too long for CRAN checks data(storms) dim(storms) dim(cut(storms, "week", touches = FALSE)) # same number of geometries dim(cut(storms, "week")) # increase of geometries = increase of tracks } } \keyword{dplot} <file_sep>/man/avedistTrack.Rd \name{avedistTrack} \alias{avedistTrack} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Average pairwise distance of trajectory pattern over time } \description{ This measures the average of pairwise distances between tracks over time. } \usage{ avedistTrack(X,timestamp) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{a list of some objects of class "Track" %% ~~Describe \code{x} here~~ } \item{timestamp}{timestamp to calculate the pairwise distances between tarcks} } \details{ This function calculates the average pairwise distance between a list of tracks according to a given timestamp. } \value{ An object of class "distrack". It can be plotted over time. } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{as.Track.ppp} } \examples{ if (require(spatstat.geom)) { X <- list() for(i in 1:10){ m <- matrix(c(0,10,0,10),nrow=2,byrow = TRUE) X[[i]] <- rTrack(bbox = m,transform = TRUE) } ave <- avedistTrack(X,timestamp = "120 secs") plot(ave,type="l") } } <file_sep>/man/Track-class.Rd \name{Track-class} \docType{class} \alias{Track-class} \alias{Tracks-class} \alias{TracksCollection-class} \alias{segments-class} \alias{Track} \alias{Tracks} \alias{TracksCollection} \alias{TrackStats} \alias{TrackSummary} \alias{TracksSummary} \alias{[,Track-method} \alias{[,Tracks-method} \alias{[,TracksCollection-method} \alias{[,Track,ANY,ANY,ANY-method} \alias{[,Tracks,ANY,ANY,ANY-method} \alias{[,TracksCollection,ANY,ANY,ANY-method} \alias{[[,Track,ANY,missing-method} \alias{[[,Tracks,ANY,missing-method} \alias{[[,TracksCollection,ANY,missing-method} \alias{[[<-,Track,ANY,missing-method} \alias{[[<-,Tracks,ANY,missing-method} \alias{[[<-,TracksCollection,ANY,missing-method} \alias{$,Track-method} \alias{$,Tracks-method} \alias{$,TracksCollection-method} \alias{$<-,Track-method} \alias{$<-,Tracks-method} \alias{$<-,TracksCollection-method} \alias{coerce,Track,data.frame-method} \alias{coerce,Tracks,data.frame-method} \alias{coerce,TracksCollection,data.frame-method} \alias{coordnames,Track-method} \alias{coordnames,Tracks-method} \alias{coordnames,TracksCollection-method} \alias{aggregate,Track-method} \alias{aggregate,Tracks-method} \alias{aggregate,TracksCollection-method} \alias{plot,TracksCollection,ANY-method} \alias{plot,Track,missing-method} \alias{plot,Tracks,ANY-method} \alias{stplot,TracksCollection-method} \alias{spTransform,Track,CRS-method} \alias{spTransform,Tracks,CRS-method} \alias{spTransform,TracksCollection,CRS-method} \alias{segPanel} \alias{tracksPanel} \alias{approxTrack} \alias{approxTracks} \alias{approxTracksCollection} \title{Classes "Track", "Tracks", and "TracksCollection"} \description{ Classes for representing sets of trajectory data, with attributes, for different IDs (persons, objects, etc) } \section{Objects from the Class}{ Objects of class \code{Track} extend \link{STIDF-class} and contain single trips or tracks, objects of class \code{Tracks} contain multiple \code{Track} objects for a single ID (person, object or tracking device), objects of class \code{TracksCollection} contain multiple \code{Tracks} objects for different IDs. } \section{Slots of class "Track"}{ \describe{ \item{\code{sp}:}{spatial locations of the track points, with length n} \item{\code{time}:}{time stamps of the track points} \item{\code{endTime}:}{end time stamps of the track points} \item{\code{data}:}{\code{data.frame} with n rows, containing attributes of the track points} \item{\code{connections}:}{\code{data.frame}, with n-1 rows, containing attributes between the track points such as distance and speed } } } \section{Slots of class "Tracks"}{ \describe{ \item{\code{tracks}:}{\code{list} with \code{Track} objects, of length m} \item{\code{tracksData}:}{\code{data.frame} with m rows, containing summary data for each \code{Track} object} } } \section{Slots of class "TracksCollection"}{ \describe{ \item{\code{tracksCollection}:}{\code{list} \code{Tracks} objects, of length p} \item{\code{tracksCollectionData}:}{\code{data.frame} with p rows, containing summary data for each \code{Tracks} object} } } \section{Methods}{ \describe{ \item{[[}{\code{signature(obj = "Track")}: retrieves the attribute element} \item{[[}{\code{signature(obj = "Tracks")}: retrieves the attribute element} \item{[[}{\code{signature(obj = "TracksCollection")}: retrieves the attribute element} \item{[[<-}{\code{signature(obj = "Track")}: sets or replaces the attribute element} \item{[[<-}{\code{signature(obj = "Tracks")}: sets or replaces the attribute element} \item{[[<-}{\code{signature(obj = "TracksCollection")}: sets or replaces the attribute element} \item{$}{\code{signature(obj = "Track")}: retrieves the attribute element} \item{$}{\code{signature(obj = "Tracks")}: retrieves the attribute element} \item{$}{\code{signature(obj = "TracksCollection")}: retrieves the attribute element} \item{$<-}{\code{signature(obj = "Track")}: sets or replaces the attribute element} \item{$<-}{\code{signature(obj = "Tracks")}: sets or replaces the attribute element} \item{$<-}{\code{signature(obj = "TracksCollection")}: sets or replaces the attribute element} \item{coerce}{Track,data.frame}{coerce to \code{data.frame}} \item{coerce}{Tracks,data.frame}{coerce to \code{data.frame}} \item{coerce}{TracksCollection,data.frame}{coerce to \code{data.frame}} \item{plot}{\code{signature(x = "TracksCollection", y = "missing")}: plots sets of sets of tracks} \item{stplot}{\code{signature(obj = "TracksCollection")}: plots sets of sets of tracks} % for spatial objects; does nothing but setting up a plotting region choosing % a suitable aspect if not given(see below), colouring the plot background using either a bg= argument or par("bg"), and possibly drawing axes. } % \item{summary}{\code{signature(object = "Spatial")}: summarize object} } } \usage{ Track(track, df = fn(track), fn = TrackStats) Tracks(tracks, tracksData = data.frame(row.names=names(tracks)), fn = TrackSummary) TracksCollection(tracksCollection, tracksCollectionData, fn = TracksSummary) TrackStats(track) TrackSummary(track) TracksSummary(tracksCollection) \S4method{[}{Track}(x, i, j, ..., drop = TRUE) \S4method{[}{TracksCollection}(x, i, j, ..., drop = TRUE) \S4method{coerce}{Track,data.frame}(from, to) \S4method{coerce}{Tracks,data.frame}(from, to) \S4method{coerce}{TracksCollection,data.frame}(from, to) % \S4method{over}{Tracks,Spatial}(x, y, returnList = FALSE, fn = NULL, ...) % \S4method{over}{TracksCollection,Spatial}(x, y, returnList = FALSE, } \arguments{ \item{track}{object of class \link{STIDF-class}, representing a single trip} \item{df}{optional \code{data.frame} with information between track points} \item{tracks}{named list with \code{Track} objects} \item{tracksData}{\code{data.frame} with summary data for each \code{Track}} \item{tracksCollection}{list, with \code{Tracks} objects} \item{tracksCollectionData}{data.frame, with summary data on \code{tracksCollection}} \item{fn}{function; } \item{x}{object of class \code{Track} etc} %\item{y}{object of class \code{Spatial}} \item{i}{selection of spatial entities} \item{j}{selection of temporal entities (see syntax in package xts) } \item{...}{selection of attribute(s)} \item{drop}{logical} \item{from}{from} \item{to}{target class} } \value{Functions \code{Track}, \code{Tracks} and \code{TracksCollection} are constructor functions that take the slots as arguments, check object validity, and compute summary statistics on the track and tracks sets. \code{TrackStats} returns a \code{data.frame} with for each track segment the distance, duration, speed, and direction. In case data are geographical coordinates (long/lat), distance is in m, and direction is initial bearing. \code{TrackSummary} reports for each track xmin, xmax, ymin, ymax, tmin, tmax, (number of points) n, (total) distance, and medspeed (median speed). \code{TracksSummary} reports for each Tracks of a TracksCollection (number of tracks) n, xmin, xmax, ymin, ymax, tmin, tmin, tmax. } \author{ <NAME>, \email{<EMAIL>} } \references{ http://www.jstatsoft.org/v51/i07/ } \note{\code{segments} is a \code{data.frame} form in which track segments instead of track points form a record, with \code{x0}, \code{y0}, \code{x1} and \code{y1} the start and end coordinates} \examples{ library(sp) library(spacetime) # t0 = as.POSIXct(as.Date("2013-09-30",tz="CET")) t0 = as.POSIXct("2013-09-30 02:00:00", tz = "Europe/Berlin") # person A, track 1: x = c(7,6,5,5,4,3,3) y = c(7,7,6,5,5,6,7) n = length(x) set.seed(131) t = t0 + cumsum(runif(n) * 60) crs = CRS("+proj=longlat +datum=WGS84") # longlat stidf = STIDF(SpatialPoints(cbind(x,y),crs), t, data.frame(co2 = rnorm(n))) A1 = Track(stidf) # person A, track 2: x = c(7,6,6,7,7) y = c(6,5,4,4,3) n = length(x) t = max(t) + cumsum(runif(n) * 60) stidf = STIDF(SpatialPoints(cbind(x,y),crs), t, data.frame(co2 = rnorm(n))) A2 = Track(stidf) # Tracks for person A: A = Tracks(list(A1=A1,A2=A2)) # person B, track 1: x = c(2,2,1,1,2,3) y = c(5,4,3,2,2,3) n = length(x) t = max(t) + cumsum(runif(n) * 60) stidf = STIDF(SpatialPoints(cbind(x,y),crs), t, data.frame(co2 = rnorm(n))) B1 = Track(stidf) # person B, track 2: x = c(3,3,4,3,3,4) y = c(5,4,3,2,1,1) n = length(x) t = max(t) + cumsum(runif(n) * 60) stidf = STIDF(SpatialPoints(cbind(x,y),crs), t, data.frame(co2 = rnorm(n))) B2 = Track(stidf) # Tracks for person A: B = Tracks(list(B1=B1,B2=B2)) Tr = TracksCollection(list(A=A,B=B)) stplot(Tr, scales = list(draw=TRUE)) stplot(Tr, attr = "direction", arrows=TRUE, lwd = 3, by = "direction") stplot(Tr, attr = "direction", arrows=TRUE, lwd = 3, by = "IDs") plot(Tr, col=2, axes=TRUE) dim(Tr) dim(Tr[2]) dim(Tr[2][1]) u = stack(Tr) # four IDs dim(u) dim(unstack(u, c(1,1,2,2))) # regroups to original dim(unstack(u, c(1,1,2,3))) # regroups to three IDs dim(unstack(u, c(1,2,2,1))) # regroups differently as(Tr, "data.frame")[1:10,] # tracks separated by NA rows as(Tr, "segments")[1:10,] # track segments as records Tr[["distance"]] = Tr[["distance"]] * 1000 Tr$distance = Tr$distance / 1000 Tr$distance # work with custum TrackStats function: MyStats = function(track) { df = apply(coordinates(track@sp), 2, diff) # requires sp data.frame(distance = apply(df, 1, function(x) sqrt(sum(x^2)))) } crs = CRS(as.character(NA)) stidf = STIDF(SpatialPoints(cbind(x,y),crs), t, data.frame(co2 = rnorm(n))) B2 = Track(stidf) # no longer longlat; B3 = Track(stidf, fn = MyStats) all.equal(B3$distance, B2$distance) # approxTrack: opar = par() par(mfrow = c(1, 2)) plot(B2, ylim = c(.5, 6)) plot(B2, pch = 16, add = TRUE) title("irregular time steps") i = index(B2) B3 = approxTrack(B2, seq(min(i), max(i), length.out = 50)) plot(B3, col = 'red', type = 'p', add = TRUE) B4 = approxTrack(B2, seq(min(i), max(i), length.out = 50), FUN = spline) plot(B4, col = 'blue', type = 'b', add = TRUE) # regular time steps: t = max(t) + (1:n) * 60 # regular B2 = Track(STIDF(SpatialPoints(cbind(x,y),crs), t, data.frame(co2 = rnorm(n)))) plot(B2, ylim = c(.5, 6)) plot(B2, pch = 16, add = TRUE) title("constant time steps") i = index(B2) B3 = approxTrack(B2) plot(B3, type = 'p', col = 'red', add = TRUE) B4 = approxTrack(B2, FUN = spline) plot(B4, type = 'p', col = 'blue', add = TRUE) \donttest{ # par(opar) # good to do, but would generate warnings smth = function(x,y,xout,...) predict(smooth.spline(as.numeric(x), y), as.numeric(xout)) data(storms) plot(storms, type = 'p') storms.smooth = approxTracksCollection(storms, FUN = smth, n = 200) plot(storms.smooth, add = TRUE, col = 'red') } } \keyword{classes} <file_sep>/demo/A3.R require(RCurl) require(rgdal) require(rjson) require(sp) require(spacetime) importEnviroCar = function(trackID, url = "https://envirocar.org/api/stable/tracks/") { url = getURL(paste(url, trackID, sep = ""), .opts = list(ssl.verifypeer = FALSE)) # .opts needed for Windows # Read data into spatial object. spdf = readOGR(dsn = url, layer = "OGRGeoJSON", verbose = FALSE) # Convert time from factor to POSIXct. #time = as.POSIXct(spdf$time, format = "%Y-%m-%dT%H:%M:%SZ") time = as.POSIXct(paste0(as.character(spdf$time),"00"), format = "%Y/%m/%d %H:%M:%S%z") # Convert phenomena from JSON to data frame. phenomena = lapply(as.character(spdf$phenomenons), fromJSON) values = lapply(phenomena, function(x) as.data.frame(lapply(x, function(y) y$value))) # Get a list of all phenomena for which values exist. names = vector() for(i in values) names = union(names, names(i)) # Make sure that each data frame has the same number of columns. values = lapply(values, function(x) { xNames = names(x) # Get the symmetric difference. diff = setdiff(union(names, xNames), intersect(names, xNames)) if(length(diff) > 0) x[diff] = NA x }) # Bind values together. data = do.call(rbind, values) sp = SpatialPoints(coords = coordinates(spdf), proj4string = CRS("+proj=longlat +datum=WGS84")) stidf = STIDF(sp = sp, time = time, data = data) Track(track = stidf) } A3 = importEnviroCar("<KEY>") plot(A3) <file_sep>/man/print.distrack.Rd \name{print.distrack} \alias{print.distrack} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "distrack" } \description{ This is a method for class "distrack". } \usage{ \method{print}{distrack}(x,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "distrack"} \item{...}{ignored} } \details{ This is a method for class "distrack". } \value{ See the documentation on the corresponding generic function. } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \examples{ if (require(spatstat.geom)) { X <- list() for(i in 1:10){ m <- matrix(c(0,10,0,10),nrow=2,byrow = TRUE) X[[i]] <- rTrack(bbox = m,transform = TRUE) } ave <- avedistTrack(X,timestamp = "30 secs") plot(ave,type="l") } } <file_sep>/man/print.Trrow.Rd \name{print.Trrow} \alias{print.Trrow} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "Trrow" } \description{ Print objetcs of class "Trrow"} \usage{ \method{print}{Trrow}(x,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "Trrow" } \item{...}{ ignored } } \author{ <NAME> <<EMAIL>> } \seealso{ as.Track.arrow } <file_sep>/R/Tracks-methods.R # Segments are data.frames with a segment on each row, with x0 y0 x1 y1 the # first four values, followed by attributes. setClass("segments", contains = "data.frame") # Coerce to segments. setAs("Track", "segments", function(from) { cc = coordinates(from@sp) t = index(from@time) df = from@data data.frame(x0 = head(cc[,1], -1), y0 = head(cc[,2], -1), x1 = tail(cc[,1], -1), y1 = tail(cc[,2], -1), time = head(t, -1), head(df, -1), from@connections) } ) setAs("Tracks", "segments", function(from) { ret = do.call(rbind, lapply(from@tracks, function(x) as(x, "segments"))) ret$Track = rep(names(from@tracks), times = sapply(from@tracks, length) - 1) ret } ) setAs("TracksCollection", "segments", function(from) { l = lapply(from@tracksCollection, function(x) as(x, "segments")) ret = do.call(rbind, l) ret$IDs = rep(names(from@tracksCollection), times = sapply(l, nrow)) ret } ) # Coerce to data frame. setAs("Track", "data.frame", function(from) as(as(from, "STIDF"), "data.frame") ) setAs("Tracks", "data.frame", function(from) { l = lapply(from@tracks, function(x) rbind(as(x, "data.frame"), NA)) d = do.call(rbind, l) d$Track = rep(names(from@tracks), times = sapply(l, nrow)) d } ) setAs("TracksCollection", "data.frame", function(from) { l = lapply(from@tracksCollection, function(x) as(x, "data.frame")) ret = do.call(rbind, l) data.frame(ret, IDs = rep(names(from@tracksCollection), times = sapply(l, nrow))) } ) # Coerce to Line, Lines, SpatialLines and SpatialLinesDataFrame. setAs("Track", "Line", function(from) Line(coordinates(from)) ) setAs("Track", "Lines", function(from) Lines(list(as(from, "Line")), "ID") ) setAs("Track", "SpatialLines", function(from) SpatialLines(list(as(from, "Lines")), from@sp@proj4string) ) setAs("Tracks", "Lines", function(from) { tz = from@tracks # The Lines ID is made up of the conjunction of the first and last Track # ID, using hyphen as separator. Lines(lapply(tz, function(x) as(x, "Line")), paste(names(tz)[1], names(tz)[length(tz)], sep = "-")) } ) setAsWithID <- function(from, ID=NA) { l = lapply(from@tracks, function(x) as(x, "Lines")) for (i in seq_along(l)) l[[i]]@ID = paste(switch(is.na(ID),"ID",ID), "_", i, sep="") SpatialLines(l, from@tracks[[1]]@sp@proj4string) } setAs("Tracks", "SpatialLines", function(from) setAsWithID(from)) setAs("Tracks", "SpatialLinesDataFrame", function(from) SpatialLinesDataFrame(as(from, "SpatialLines"), from@tracksData, match.ID = FALSE) ) setAs("TracksCollection", "SpatialLines", function(from) { l <- lapply(from@tracksCollection, function(tracksObj) as(tracksObj, "Lines")) if (is.null(rownames(from@tracksCollectionData))) tracksIDs <- paste("ID", 1:length(from@tracksCollection), sep="") else tracksIDs <- rownames(from@tracksCollectionData) trackIDs <- rep(tracksIDs, sapply(from@tracksCollection, length)) for (i in seq_along(l)) { l[[i]]@ID <- paste(trackIDs[i], l[[i]]@ID, sep="_") } #SpatialLines(l, from@sp@proj4string) SpatialLines(l, from@tracksCollection[[1]]@tracks[[1]]@sp@proj4string) } ) setAs("TracksCollection", "SpatialLinesDataFrame", function(from) SpatialLinesDataFrame(as(from, "SpatialLines"), from@tracksCollectionData, match.ID = FALSE) ) # Coerce to xts; Track is automatic through STIDF. setAs("Tracks", "xts", function(from) do.call(rbind, lapply(from@tracks, function(x) as(x, "xts"))) ) setAs("TracksCollection", "xts", function(from) do.call(rbind, lapply(from@tracksCollection, function(x) as(x, "xts"))) ) # Coerce to STIDF. setAs("Tracks", "STIDF", function(from) do.call(rbind, lapply(from@tracks, function(x) as(x, "STIDF"))) ) setAs("TracksCollection", "STIDF", function(from) do.call(rbind, lapply(from@tracksCollection, function(x) as(x, "STIDF"))) ) # Coerce to Spatial* setAs("Track", "Spatial", function(from) { from@data$time = index(from@time) if (!all(from@data$time == from@endTime)) from@data$endTime = from@endTime addAttrToGeom(from@sp, from@data, match.ID = FALSE) } ) setAs("Tracks", "Spatial", function(from) { ret = do.call(rbind, lapply(from@tracks, function(x) as(x, "Spatial"))) ret$Track = rep(names(from@tracks), times = lapply(from@tracks, length)) ret } ) setAs("TracksCollection", "Spatial", function(from) do.call(rbind, lapply(from@tracksCollection, function(x) as(x, "Spatial"))) ) # Coerce to SpatialPointsDataFrame. setAs("Track", "SpatialPointsDataFrame", function(from) as(from, "Spatial")) setAs("Tracks", "SpatialPointsDataFrame", function(from) as(from, "Spatial")) setAs("TracksCollection", "SpatialPointsDataFrame", function(from) as(from, "Spatial")) # Provide coordinates methods. setMethod("coordinates", "Track", function(obj) { if(inherits(obj@sp, "SpatialPoints")) {return(as.data.frame(obj@sp))} if (inherits(obj@sp, "SpatialLines")) {do.call(rbind,lapply(coordinates(obj@sp), as.data.frame))} } ) setMethod("coordinates", "Tracks", function(obj) do.call(rbind, lapply(obj@tracks, function(x) coordinates(x))) ) setMethod("coordinates", "TracksCollection", function(obj) do.call(rbind, lapply(obj@tracksCollection, function(x) coordinates(x))) ) # Provide proj4string methods. setMethod("proj4string", signature(obj = "Track"), function(obj) proj4string(obj@sp) ) setMethod("proj4string", signature(obj = "Tracks"), function(obj) proj4string(obj@tracks[[1]]) ) setMethod("proj4string", signature(obj = "TracksCollection"), function(obj) proj4string(obj@tracksCollection[[1]]) ) # Provide plot methods. TODO Make more generic. plot.TracksCollection <- function(x, y, ..., xlim = stbox(x)[,1], ylim = stbox(x)[,2], col = 1, lwd = 1, lty = 1, axes = TRUE, Arrows = FALSE, Segments = FALSE, add = FALSE, length = 0.25, angle = 30, code = 2) { sp = x@tracksCollection[[1]]@tracks[[1]]@sp if (Arrows || Segments) { if (! add) plot(sp, xlim = xlim, ylim = ylim, axes = axes, ...) if (axes == FALSE) box() df = as(x, "segments") args = list(x0 = df$x0, y0 = df$y0, x1 = df$x1, y1 = df$y1, col = col, lwd = lwd, lty = lty) if (Arrows) do.call(arrows, append(args, list(length = length, angle = angle, code = code))) else do.call(segments, args) } else plot(as(x, "SpatialLines"), xlim = xlim, ylim = ylim, axes = axes, col = col, lwd = lwd, lty = lty, add = add, ...) } setMethod("plot", "TracksCollection", plot.TracksCollection) setMethod("plot", "Tracks", function(x, ...) plot(TracksCollection(list(x)), ...)) setMethod("plot", c("Track", "missing"), function(x, ...) plot(Tracks(list(x)), ...)) # Provide coordnames methods. setMethod("coordnames", "Track", function(x) coordnames(x@sp)) setMethod("coordnames", "Tracks", function(x) coordnames(x@tracks[[1]])) setMethod("coordnames", "TracksCollection", function(x) coordnames(x@tracksCollection[[1]])) # Provide stbox methods. # AUTOMATIC: fallback to ST (see ST-methods.R) #setMethod("stbox", "Track", # function(obj) { # bb = data.frame(t(bbox(obj@sp))) # bb$time = range(index(obj@time)) # rownames(bb) = c("min", "max") # bb # } #) setMethod("stbox", "Tracks", function(obj) { df = obj@tracksData xr = c(min(df$xmin), max(df$xmax)) yr = c(min(df$ymin), max(df$ymax)) tr = c(min(df$tmin), max(df$tmax)) cn = coordnames(obj) ret = data.frame(xr, yr, time = tr) colnames(ret)[1:2] = cn rownames(ret) = c("min", "max") ret } ) setMethod("stbox", "TracksCollection", function(obj) { df = obj@tracksCollectionData xr = c(min(df$xmin), max(df$xmax)) yr = c(min(df$ymin), max(df$ymax)) tr = c(min(df$tmin), max(df$tmax)) cn = coordnames(obj) ret = data.frame(xr, yr, time = tr) colnames(ret)[1:2] = cn rownames(ret) = c("min", "max") ret } ) # Provide bbox methods. setMethod("bbox", "Tracks", function(obj) t(stbox(obj)[1:2])) setMethod("bbox", "TracksCollection", function(obj) t(stbox(obj)[1:2])) # Provide over methods. setMethod("over", c("Track", "Spatial"), function(x, y, ...) over(as(x, "SpatialLines"), y, ...)) setMethod("over", c("Tracks", "Spatial"), function(x, y, ...) over(as(x, "SpatialLines"), y, ...)) setMethod("over", c("TracksCollection", "Spatial"), function(x, y, ...) over(as(x, "SpatialLines"), y, ...)) setMethod("over", c("Track", "xts"), function(x, y, ...) over(as(x, "xts"), y, ...)) setMethod("over", c("Tracks", "xts"), function(x, y, ...) over(as(x, "xts"), y, ...)) setMethod("over", c("TracksCollection", "xts"), function(x, y, ...) over(as(x, "xts"), y, ...)) # Provide aggregate methods. setMethod("aggregate", "Track", function(x, ...) { aggregate(as(x, "SpatialPointsDataFrame"), ...) } ) setMethod("aggregate", "Tracks", function(x, ...) { aggregate(as(x, "SpatialPointsDataFrame"), ...) } ) setMethod("aggregate", "TracksCollection", function(x, ...) { aggregate(as(x, "SpatialPointsDataFrame"), ...) } ) # Provide dimension methods. dim.Track = function(x) c(geometries = length(x@sp)) dim.Tracks = function(x) c(tracks = length(x@tracks), geometries = sum(sapply(x@tracks, dim))) dim.TracksCollection = function(x) c(IDs = length(x@tracksCollection), apply(sapply(x@tracksCollection,dim), 1, sum)) # Provide summary methods. summary.Track = function(object, ...) { obj = list() obj$class = class(object) obj$dim = dim(object) obj$stbox = stbox(object) obj$sp = summary(object@sp) obj$time = summary(object@time) obj$data = summary(object@data) obj$connections = summary(object@connections) class(obj) = "summary.Track" obj } setMethod("summary", "Track", summary.Track) print.summary.Track = function(x, ...) { cat(paste("Object of class ", x$class, "\n", sep = "")) cat(" with Dimensions: (") cat(paste(x$dim, collapse = ", ")) cat(")\n") cat("[[stbox]]\n") print(x$stbox) cat("[[Spatial:]]\n") print(x$sp) cat("[[Temporal:]]\n") print(x$time) cat("[[Data attributes:]]\n") print(x$data) cat("[[Connections:]]\n") print(x$connections) invisible(x) } summary.Tracks = function(object, ...) { obj = list() obj$class = class(object) obj$dim = dim(object) obj$stbox = stbox(object) obj$sp = summary(do.call(rbind, lapply(object@tracks, function(x) x@sp))) obj$time = summary(do.call(rbind, lapply(object@tracks, function(x) x@time))) obj$data = summary(do.call(rbind, lapply(object@tracks, function(x) x@data))) obj$connections = summary(do.call(rbind, lapply(object@tracks, function(x) x@connections))) class(obj) = "summary.Tracks" obj } setMethod("show", "Track", function(object) print.Track(object)) setMethod("show", "Tracks", function(object) print.Tracks(object)) setMethod("show", "TracksCollection", function(object) print.TracksCollection(object)) setMethod("summary", "Tracks", summary.Tracks) print.summary.Tracks = function(x, ...) { cat(paste("Object of class ", x$class, "\n", sep = "")) cat(" with Dimensions (tracks, geometries): (") cat(paste(x$dim, collapse = ", ")) cat(")\n") cat("[[stbox]]\n") print(x$stbox) cat("[[Spatial:]]\n") print(x$sp) cat("[[Temporal:]]\n") print(x$time) cat("[[Data attributes:]]\n") print(x$data) cat("[[Connections:]]\n") print(x$connections) invisible(x) } summary.TracksCollection = function(object, ...) { obj = list() obj$class = class(object) obj$dim = dim(object) obj$stbox = stbox(object) obj$sp = summary(do.call(rbind, lapply(object@tracksCollection, function(x) do.call(rbind, lapply(x@tracks, function(y) y@sp))))) obj$time = summary(do.call(rbind, lapply(object@tracksCollection, function(x) do.call(rbind, lapply(x@tracks, function(y) y@time))))) obj$data = summary(do.call(rbind, lapply(object@tracksCollection, function(x) do.call(rbind, lapply(x@tracks, function(y) y@data))))) obj$connections = summary(do.call(rbind, lapply(object@tracksCollection, function(x) do.call(rbind, lapply(x@tracks, function(y) y@connections))))) class(obj) = "summary.TracksCollection" obj } setMethod("summary", "TracksCollection", summary.TracksCollection) print.summary.TracksCollection = function(x, ...) { cat(paste("Object of class ", x$class, "\n", sep = "")) cat(" with Dimensions (IDs, tracks, geometries): (") cat(paste(x$dim, collapse = ", ")) cat(")\n") cat("[[stbox]]\n") print(x$stbox) cat("[[Spatial:]]\n") print(x$sp) cat("[[Temporal:]]\n") print(x$time) cat("[[Data attributes:]]\n") print(x$data) cat("[[Connections:]]\n") print(x$connections) invisible(x) } # Provide selection methods. subs.Track <- function(x, i, j, ..., drop = TRUE) { Track(as(x, "STIDF")[i, j, ..., drop = drop]) } setMethod("[", "Track", subs.Track) subs.Tracks <- function(x, i, j, ... , drop = TRUE) { if (missing(i)) i = 1:length(x@tracks) else if (is(i, "Spatial")) i = which(!is.na(over(x, geometry(i)))) else if (is.character(i) && length(i) == 1 && !(i %in% names(x@tracks))) # i time: i = sapply(x@tracks, function(x) nrow(as(x, "xts")[i]) > 0) else if (is.logical(i)) i = which(i) if (length(i) == 1 && drop) x@tracks[[i]] else { if (!any(i)) NULL else Tracks(x@tracks[i], x@tracksData[i, j, drop=FALSE]) } } setMethod("[", "Tracks", subs.Tracks) subs.TracksCollection <- function(x, i, j, ... , drop = TRUE) { if (!missing(j) && is.character(j)) { for(tz in seq_along(x@tracksCollection)) { for(t in seq_along(x[tz]@tracks)) { data = x[tz][t]@data connections = x[tz][t]@connections if(j %in% names(data)) data = data[j] else # An empty data slot is returned if the passed attribute # does not exist. The same applies to the connections slot. data = data.frame(matrix(nrow = dim(x[tz][t])["geometries"], ncol = 0)) if(j %in% names(connections)) connections = connections[j] else connections = data.frame(matrix(nrow = dim(x[tz][t])["geometries"] - 1, ncol = 0)) # Write back the just processed data and connection slots. x@tracksCollection[[tz]]@tracks[[t]]@data = data x@tracksCollection[[tz]]@tracks[[t]]@connections = connections } } } if (missing(i)) s = 1:length(x@tracksCollection) else if (is(i, "Spatial")) s = which(!is.na(over(x, geometry(i)))) else if (is.character(i) && length(i) == 1 && !(i %in% names(x@tracksCollection))) # i time: i = lapply(x@tracksCollection, function(x) which(sapply(x@tracks, function(x) nrow(as(x, "xts")[i]) > 0))) else if (is.logical(i)) s = which(i) else s = i if (!missing(i) && is.list(i)) { # might have been created by the lappty() above stopifnot(all(sapply(i, function(x) is.numeric(x)))) s = which(sapply(i, function(x) length(x) > 0)) for(index in seq_along(s)) { tz = x@tracksCollection[[s[index]]] tz@tracks = tz@tracks[i[[s[index]]]] tz@tracksData = tz@tracksData[i[[s[index]]], ] # Write back the just processed Tracks element. x@tracksCollection[[s[index]]] = tz } } # Drop data structure. Only relevant in case one single Tracks/Track element # have/has been selected. Multiple Tracks elements are always returned as # TracksCollection, independently of whether drop is true or false. if (drop && length(s) == 1) { if(is.list(i) && length(i[[s[1]]]) == 1) # Last [] is 1, since all but one Track elements have been sorted # out above. x@tracksCollection[[s]][1] else x@tracksCollection[[s]] } # Retain data structure, even if only one single Tracks/Track element # have/has been selected. else TracksCollection(x@tracksCollection[s], x@tracksCollectionData[s,,drop=FALSE]) } setMethod("[", "TracksCollection", subs.TracksCollection) setMethod("[[", c("Track", "ANY", "missing"), function(x, i, j, ...) { # TODO What if the attribute name coexists in both the data and # connections slot? Returning a list is inconvenient in the way that it # raises new design issues when making selections on objects of class # Tracks or TracksCollection: How to merge lists if tracks differ in # their "attribute state" (the passed attribute coexists in both slots, # exists in one slot only, does not exist)? if(i %in% names(x@data)) x@data[[i]] else # Returns NULL if the attribute does not exist. x@connections[[i]] } ) setMethod("[[", c("Tracks", "ANY", "missing"), function(x, i, j, ...) { do.call(c, lapply(x@tracks, function(t) t[[i]])) } ) setMethod("[[", c("TracksCollection", "ANY", "missing"), function(x, i, j, ...) { do.call(c, lapply(x@tracksCollection, function(t) t[[i]])) } ) setReplaceMethod("[[", c("Track", "ANY", "missing", "ANY"), function(x, i, j, value) { if (i %in% names(x@connections)) { warning(paste("replacing", i, "in connections slot")) x@connections[[i]] = value } else x@data[[i]] = value x } ) setReplaceMethod("[[", c("Tracks", "ANY", "missing", "ANY"), function(x, i, j, value) { for(index in seq_along(x@tracks)) { if(i %in% names(x[index]@data)) { # "dim" (and with that "from" and "to") have to be reinitialized # each loop, since tracks might differ in their "attribute # state" (the passed attribute coexists in both slots, exists in # one slot only, does not exist). dim = sapply(x@tracks, function(t) dim(t)[["geometries"]]) from = if(index == 1) 1 else cumsum(dim)[index-1] + 1 to = cumsum(dim)[index] x@tracks[[index]]@data[[i]] = value[from:to] } else if(i %in% names(x[index]@connections)) { dim = sapply(x@tracks, function(t) dim(t)[["geometries"]]) - 1 from = if(index == 1) 1 else cumsum(dim)[index-1] + 1 to = cumsum(dim)[index] x@tracks[[index]]@connections[[i]] = value[from:to] } } x } ) setReplaceMethod("[[", c("TracksCollection", "ANY", "missing", "ANY"), function(x, i, j, value) { index = 1 for(tz in seq_along(x@tracksCollection)) { for(t in seq_along(x[tz]@tracks)) { if(i %in% names(x[tz][t]@data)) { dim = do.call(c, lapply(x@tracksCollection, function(tz) sapply(tz@tracks, function(t) dim(t)[["geometries"]]))) from = if(index == 1) 1 else cumsum(dim)[index-1] + 1 to = cumsum(dim)[index] x@tracksCollection[[tz]]@tracks[[t]]@data[[i]] = value[from:to] } else if(i %in% names(x[tz][t]@connections)) { dim = do.call(c, lapply(x@tracksCollection, function(tz) sapply(tz@tracks, function(t) dim(t)[["geometries"]]))) - 1 from = if(index == 1) 1 else cumsum(dim)[index-1] + 1 to = cumsum(dim)[index] x@tracksCollection[[tz]]@tracks[[t]]@connections[[i]] = value[from:to] } index = index + 1 } } x } ) setMethod("$", "Track", function(x, name) x[[name]]) setMethod("$", "Tracks", function(x, name) x[[name]]) setMethod("$", "TracksCollection", function(x, name) x[[name]]) setReplaceMethod("$", "Track", function(x, name, value) { x[[name]] = value x } ) setReplaceMethod("$", "Tracks", function(x, name, value) { x[[name]] = value x } ) setReplaceMethod("$", "TracksCollection", function(x, name, value) { x[[name]] = value x } ) # Provide stack, unstack and concatenate c() methods. stack.TracksCollection = function (x, select, ...) { stopifnot(missing(select)) splt = function(Tr) lapply(Tr@tracks, function(x) Tracks(list(x))) l = lapply(x@tracksCollection, function(x) splt(x)) TracksCollection(do.call(c, l)) } c.Track = function(...) { lst = list(...) # check time is in sequence: i = do.call(c, lapply(lst, function(x) index(x))) if (is.unsorted(i)) stop("cannot concatenate overlapping or unsorted Track objects") Track(do.call(rbind, lapply(lst, function(x) as(x, "STIDF")))) } c.Tracks = function(...) Tracks(do.call(c, lapply(list(...), function(x) x@tracks))) c.TracksCollection = function(...) TracksCollection(do.call(c, lapply(list(...), function(x) x@tracksCollection))) unstack.TracksCollection = function(x, form, ...) { TracksCollection(lapply(split(x@tracksCollection, form), function(x) do.call(c, x))) } # approx coordinates and attributes for specific new time points, approxTrack = function(track, when, ..., n = 50, by, FUN = stats::approx, warn.if.outside = TRUE) { x = index(track) if (missing(when)) { if (missing(by)) when = seq(min(x), max(x), length.out = n) else when = seq(min(x), max(x), by = by) } else if (warn.if.outside && (min(when) < min(index(track)) || max(when) > max(index(track)))) warning("approxTrack: approximating outside data range") cc = coordinates(track) p = apply(cc, 2, function(y) FUN(x, y, xout = when, n = n, ...)$y) d = data.frame(lapply(track@data, function(y) FUN(x, y, xout = when, n = n, ... )$y)) if (!is.matrix(p)) { # single point: return STIDF p = matrix(p, ncol = ncol(cc)) STIDF(SpatialPoints(p, track@sp@proj4string), when, d) } else Track(STIDF(SpatialPoints(p, track@sp@proj4string), when, d)) } approxTracks = function(tr, ...) Tracks(lapply(tr@tracks, function(x) approxTrack(x,...))) approxTracksCollection = function(tc, ...) TracksCollection(lapply(tc@tracksCollection, function(x) approxTracks(x,...))) setMethod("spTransform", c("Track", "CRS"), function(x, CRSobj, ...) #Track(spTransform(as(x, "STIDF"), CRSobj, ...), df = x@connections) Track(spTransform(as(x, "STIDF"), CRSobj, ...)) ) setMethod("spTransform", c("Tracks", "CRS"), function(x, CRSobj, ...) Tracks(lapply(x@tracks, function(y) spTransform(y, CRSobj, ...))) ) setMethod("spTransform", c("TracksCollection", "CRS"), function(x, CRSobj, ...) TracksCollection(lapply(x@tracksCollection, function(y) spTransform(y, CRSobj, ...))) ) ## Default S3 method: # cut(x, breaks, labels = NULL, # include.lowest = FALSE, right = TRUE, dig.lab = 3, # ordered_result = FALSE, ...) cut.Track = function(x, breaks, ..., include.lowest = TRUE, touch = TRUE) { i = index(x) f = cut(i, breaks, ..., include.lowest = include.lowest) d = dim(x) # nr of pts x = as(x, "STIDF") if (! touch) spl = lapply(split(x = seq_len(d), f), function(ind) x[ind, , drop = FALSE]) else spl = lapply(split(x = seq_len(d), f), function(ind) { ti = tail(ind, 1) if (ti < d) ind = c(ind,ti+1) x[ind, , drop = FALSE] }) Tracks(lapply(spl[sapply(spl, length) > 1], Track)) } cut.Tracks = function(x, breaks, ...) do.call(c, lapply(x@tracks, cut, breaks = breaks, ...)) cut.TracksCollection = function(x, breaks, ...) TracksCollection(lapply(x@tracksCollection, cut, breaks = breaks, ...)) "index<-.Track" = function(x, value) { index(x@time) = value x } setReplaceMethod("geometry", c("Track", "Spatial"), function(obj, value) { obj@sp = value obj }) <file_sep>/R/difftrack.R setClass("difftrack", slots=c(track1 ="Track", track2 = "Track", conns1 = "SpatialLinesDataFrame", conns2 = "SpatialLinesDataFrame"), ) ## plots a difftrack plot.difftrack <- function(x, y, ..., axes = TRUE) { plot(x@track1@sp, col="red", ..., axes = axes) points(x@track2@sp, col="blue") lines(x@conns1) lines(x@conns2) } setMethod("plot", "difftrack", plot.difftrack) ## stcube for difftrack stcube.difftrack <- function(x, showMap = FALSE, mapType = "osm", normalizeBy = "week", ..., y, z) { tracks <- Tracks(list(x@track1, x@track2)) stcube(tracks, showMap = showMap, mapType = mapType, normalizeBy = normalizeBy, ...) lines1 <- x@conns1@lines lines2 <- x@conns2@lines time1 <- x@conns1@data$time time1 <- normalize(time1, normalizeBy) time2 <- x@conns2@data$time time2 <- normalize(time2, normalizeBy) sapply(lines1, function(l) { coords <- coordinates(l) id <- as.numeric(l@ID) z <- time1[id] rgl::lines3d(coords[[1]][,1], coords[[1]][,2], z, col = "red") }) sapply(lines2, function(l) { coords <- coordinates(l) id <- as.numeric(l@ID) z <- time2[id] rgl::lines3d(coords[[1]][,1], coords[[1]][,2], z, col = "blue") }) } setMethod("stcube", "difftrack", stcube.difftrack) <file_sep>/R/rtracks.R rTrack <- function (n = 100, origin = c(0, 0), start = as.POSIXct("1970-01-01"), ar = 0.8, step = 60, sd0 = 1,bbox=bbox, transform=FALSE,nrandom=FALSE, ...){ if(nrandom) repeat{n <- rpois(1,n);if(!n==0) break()} if (missing(bbox) & transform) { xo <- runif(1) yo <- runif(1) origin <- c(xo,yo) } if (!missing(bbox) & transform) { xo <- runif(1,bbox[1,1],bbox[1,2]) yo <- runif(1,bbox[2,1],bbox[2,2]) origin <- c(xo,yo) } if (length(ar) == 1 && ar == 0) xy = cbind(x=cumsum(rnorm(n, sd = sd0)) + origin[1], y=cumsum(rnorm(n, sd = sd0)) + origin[2]) else {xy = cbind(x=origin[1] + cumsum(as.vector(arima.sim(list(ar = ar), n, sd = sd0, ...))), y=origin[2] + cumsum(as.vector(arima.sim(list(ar = ar), n, sd = sd0, ...))))} if(transform) { if(missing(bbox)) bbox <- matrix(c(0,1,0,1),nrow = 2,byrow = T); colnames(bbox) <- c("min","max");rownames(bbox) <- c("x","y") xr <- max(xy[,1])-min(xy[,1]) yr <- max(xy[,2])-min(xy[,2]) xt <- (xy[,1]-min(xy[,1]))/xr yt <- (xy[,2]-min(xy[,2]))/yr xy <- cbind(xt,yt) xy <- cbind(x=xy[,1]*bbox[1,2],y=xy[,2]*bbox[2,2]) } T = start + 0:(n - 1) * step sti = STI(SpatialPoints(xy), T) out <- Track(sti) if (transform) out@sp@bbox <- bbox return(out) } rTracks <- function (m = 20, start = as.POSIXct("1970-01-01"), delta = 7200, sd1 = 0, origin = c(0, 0), ...) Tracks(lapply(0:(m - 1) * delta, function(x) rTrack(start = start + x, origin = origin + rnorm(2, sd = sd1), ...))) rTracksCollection <- function (p = 10, sd2 = 0, ...) TracksCollection(lapply(1:p, function(x) rTracks(origin = rnorm(2, sd = sd2), ...))) print.Track <- function(x,...){ X = x if (inherits(X@sp, "SpatialPoints")) { cat("An object of class Track \n"); cat(paste0(nrow(as.data.frame(X@sp)), "points"),"\n"); } if (inherits(X@sp, "SpatialLines")) { cat("A generalized object of class Track \n"); cat(paste0(length(X@sp@lines), "lines"),"\n"); } cat(paste0("bbox:"),"\n"); print(X@sp@bbox); cat(paste0("Time period: [",range(X@endTime)[1],", ", range(X@endTime)[2],"]")) } print.Tracks <- function(x, ...){ X = x cat("An object of class Tracks" ,"\n"); cat(paste0(length(X@tracks)), "tracks followed by a single object") } print.TracksCollection <- function(x, ...){ X = x cat("An object of class TracksCollection" ,"\n"); cat(paste0(length(X@tracksCollection)) , "collection of tracks followed by", paste0(length(X@tracksCollection)), " object") } <file_sep>/demo/google.R # read a file obtained by "Export to kml" from https://maps.google.com/locationhistory/ filename = system.file("history-06-09-2015.kml", package="trajectories") library(XML) kml <- xmlToList(filename) tr = kml$Document$Placemark$Track cc = which(names(tr) == "coord") coord = t(sapply(kml$Document$Placemark$Track[cc], function(x) scan(text = x, quiet = TRUE)))[,1:2] row.names(coord) = NULL # they are all duplicates when = which(names(tr) == "when") # convert the "-07:00" into " -0700" with sub: #time = strptime(sub("-08:00$", " -0800", unlist(kml$Document$Placemark$Track[when])), time = strptime(sub("([+\\-])(\\d\\d):(\\d\\d)$", "\\1\\2\\3", unlist(kml$Document$Placemark$Track[when])), "%Y-%m-%dT%H:%M:%OS %z") library(sp) library(spacetime) library(trajectories) track = Track(STI(SpatialPoints(coord, CRS("+proj=longlat +datum=WGS84")), time)) summary(track) head(as(track, "data.frame")) plot(track, axes = TRUE) # the following will try to read your complete Locationhistory JSON dump: library(jsonlite) system.time(x <- fromJSON("Location History/LocationHistory.json")$locations) object.size(x) sapply(x, class) x$time = as.POSIXct(as.numeric(x$timestampMs)/1000, origin = "1970-01-01") x$lat = x$latitudeE7 / 1e7 x$lon = x$longitudeE7 / 1e7 a = x$activitys types = unique(unlist(lapply(a, function(x) if (is.null(x[[2]])) "null" else x[[2]][[1]]$type))) types = types[types != "null"] # NULL entries getType = function(x, Type) { if (is.null(x)) as.numeric(NA) else { s = subset(x$activities[[1]], type == Type)$confidence if (length(s) == 0) s = 0.0 s[1] # there might be more than one, we're now ignoring all others! } } for (Tp in types) # untangle: x[[Tp]] = sapply(a, getType, Type = Tp) a = apply(x[,types], 1, function(x) if(all(is.na(x))) NA else which.max(x)) x$activity = factor(types[a]) x$confidence = apply(x[,types], 1, function(x) if(all(is.na(x))) NA else x[which.max(x)]) x$activitys = NULL # remove the complex list library(sp) loc.sp = x coordinates(loc.sp) = ~lon+lat proj4string(loc.sp) = CRS("+proj=longlat +datum=WGS84") library(spacetime) library(trajectories) tr = Track(STIDF(geometry(loc.sp), loc.sp$time, loc.sp@data)) <file_sep>/man/as.list.Tracks.Rd \name{as.list.Tracks} \alias{as.list.Tracks} %- Also NEED an '\alias' for EACH other topic documented here. \title{ as.list.Tracks %% ~~function to do ... ~~ } \description{ Convert a "Tracks" object to a list of tracks %% ~~ A concise (1-5 lines) description of what the function does. ~~ } \usage{ \method{as.list}{Tracks}(x,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "Tracks" %% ~~Describe \code{X} here~~ } \item{...}{passed to arguments of as.list} } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{rTrack}, \link{rTracks}, \link{rTracksCollection}, \link{as.list} } \examples{ x <- rTracks() as.list(x) } <file_sep>/R/stcube.R # Provide stcube methods. map3d = function(map, z, ...) { if (!requireNamespace("rgl", quietly = TRUE)) stop("rgl required") if(length(map$tiles) != 1) stop("Pass single map tile only.") nx = map$tiles[[1]]$xres ny = map$tiles[[1]]$yres xmin = map$tiles[[1]]$bbox$p1[1] xmax = map$tiles[[1]]$bbox$p2[1] ymin = map$tiles[[1]]$bbox$p1[2] ymax = map$tiles[[1]]$bbox$p2[2] xc = seq(xmin, xmax, len = ny) yc = seq(ymin, ymax, len = nx) col = matrix(data = map$tiles[[1]]$colorData, nrow = ny, ncol = nx) m = matrix(data = z, nrow = ny, ncol = nx) rgl::surface3d(x = xc, y = yc, z = m, col = col, lit = FALSE, ...) } normalize = function(time, by = "week") { tn = as.numeric(time) switch(by, minute = (tn %% 60), hour = (tn %% 3600) / 60 , # decimal minute of the hour day = (tn %% (3600 * 24)) / 3600, # decimal hour of the day week = (tn %% (3600 * 24 * 7)) / 24 / 3600, # decimal day of the week stop(paste("unknown value for by: ", by))) } OSM = function(xlim, ylim, mapZoom, mapType, projection) { if (!requireNamespace("OpenStreetMap", quietly = TRUE)) stop("package OpenStreetMap required") bboxSp <- SpatialPoints(rbind(c(xlim[1], ylim[2]), c(xlim[2], ylim[1]))) bboxSp@proj4string <- CRS(projection) bboxSp <- spTransform(bboxSp, CRS("+init=epsg:4326")) map = OpenStreetMap::openmap(upperLeft = bboxSp@coords[1,2:1], lowerRight = bboxSp@coords[2,2:1], zoom = mapZoom, type = mapType) OpenStreetMap::openproj(x = map, projection = projection) } if(!isGeneric("stcube")) setGeneric("stcube", function(x, ...) standardGeneric("stcube")) setMethod("stcube", signature(x = "Track"), function(x, xlab = "x", ylab = "y", zlab = "t", type = "l", aspect, xlim = stbox(x)[[1]] + c(-0.1,0.1) * diff(stbox(x)[[1]]), ylim = stbox(x)[[2]] + c(-0.1,0.1) * diff(stbox(x)[[2]]), zlim = stbox(x)$time, showMap = FALSE, mapType = "osm", mapZoom = NULL, ..., y, z) { # "y" and "z" are ignored, but added to avoid ... absorbs them if (!requireNamespace("rgl", quietly = TRUE)) stop("rgl required") coords = coordinates(x@sp) time = index(x@time) time <- time - min(time) # seconds from start if(missing(aspect)) aspect = if((asp = mapasp(x@sp)) == "iso") c(1, diff(ylim)/diff(xlim), 1) else c(1, asp, 1) if (missing(zlim)) zlim = range(time) rgl::plot3d(x = coords[, 1], y = coords[, 2], z = time, xlab = xlab, ylab = ylab, zlab = zlab, type = type, aspect = aspect, xlim = xlim, ylim = ylim, zlim = zlim, ...) if(showMap) map3d(map = OSM(xlim, ylim, mapZoom, mapType, proj4string(x)), z = time[1]) } ) setMethod("stcube", signature(x = "Tracks"), function(x, xlab = "x", ylab = "y", zlab = "t", type = "l", aspect, xlim = stbox(x)[[1]] + c(-0.1,0.1) * diff(stbox(x)[[1]]), ylim = stbox(x)[[2]] + c(-0.1,0.1) * diff(stbox(x)[[2]]), zlim = stbox(x)$time, showMap = FALSE, mapType = "osm", normalizeBy = "week", mapZoom = NULL, ..., y, z, col) { # "y" and "z" are ignored, but added to avoid ... absorbs them if (!requireNamespace("rgl", quietly = TRUE)) stop("rgl required") dim = dim(x@tracks[[1]])["geometries"] coordsAll = do.call(rbind, lapply(x@tracks, function(x) coordinates(x@sp))) timeAll = normalize(do.call(c, lapply(x@tracks, function(x) index(x@time))), normalizeBy) col = rainbow(length(x@tracks)) if(missing(aspect)) # mapasp() processes objects of class Spatial* only. aspect = if((asp = mapasp(as(x, "SpatialLines"))) == "iso") c(1, diff(ylim)/diff(xlim), 1) else c(1, asp, 1) if (missing(zlim)) zlim = range(timeAll) rgl::plot3d(x = coordsAll[1:dim, 1], y = coordsAll[1:dim, 2], z = timeAll[1:dim], xlab = xlab, ylab = ylab, zlab = zlab, type = type, col = col[1], aspect = aspect, xlim = xlim, ylim = ylim, zlim = zlim, ...) tracks = x@tracks[-1] for(t in seq_along(tracks)) { coords = coordinates(tracks[[t]]@sp) time = normalize(index(tracks[[t]]@time), normalizeBy) rgl::lines3d(x = coords[, 1], y = coords[, 2], z = time, col = col[t+1]) } if(showMap) map3d(map = OSM(xlim, ylim, mapZoom, mapType, proj4string(x)), z = timeAll[1]) } ) setMethod("stcube", signature(x = "TracksCollection"), function(x, xlab = "x", ylab = "y", zlab = "t", type = "l", aspect, xlim = stbox(x)[[1]] + c(-0.1,0.1) * diff(stbox(x)[[1]]), ylim = stbox(x)[[2]] + c(-0.1,0.1) * diff(stbox(x)[[2]]), zlim = stbox(x)$time, showMap = FALSE, mapType = "osm", normalizeBy = "week", mapZoom = NULL, ..., y, z, col) { # "y", "z" and "col" are ignored, but included in the method signature if (!requireNamespace("rgl", quietly = TRUE)) stop("rgl required") dim = dim(x@tracksCollection[[1]]@tracks[[1]])["geometries"] coordsAll = do.call(rbind, lapply(x@tracksCollection, function(x) do.call(rbind, lapply(x@tracks, function(y) coordinates(y@sp))))) timeAll = normalize(do.call(c, lapply(x@tracksCollection, function(x) do.call(c, lapply(x@tracks, function(y) index(y@time))))), normalizeBy) if (missing(col)) col = rainbow(length(x@tracksCollection)) if(missing(aspect)) # mapasp() processes objects of class Spatial* only. aspect = if((asp = mapasp(as(x, "SpatialLines"))) == "iso") c(1, diff(ylim)/diff(xlim), 1) else c(1, asp, 1) if (missing(zlim)) zlim = range(timeAll) rgl::plot3d(x = coordsAll[1:dim, 1], y = coordsAll[1:dim, 2], z = timeAll[1:dim], xlab = xlab, ylab = ylab, zlab = zlab, type = type, col = col[1], aspect = aspect, xlim = xlim, ylim = ylim, zlim = zlim, ...) for(tz in seq_along(x@tracksCollection)) { if(tz == 1) tracks = x@tracksCollection[[tz]]@tracks[-1] else tracks = x@tracksCollection[[tz]]@tracks for(t in seq_along(tracks)) { coords = coordinates(tracks[[t]]@sp) time = normalize(index(tracks[[t]]@time), normalizeBy) rgl::lines3d(x = coords[, 1], y = coords[, 2], z = time, col = col[tz]) } } if(showMap) map3d(map = OSM(xlim, ylim, mapZoom, mapType, proj4string(x)), z = timeAll[1]) } ) stcube.STI <- function(x, xlab = "x", ylab = "y", zlab = "t", type = "p", aspect, xlim = stbox(x)[[1]] + c(-0.1,0.1) * diff(stbox(x)[[1]]), ylim = stbox(x)[[2]] + c(-0.1,0.1) * diff(stbox(x)[[2]]), zlim = stbox(x)$time, showMap = FALSE, mapType = "osm", mapZoom = NULL, ..., y, z) { # "y" and "z" are ignored, but added to avoid ... absorbs them if (!requireNamespace("rgl", quietly = TRUE)) stop("rgl required") stopifnot(class(x@sp) %in% c("SpatialPoints", "SpatialPointsDataFrame")) # would also be nice for Lines coords = coordinates(x@sp) time = index(x@time) time <- time - min(time) # seconds from start if(missing(aspect)) aspect = if((asp = mapasp(x@sp)) == "iso") c(1, diff(ylim)/diff(xlim), 1) else c(1, asp, 1) if (missing(zlim)) zlim = range(time) rgl::open3d() rgl::plot3d(x = coords[, 1], y = coords[, 2], z = time, xlab = xlab, ylab = ylab, zlab = zlab, type = type, aspect = aspect, xlim = xlim, ylim = ylim, zlim = zlim, ...) if(showMap) map3d(map = OSM(xlim, ylim, mapZoom, mapType, proj4string(x)), z = time[1]) } stcube.STIDF <- function(x, xlab = "x", ylab = "y", zlab = "t", type = "p", aspect, xlim = stbox(x)[[1]] + c(-0.1,0.1) * diff(stbox(x)[[1]]), ylim = stbox(x)[[2]] + c(-0.1,0.1) * diff(stbox(x)[[2]]), zlim = stbox(x)$time, showMap = FALSE, mapType = "osm", mapZoom = NULL, col, ..., y, z) { time = index(x@time) time <- time - min(time) # seconds from start if (missing(zlim)) zlim = range(time) if(missing(col)) col <- heat.colors(10)[findInterval(x@data[,1], min(x@data[,1], na.rm = T)+0:9*(max(x@data[,1], na.rm = T) - min(x@data[,1], na.rm = T))/9)] stcube.STI(x, xlab, ylab, zlab, type, aspect, xlim, ylim, zlim, showMap, mapType, mapZoom, col, ...) } setMethod("stcube", signature(x = "STIDF"), stcube.STIDF) setMethod("stcube", signature(x = "STI"), stcube.STI)<file_sep>/man/tsqTracks.Rd \name{tsqTracks} \alias{tsqTracks} %- Also NEED an '\alias' for EACH other topic documented here. \title{ tsqTracks } \description{ tsqtracks returns a sequance of time based on a list of tracks (or a single object of class "Track"") and an argument timestamp. } \usage{ tsqTracks(X,timestamp) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{either an object of class "Track"" or a list of some objects of class "Track" %% ~~Describe \code{x} here~~ } \item{timestamp}{a timestamp to create the time sequence based on it} } \details{ This creates a sequence of time based on a track or a list of tracks. %% ~~ If necessary, more details than the description above ~~ } \value{ An object of class "POSIXct" or "POSIXt". } \author{ <NAME> <<EMAIL>>} %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ rTrack } \examples{ library(sp) library(spacetime) # t0 = as.POSIXct(as.Date("2013-09-30",tz="CET")) t0 = as.POSIXct("2013-09-30 02:00:00", tz = "Europe/Berlin") # person A, track 1: x = c(7,6,5,5,4,3,3) y = c(7,7,6,5,5,6,7) n = length(x) set.seed(131) t = t0 + cumsum(runif(n) * 60) crs = CRS("+proj=longlat +datum=WGS84") # longlat stidf = STIDF(SpatialPoints(cbind(x,y),crs), t, data.frame(co2 = rnorm(n))) A1 = Track(stidf) tsqTracks(A1,timestamp = "1 sec") } <file_sep>/man/frechetDist.Rd \name{frechetDist} \docType{methods} \alias{frechetDist} \alias{frechetDist,Track-method} \title{Frechet distance} \description{ Compute the discrete Frechet distance between two \code{Track} objects. } \usage{% \S4method{frechetDist}{Track}(track1, track2) } \arguments{ \item{track1}{An object of class \code{Track}.} \item{track2}{An object of class \code{Track}.} } \value{Discrete Frechet distance.} \references{ http://en.wikipedia.org/wiki/Fr\'echet_distance } \author{ <NAME> <<EMAIL>> } \keyword{methods} <file_sep>/man/avemove.Rd \name{avemove} \alias{avemove} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Average movement of trajectory pattern } \description{ This returns the average movements of a lits of objects of class "Track" over time. } \usage{ avemove(X,timestamp,epsilon=epsilon) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{a list of some objects of class Track %% ~~Describe \code{x} here~~ } \item{timestamp}{timestamp to calculate the pairwise distances between tarcks} \item{epsilon}{(optional) movements with length less than epsilon are not considered in the calculation} } \details{ when analysying a list of tracks, avemove calculate the average of movements based on given timestamp.} \value{ an object of class "numeric" or "arwlen". } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{as.Track.arrow} } \examples{ if (require(spatstat.geom)) { X <- list() for(i in 1:10){ m <- matrix(c(0,10,0,10),nrow=2,byrow = TRUE) X[[i]] <- rTrack(bbox = m,transform = TRUE) } avemove(X,timestamp = "30 secs") } } <file_sep>/man/stcube.Rd \name{stcube} \alias{stcube} \alias{stcube,STI-method} \alias{stcube,STIDF-method} \alias{stcube,Track-method} \alias{stcube,Tracks-method} \alias{stcube,TracksCollection-method} \alias{stcube,difftrack-method} \title{Draw a space-time cube.} \description{Draw a space-time cube for a Track, TRacks, TracksCollection, difftrack or STI(DF) class.} \usage{% \S4method{stcube}{Track}(x, xlab = "x", ylab = "y", zlab = "t", type = "l", aspect, xlim = stbox(x)[[1]] + c(-0.1,0.1) * diff(stbox(x)[[1]]), ylim = stbox(x)[[2]] + c(-0.1,0.1) * diff(stbox(x)[[2]]), zlim = stbox(x)$time, showMap = FALSE, mapType = "osm", mapZoom = NULL, ..., y, z) \S4method{stcube}{Tracks}(x, xlab = "x", ylab = "y", zlab = "t", type = "l", aspect, xlim, ylim, zlim, showMap = FALSE, mapType = "osm", normalizeBy = "week", mapZoom = NULL, ..., y, z, col) \S4method{stcube}{TracksCollection}(x, xlab = "x", ylab = "y", zlab = "t", type = "l", aspect, xlim, ylim, zlim, showMap = FALSE, mapType = "osm", normalizeBy = "week", mapZoom = NULL, ..., y, z, col) \S4method{stcube}{difftrack}(x, showMap = FALSE, mapType = "osm", normalizeBy = "week", ..., y, z) \S4method{stcube}{STI}(x, xlab = "x", ylab = "y", zlab = "t", type = "p", aspect, xlim = stbox(x)[[1]] + c(-0.1,0.1) * diff(stbox(x)[[1]]), ylim = stbox(x)[[2]] + c(-0.1,0.1) * diff(stbox(x)[[2]]), zlim = stbox(x)$time, showMap = FALSE, mapType = "osm", mapZoom = NULL, ..., y, z) \S4method{stcube}{STIDF}(x, xlab = "x", ylab = "y", zlab = "t", type = "p", aspect, xlim = stbox(x)[[1]] + c(-0.1,0.1) * diff(stbox(x)[[1]]), ylim = stbox(x)[[2]] + c(-0.1,0.1) * diff(stbox(x)[[2]]), zlim = stbox(x)$time, showMap = FALSE, mapType = "osm", mapZoom = NULL, col, ..., y, z)} \arguments{ \item{x}{An object of class \code{Track}, \code{Tracks}, or \code{TracksCollection} or \code{difftrack}.} \item{xlab, ylab, zlab, type, aspect, xlim, ylim, zlim}{Arguments passed to plot3d() of package \code{rgl}.} \item{showMap}{Flag if a basemap is to be shown on the xy plane; for this to function, you may need to load library \code{raster} first, see also the \code{stcube} demo script.} \item{mapType}{The tile server from which to get the map. Passed as \code{type} to openmap() of package \code{OpenStreetMap}.} \item{normalizeBy}{An abstract time period (either \code{week} or \code{day}) to be normalized by.} \item{mapZoom}{Set a zoom level for the map used as background. Null will use the osm package default strategie.} \item{y, z, col}{Ignored, but included in the method signature for implementation reasons.} \item{...}{Additional arguments passed to plot3d() of package \code{rgl}.}} \value{A space-time cube.} \examples{ \dontrun{demo(stcube)} } \keyword{space-time cube} <file_sep>/R/Trackstat.R as.list.Tracks <- function(x,...){ stopifnot(inherits(x, "Tracks")) return(as.list(x@tracks,...)) } as.list.TracksCollection <- function(x,...){ stopifnot(inherits(x, "TracksCollection")) out <- lapply(X=1:length(x@tracksCollection), function(i){ as.list.Tracks(x@tracksCollection[[i]],...) }) return(unlist(out, recursive=FALSE)) } as.Track <- function(x,y,t,covariate){ stopifnot(length(x)>0 | length(y)>0 | length(t)>0) sp <- cbind(x,y) sp <- SpatialPoints(sp) td <- as.POSIXct(t) if(missing(covariate)) covariate <- data.frame(d=rep(1,length(x))) return(Track(STIDF(sp,time = td,data =covariate))) } # function reTrack accepts X as an object of class Track. Output is a reconstructed Track (an object of class Track), based on "timestamp". # It only returns the interpolated points. reTrack <- function(X,at=c("track","dfrm"),timestamp=timestamp,tsq=NULL){ if (missing(tsq)) tsq <- tsqTracks(X,timestamp = timestamp) if(missing(at)) at <- "track" Xrange <- range.Track(X) X <- cbind(as.data.frame(X)[c(coordnames(X), "time")]) xnew <- c() ynew <- c() x <- X$x y <- X$y time <- tsq[tsq<Xrange[2] & tsq>Xrange[1]] ivs <- findInterval(time,X$time) for (i in 1:length(ivs)) { if (!ivs[i] == 0 && !ivs[i] == nrow(X)) { iv <- ivs[i] tdiff1 <- difftime(time[i],X$time[iv],units = "sec") # diff between timestamp and start of the interval it falls in tdiff2 <- difftime(X$time[iv+1],X$time[iv],units = units(tdiff1)) # diff between timestamps (calculated here because it often varies) ratio <- as.numeric(tdiff1)/as.numeric(tdiff2) x1 <- X[iv,1] # segment coordinates y1 <- X[iv,2] x2 <- X[iv+1,1] y2 <- X[iv+1,2] xnew <- c(xnew, x1 + ratio * (x2 - x1)) #find point ynew <- c(ynew, y1 + ratio * (y2 - y1)) } } newTrack <- data.frame(xnew, ynew, time) newTrack <- newTrack[!duplicated(newTrack),] # remove duplicates newTrack <- newTrack[order(newTrack$time),] # sort by timestamp colnames(newTrack) <- c("xcoor","ycoor","time") if (at=="dfrm") {attr(newTrack,"tsq") <-tsq;return(newTrack) } return(as.Track(newTrack[,1],newTrack[,2],newTrack[,3])) } # range.Track returns the timerange of an object of class Track range.Track <- function(X,...) { Y <- cbind(as.data.frame(X)[c(coordnames(X), "time")]) return(range(Y$time,...)) } # tsqtracks returns a sequance of time based on a list of tracks (or a single object of class Track) and an argument timestamp tsqTracks <- function(X, timestamp){ timerange = if (is.list(X)) lapply(X, range.Track) else range.Track(X) Trackrg <- range(timerange) class(Trackrg) <- c('POSIXt','POSIXct') # a seq from the range has been created every timestamp timeseq <- seq(from=as.POSIXct(strftime(Trackrg[1])),to=as.POSIXct(strftime(Trackrg[2])),by = timestamp) return(timeseq) } # function avedistTrack accepts X as a list of tracks and reports the average distance between # tracks over time, output is an object of class "distrack" avedistTrack <- function(X,timestamp){ stopifnot(is.list(X) || inherits(X, c("Tracks", "TracksCollection"))) if(inherits(X, "Tracks")) X <- as.list.Tracks(X) if (inherits(X, "TracksCollection")) X <- as.list.TracksCollection(X) stopifnot(length(X)>1 & is.list(X)) if (!requireNamespace("spatstat.geom", quietly = TRUE)) stop("spatstat.geom required: install first?") if (missing(timestamp)) stop("set timestamp") # calculate a sequance of time to interpolate tracks within this sequance timeseq <- tsqTracks(X,timestamp = timestamp) Y <- as.Track.ppp(X,timestamp) avedist <- lapply(X=1:length(Y), function(i){ pd <- spatstat.geom::pairdist(Y[[i]]) mean(pd[pd>0]) }) avedist <- unlist(avedist) class(avedist) <- c("distrack","numeric") attr(avedist,"ppp") <- Y attr(avedist,"tsq") <- attr(Y,"tsq") return(avedist) } print.distrack <- function(x, ...){ print(as.vector(x), ...) } plot.distrack <- function(x,...){ x = unclass(x) plot(attr(x,"tsq"), x, xlab="time",ylab="average distance",...) } unique.Track <- function(x,...){ x <- cbind(as.data.frame(x)[c(coordnames(x), "time")]) x <- unique(x,...) return(as.Track(x[,1],x[,2],x[,3])) } as.Track.ppp <- function(X,timestamp){ stopifnot(is.list(X) || inherits(X, c("Tracks", "TracksCollection"))) if(inherits(X, "Tracks")) X <- as.list.Tracks(X) if (inherits(X, "TracksCollection")) X <- as.list.TracksCollection(X) stopifnot(length(X)>1 & is.list(X)) if (!requireNamespace("spatstat.geom", quietly = TRUE)) stop("spatstat.geom required: install first?") if (missing(timestamp)) stop("set timestamp") # calculate a sequance of time to interpolate tracks within this sequance timeseq <- tsqTracks(X,timestamp = timestamp) # reconstruct tracks in sequance timeseq Z <- lapply(X,reTrack,tsq = timeseq,at="dfrm") id <- rep(1:length(Z),sapply(Z, nrow)) Z <- do.call("rbind",Z) Z <- cbind(Z,id) allZ <- split(Z,Z[,3]) dx <- (max(Z$xcoor)-min(Z$xcoor))/1000 dy <- (max(Z$ycoor)-min(Z$ycoor))/1000 w <- spatstat.geom::owin(c(min(Z$xcoor)-dx,max(Z$xcoor)+dx),c(min(Z$ycoor)-dy,max(Z$ycoor)+dy)) Tppp <- lapply(X=1:length(allZ), function(i){ p <- spatstat.geom::as.ppp(allZ[[i]][,-c(3,4)],W=w) p <- spatstat.geom::`marks<-`(p, value = allZ[[i]][,4]) return(p) }) class(Tppp) <- c("list","ppplist") attr(Tppp,"tsq") <- as.POSIXlt.character(attributes(allZ)$names) return(Tppp) } print.ppplist <- function(x,...){ attributes(x) <- NULL print(x, ...) } density.list <- function(x, timestamp, ...) { stopifnot(is.list(x) || inherits(x, c("Tracks", "TracksCollection"))) if (inherits(x, "Tracks")) x <- as.list.Tracks(x) if (inherits(x, "TracksCollection")) x <- as.list.TracksCollection(x) stopifnot(length(x)>1 & is.list(x)) if (!requireNamespace("spatstat.explore", quietly = TRUE)) stop("spatstat.explore required: install first?") if (missing(timestamp)) stop("set timestamp") p <- as.Track.ppp(x, timestamp) p <- p[!sapply(p, is.null)] imlist <- lapply(p, spatstat.explore::density.ppp, ...) out <- Reduce("+", imlist) / length(imlist) attr(out, "Tracksim") <- imlist attr(out, "ppps") <- p return(out) } as.Track.arrow <- function(X,timestamp,epsilon=epsilon){ stopifnot(is.list(X) || inherits(X, c("Tracks", "TracksCollection"))) if(inherits(X, "Tracks")) X <- as.list.Tracks(X) if (inherits(X, "TracksCollection")) X <- as.list.TracksCollection(X) stopifnot(length(X)>1 & is.list(X)) if (!requireNamespace("spatstat.geom", quietly = TRUE)) stop("spatstat.geom required: install first?") if (missing(timestamp)) stop("set timestamp") if(missing(epsilon)) epsilon <- 0 Z <- as.Track.ppp(X,timestamp) tsq <- attr(Z,"tsq") Z <- Z[!sapply(Z, is.null)] wind <- Z[[1]]$window arrows <- list() Y <- list() for (i in 1:length(Z)) { if(i==length(Z)) break() j <- i+1 m1 <- match(spatstat.geom::marks(Z[[i]]),spatstat.geom::marks(Z[[j]])) m2 <- match(spatstat.geom::marks(Z[[j]]),spatstat.geom::marks(Z[[i]])) m1 <- m1[!is.na(m1)] m2 <- m2[!is.na(m2)] x <- Z[[j]][m1] y <- Z[[i]][m2] l <- spatstat.geom::psp(y$x,y$y,x$x,x$y,window = wind) arrows[[i]] <- l center <- spatstat.geom::midpoints.psp(l) mark <- spatstat.geom::lengths_psp(l) center <- spatstat.geom::`marks<-`(center, value = mark) if (missing(epsilon)) epsilon <- 0 Y[[i]] <- center[mark>epsilon] } class(Y) <- c("list","Trrow") attr(Y, "psp") <- arrows attr(Y,"time") <- tsq[-length(tsq)] return(Y) } print.Trrow <- function(x, ...) { attributes(x) <- NULL print(x, ...) } Track.idw <- function(X,timestamp,epsilon=epsilon,...){ stopifnot(is.list(X) || inherits(X, c("Tracks", "TracksCollection"))) if(inherits(X, "Tracks")) X <- as.list.Tracks(X) if (inherits(X, "TracksCollection")) X <- as.list.TracksCollection(X) stopifnot(length(X)>1 & is.list(X)) if (missing(timestamp)) stop("set timestamp") if(missing(epsilon)) epsilon <- 0 Y <- as.Track.arrow(X,timestamp,epsilon=epsilon) Z <- lapply(Y, spatstat.explore::idw, ...) meanIDW <- Reduce("+",Z)/length(Z) return(meanIDW) } avemove <- function(X,timestamp,epsilon=epsilon){ stopifnot(is.list(X) || inherits(X, c("Tracks", "TracksCollection"))) if (inherits(X, "Tracks")) X <- as.list.Tracks(X) if (inherits(X, "TracksCollection")) X <- as.list.TracksCollection(X) stopifnot(length(X)>1 & is.list(X)) if (!requireNamespace("spatstat.geom", quietly = TRUE)) stop("spatstat.geom required: install first?") if (missing(timestamp)) stop("set timestamp") timeseq <- tsqTracks(X,timestamp = timestamp) if (missing(epsilon)) epsilon <- 0 Y <- as.Track.arrow(X,timestamp,epsilon=epsilon) Z <- attr(Y,"psp") preout <- lapply(X=1:length(Z), function(i){ mean(spatstat.geom::lengths_psp(Z[[i]])) }) out <- unlist(preout) class(out) <- c("numeric", "arwlen") attr(out,"time") <- attr(Y,"time") return(out) } print.arwlen <- function(x, ...){ print(as.vector(x), ...) } plot.arwlen <- function(x,...){ if (!requireNamespace("spatstat.geom", quietly = TRUE)) stop("spatstat.geom required: install first?") x = unclass(x) tsq <- attr(x,"time") plot(tsq,x,xlab="time",ylab="average movement",...) } chimaps <- function(X,timestamp,rank,...){ stopifnot(is.list(X) || inherits(X, c("Tracks","TracksCollection"))) if(inherits(X, "Tracks")) X <- as.list.Tracks(X) if (inherits(X, "TracksCollection")) X <- as.list.TracksCollection(X) stopifnot(length(X)>1 & is.list(X)) if (!requireNamespace("spatstat.geom", quietly = TRUE)) stop("spatstat.geom required: install first?") if(missing(rank)) rank <- 1 if (!is.numeric(rank)) stop("rank must be numeric") if (rank < 1 | rank >length(X)) stop("rank must be number between one and the number of Tracks") stopifnot(length(X)>1 & is.list(X)) if (missing(timestamp)) stop("set timestamp") timeseq <- tsqTracks(X,timestamp = timestamp) d <- density.list(X, timestamp = timestamp,...) imlist <- attr(d,"Tracksim") sumim <- Reduce("+",imlist) chi <- lapply(X=1:length(imlist),FUN = function(i){ E1 <- sumim*sum(imlist[[i]]$v)/(sum(sumim$v)) return((imlist[[i]]-E1)/sqrt(E1)) }) out <- chi[[rank]] attr(out,"ims") <- chi attr(out,"time") <- timeseq[rank] attr(out,"timevec") <- timeseq return(out) } Kinhom.Track <- function(X,timestamp, correction=c("border", "bord.modif", "isotropic", "translate"),q, sigma=c("default","bw.diggle","bw.ppl"," bw.scott"),...){ stopifnot(is.list(X) || inherits(X, c("Tracks", "TracksCollection"))) if (inherits(X, "Tracks")) X <- as.list.Tracks(X) if (inherits(X, "TracksCollection")) X <- as.list.TracksCollection(X) if (!requireNamespace("spatstat.explore", quietly = TRUE)) stop("spatstat.explore required: install first?") stopifnot(length(X)>1 & is.list(X)) if (missing(timestamp)) stop("set timestamp") if (missing(q)) q <- 0 cor <- match.arg(correction,correction) bw <- match.arg(sigma,sigma) if (bw == "default") { Y <- as.Track.ppp(X,timestamp = timestamp) W <- Y[[1]]$window ripley <- min(diff(W$xrange), diff(W$yrange))/4 rr <- seq(0,ripley,length.out = 513) K <- lapply(X=1:length(Y), function(i){ kk <- spatstat.explore::Kinhom(Y[[i]],correction=cor,r=rr,...) return(as.data.frame(kk)) }) Kmat <- matrix(nrow = length(K[[1]]$theo),ncol = length(K)) for (i in 1:length(K)) { Kmat[,i] <- K[[i]][,3] } } else{ bw <- match.fun(bw) ZZ <- density.list(X, timestamp = timestamp, bw) Z <- attr(ZZ,"Tracksim") Y <- attr(ZZ,"ppps") W <- Y[[1]]$window ripley <- min(diff(W$xrange), diff(W$yrange))/4 rr <- seq(0,ripley,length.out = 513) K <- lapply(X=1:length(Y), function(i){ kk <- spatstat.explore::Kinhom(Y[[i]],lambda = Z[[i]],correction=cor,r=rr,...) return(as.data.frame(kk)) }) Kmat <- matrix(nrow = length(K[[1]]$theo),ncol = length(K)) for (i in 1:length(K)) { Kmat[,i] <- K[[i]][,3] } } # Kmat <- as.data.frame(K) lowk <- numeric() upk <- numeric() avek <- numeric() for (i in 1:nrow(Kmat)) { avek[i] <- mean(Kmat[i,],na.rm = TRUE) lowk[i] <- quantile(Kmat[i,],q,na.rm = TRUE) upk[i] <- quantile(Kmat[i,],1-q,na.rm = TRUE) } out <- data.frame(lowk=lowk,upk=upk,avek=avek,r=K[[1]]$r,theo=K[[1]]$theo) class(out) <- c("list","KTrack") attr(out,"out") <- out return(out) } print.KTrack <- function(x, ...){ print("variability area of K-function", ...) } plot.KTrack <- function(x,type="l",col= "grey70",cex=1,line=2.2,...){ if (!requireNamespace("spatstat.geom", quietly = TRUE)) stop("spatstat.geom required: install first?") ylim <- c(min(c(x$lowk,x$theo)),max(c(x$upk,x$theo))) plot(x$r,x$lowk,ylim=ylim,type=type,ylab="",xlab="r",...) title(ylab=expression(K[inhom](r)),line = line,...) points(x$r,x$upk,type=type) polygon(c(x$r, rev(x$r)), c(x$upk, rev(x$lowk)), col = col, border = NA) points(x$r,x$theo,type=type,col=2) points(x$r,x$avek,type=type) legend(0,max(c(x$upk,x$theo)),col = c(2,0,1), legend=c(expression(K[inhom]^{pois}),"",expression(bar(K)[inhom])), lty=c(1,1),cex = cex) } pcfinhom.Track <- function(X,timestamp, correction = c("translate", "Ripley"), q, sigma=c("default", "bw.diggle", "bw.ppl", "bw.scott"), ...) { stopifnot(is.list(X) || inherits(X, c("Tracks", "TracksCollection"))) if (inherits(X, "Tracks")) X <- as.list.Tracks(X) if (inherits(X, "TracksCollection")) X <- as.list.TracksCollection(X) if (!requireNamespace("spatstat.explore", quietly = TRUE)) stop("spatstat.explore required: install first?") stopifnot(length(X)>1 & is.list(X)) if (missing(timestamp)) stop("set timestamp") if (missing(q)) q <- 0 cor <- match.arg(correction,correction) bw <- match.arg(sigma,sigma) if (bw == "default"){ Y <- as.Track.ppp(X,timestamp = timestamp) W <- Y[[1]]$window ripley <- min(diff(W$xrange), diff(W$yrange))/4 rr <- seq(0,ripley,length.out = 513) g <- lapply(X=1:length(Y), function(i){ gg <- spatstat.explore::pcfinhom(Y[[i]],correction=cor,r=rr,...) return(as.data.frame(gg)) }) gmat <- matrix(nrow = length(g[[1]]$theo),ncol = length(g)) for (i in 1:length(g)) { gmat[,i] <- g[[i]][,3] } } else { bw <- match.fun(bw) ZZ <- density.list(X, timestamp = timestamp, bw) Z <- attr(ZZ,"Tracksim") Y <- attr(ZZ,"ppps") g <- lapply(X=1:length(Y), function(i){ gg <- spatstat.explore::pcfinhom(Y[[i]],lambda = Z[[i]],correction=cor,...) return(as.data.frame(gg)) }) gmat <- matrix(nrow = length(g[[1]]$theo),ncol = length(g)) for (i in 1:length(g)) { gmat[,i] <- g[[i]][,3] } } gmat <- gmat[-1,] lowg <- numeric() upg <- numeric() aveg <- numeric() for (i in 1:nrow(gmat)) { aveg[i] <- mean(gmat[i,],na.rm = TRUE) lowg[i] <- quantile(gmat[i,],q,na.rm = TRUE) upg[i] <- quantile(gmat[i,],1-q,na.rm = TRUE) } out <- data.frame(lowg=lowg,upg=upg,aveg=aveg,r=g[[1]]$r[-1],theo=g[[1]]$theo[-1]) class(out) <- c("list","gTrack") attr(out,"out") <- out return(out) } print.gTrack <- function(x, ...){ print("variability area of pair correlatio function", ...) } plot.gTrack <- function(x,type="l",col= "grey70",cex=1,line=2.2,...){ if (!requireNamespace("spatstat.geom", quietly = TRUE)) stop("spatstat.geom required: install first?") ylim <- c(min(x$lowg),max(x$upg)) plot(x$r,x$lowg,ylim=ylim,xlab="r",ylab="",type=type,...) title(ylab=expression(g[inhom](r)),line = line,...) points(x$r,x$upg,type=type) polygon(c(x$r, rev(x$r)), c(x$upg, rev(x$lowg)), col = col, border = NA) points(x$r,x$theo,type=type,col=2) points(x$r,x$aveg,type=type) legend(0.01*max(x$r),max(x$upg),col = c(2,0,1), legend=c(expression(g[inhom]^{pois}),"", expression(bar(g)[inhom])), lty=c(1,1),cex=cex) } auto.arima.Track <- function(X,...){ if (! requireNamespace("forecast", quietly = TRUE)) stop("package forecast required, please install it first") stopifnot(inherits(X, "Track")) xseries <- coordinates(X)[,1] yseries <- coordinates(X)[,2] xfit <- forecast::auto.arima(xseries,...) yfit <- forecast::auto.arima(yseries,...) out <- list(xfit,yfit) attr(out,"models") <- out class(out) <- c("ArimaTrack") return(out) } print.ArimaTrack <- function(x, ...){ attributes(x) <- NULL cat("Arima model fitted to x-coordinate: "); cat(paste0(x[[1]]),"\n") cat("Arima model fitted to y-coordinate: "); cat(paste0(x[[2]])) } <file_sep>/man/plot.arwlen.Rd \name{plot.arwlen} \alias{plot.arwlen} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "arwlen" } \description{ Methods for class "arwlen" } \usage{ \method{plot}{arwlen}(x, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "arwlen"} \item{...}{ passed on to plot} } \value{ a plot. } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{avemove} <file_sep>/man/plot.distrack.Rd \name{plot.distrack} \alias{plot.distrack} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "distrack" } \description{ The plot method for "distrack" objects. } \usage{ \method{plot}{distrack}(x, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "distrack" } \item{...}{ ignored } } \details{ This plots an object of class "distrack". } \author{ <NAME> <<EMAIL>> } <file_sep>/man/print.Tracks.Rd \name{print.Tracks} \alias{print.Tracks} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "Tracks" } \description{ method to print an object of class "Tracks"} \usage{ \method{print}{Tracks}(x,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "Tracks" } \item{...}{ ignored } } \author{ <NAME> <<EMAIL>> } <file_sep>/man/print.ppplist.Rd \name{print.ppplist} \alias{print.ppplist} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "Track" } \description{ method to print an object of class "ppplist"} \usage{ \method{print}{ppplist}(x,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "ppplist" } \item{...}{ ignored} } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ <file_sep>/man/plot.KTrack.Rd \name{plot.KTrack} \alias{plot.KTrack} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "KTrack" } \description{ Methods for class "KTrack" } \usage{ \method{plot}{KTrack}(x, type = "l", col = "grey70",cex=1,line=2.2, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{an object of class KTrack} \item{type}{ line type} \item{col}{ color} \item{cex}{used for size of legend} \item{line}{specifying a value for line overrides the default placement of labels, and places them this many lines outwards from the plot edge} \item{...}{ passed on to plot} } \details{ plotting the variability area of K-function of a list of tracks.} \value{ a plot. } \author{ <NAME> <<EMAIL>> } <file_sep>/man/storms.Rd \name{storms} \alias{storms} \title{Storm trajectories} \description{storm trajectories, 2009-2012, from http://weather.unisys.com/hurricane/atlantic/} \usage{ data(storms) } \keyword{datasets} \examples{ data(storms) dim(storms) plot(storms) x = approxTracksCollection(storms, by = "30 min", FUN = spline) plot(x, col = 'red', add = TRUE) \dontrun{ demo(storms) # regenerates these data from their source } } <file_sep>/demo/stcube.R library(spacetime) if (!requireNamespace("enviroCaR", quietly = TRUE)) { # Import enviroCar track. importEnviroCar = function(trackID, url = "https://envirocar.org/api/stable/tracks/") { require(RCurl) require(rgdal) require(rjson) url = getURL(paste(url, trackID, sep = ""), .opts = list(ssl.verifypeer = FALSE)) # Read data into spatial object. spdf = readOGR(dsn = url, layer = "OGRGeoJSON", verbose = FALSE) # Convert time from factor to POSIXct. time = as.POSIXct(spdf$time) # Convert phenomena from JSON to data frame. phenomena = lapply(as.character(spdf$phenomenons), fromJSON) values = lapply(phenomena, function(x) as.data.frame(lapply(x, function(y) y$value))) # Get a list of all phenomena for which values exist. names = vector() for(i in values) names = union(names, names(i)) # Make sure that each data frame has the same number of columns. values = lapply(values, function(x) { xNames = names(x) # Get the symmetric difference. diff = setdiff(union(names, xNames), intersect(names, xNames)) if(length(diff) > 0) x[diff] = NA x }) # Bind values together. data = do.call(rbind, values) sp = SpatialPoints(coords = coordinates(spdf), proj4string = CRS("+proj=longlat +datum=WGS84")) stidf = STIDF(sp = sp, time = time, data = data) Track(track = stidf) } A1 = importEnviroCar("528cf1a3e4b0a727145df093") A2 = importEnviroCar("528cf19ae4b0a727145deb40") A3 = importEnviroCar("528cf194e4b0a727145de63d") A = Tracks(tracks = list(A1, A2)) B = Tracks(tracks = list(A3)) Tr = TracksCollection(tracksCollection = list(A, B)) } else { A1 = enviroCaR::importEnviroCar("https://envirocar.org/api/stable/", "528cf1a3e4b0a727145df093") A2 = enviroCaR::importEnviroCar("https://envirocar.org/api/stable/", "528cf19ae4b0a727145deb40") A3 = enviroCaR::importEnviroCar("https://envirocar.org/api/stable/", "528cf194e4b0a727145de63d") A = Tracks(tracks = list(A1@tracksCollection$Tracks1@tracks$Track1, A2@tracksCollection$Tracks1@tracks$Track1)) B = Tracks(tracks = list(A3@tracksCollection$Tracks1@tracks$Track1)) Tr = TracksCollection(tracksCollection = list(A, B)) } # Plot tracks in a space-time cube. As fetching the basemap takes its time, # "showMap" defaults to FALSE. See ?stcube for detailed information. stcube(A, showMap = FALSE) stcube(B, showMap = TRUE) stcube(Tr, showMap = TRUE) <file_sep>/man/chimaps.Rd \name{chimaps} \alias{chimaps} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Chimaps of tarjectory pattern. } \description{ Computes the chimaps, corresponding to a list of objects of class "Track". chimaps are based on the discrepancy between computed and expected intensity in a given location.} \usage{ chimaps(X,timestamp,rank,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ A list of Track objects } \item{timestamp}{based on secs,mins,...} \item{rank}{a number between one and the length of corresponding time sequance which is created based on given timestamp.} \item{...}{passed to arguments of density.Track} } \details{ [estimated intensity - expected intensity] / sqrt(expected intensity). } \value{ an image of class "im". } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{density.list}, \link[spatstat.explore]{density.ppp} } \examples{ if (require(spatstat.geom)) { X <- list() for(i in 1:10){ m <- matrix(c(0,10,0,10),nrow=2,byrow = TRUE) X[[i]] <- rTrack(bbox = m,transform = TRUE) } chimaps(X, timestamp = "180 secs",rank = 2) } } <file_sep>/demo/Geolife.R ## ------------------------------------------------------------------------ # Geolife trajectories, # documentation: http://research.microsoft.com/apps/pubs/?id=152176 : # data: http://research.microsoft.com/en-us/projects/geolife/ # or http://ftp.research.microsoft.com/downloads/b16d359d-d164-469e-9fd4-daa38f2b2e13/Geolife%20Trajectories%201.2.zip # assuming we are in the "Data" directory, e.g. by: # setwd("/home/edzer/Downloads/Geolife Trajectories 1.3/Data/") library(sp) library(spacetime) library(trajectories) #sel = 1:20 sel = IDS = c("079", "095", "111", "127", "143", "159", "175") i = j = 1 # dirs = list.files("Data") dirs = sel crs = CRS("+proj=longlat +datum=WGS84") pb = txtProgressBar(style = 3, max = length(dirs)) elev = numeric(0) tr = list() for (d in dirs) { dir = paste(d, "Trajectory", sep = "/") #print(dir) lst = list() i = 1 for (f in list.files(dir, pattern = "*plt", full.names = TRUE)) { tab = read.csv(f, skip = 6, stringsAsFactors=FALSE) tab$time = as.POSIXct(paste(tab[,6],tab[,7])) tab[tab[,4] == -777, 4] = NA # altitude tab = tab[,-c(3,5,6,7)] names(tab) = c("lat", "long", "elev", "time") tab = na.omit(tab) dup = duplicated(tab["time"]) if (any(dup)) tab = tab[-dup,] tab = tab[c(TRUE, diff(tab$time) != 0),] if (all(tab$lat > -90 & tab$lat < 90 & tab$long < 360 & tab$long > -180) && nrow(tab) > 1) { lst[[i]] = Track(STIDF(SpatialPoints(tab[,2:1], crs), tab$time, data.frame(elev=elev))) i = i+1 } } if (length(lst) > 0) { tr[[j]] = Tracks(lst) j = j+1 } setTxtProgressBar(pb, j) } tc = TracksCollection(tr) object.size(tc) dim(tc) object.size(tr) plot(tc, xlim=c(116.3,116.5),ylim=c(39.8,40)) stplot(tc, xlim=c(116.3,116.5),ylim=c(39.8,40), col = 1:20) <file_sep>/demo/citibikenyc.R # https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip # x = read.csv(unz("201307-citibike-tripdata.zip", "2013-07 - Citi Bike trip data.csv")) library(sp) library(spacetime) library(trajectories) readCBN = function(year = 2013, month = 7) { url = "https://s3.amazonaws.com/tripdata/" f = "-citibike-tripdata.zip" tmp = "CBNTMPxxx.zip" res = NULL for (y in year) { for (m in month) { if (m < 10) m = paste("0", m, sep = "") fname = paste(url, year, m, f, sep = "") download.file(fname, tmp, "wget") csvname = paste(y, "-", m, " - Citi Bike trip data.csv", sep = "") x = read.csv(unz(tmp, csvname)) x$starttime = as.POSIXct(x$starttime) x$stoptime = as.POSIXct(x$stoptime) x$birth.year = as.numeric(as.character(x$birth.year)) x$gender = factor(x$gender, labels = c("unknown", "male", "female")) if (is.null(res)) res = x else res = rbind(res, x) } } res } toTrackLst = function(x) { lapply(1:nrow(x), function(i) { if (i %% 100 == 0) print(i) start = cbind(x[i,"start.station.longitude"], x[i,"start.station.latitude"]) end = cbind(x[i,"end.station.longitude"], x[i,"end.station.latitude"]) pt = SpatialPoints(rbind(start, end), CRS("+proj=longlat +datum=WGS84 +datum=WGS84")) Track(STIDF(pt, c(x[i,"starttime"], x[i,"stoptime"]), data.frame(id=c(x[i,"start.station.id"], x[i,"end.station.id"])))) }) } x = readCBN() trj = Tracks(toTrackLst(x[1:10,])) <file_sep>/man/reTrack.Rd \name{reTrack} \alias{reTrack} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Reconstruct objects of class "Track" } \description{ Function reTrack accepts X as an object of class "Track". Output is a reconstructed Track (again an object of class Track), based on a regular "timestamp". It only returns the interpolated points. } \usage{ reTrack(X,at=c("track","dfrm"),timestamp=timestamp,tsq=NULL) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ an object of class Track } \item{at}{ to set the type of output as either an object of class "Track" or data.frame } \item{timestamp}{ timestamp which Track be reconstructed based on } \item{tsq}{ a time sequence to reconstruct Track X based on it. This is optional. If this is not given, the function creates the time sequance based on timestamp. } } \details{ Sometimes tracks data are not collected according to a regular timestamp. In order to compare different tracks which share some time intervals, we might need to be aware of the locations in a regular timestamp. Function reTrack unables us to reconstruct an object of class "Track" based on a regular timestamp. Time sequance can be given by user, if not reTrack creates a regulare time sequance based on the given timestamp. } \value{ Either an object of class "Track" or a data.frame } \author{ <NAME> <<EMAIL>>} %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{rTrack}, \link{as.Track}, \link{as.POSIXct}, \link{compare} } \examples{ library(sp) library(spacetime) # t0 = as.POSIXct(as.Date("2013-09-30",tz="CET")) t0 = as.POSIXct("2013-09-30 02:00:00", tz = "Europe/Berlin") # person A, track 1: x = c(7,6,5,5,4,3,3) y = c(7,7,6,5,5,6,7) n = length(x) set.seed(131) t = t0 + cumsum(runif(n) * 60) crs = CRS("+proj=longlat +datum=WGS84") # longlat stidf = STIDF(SpatialPoints(cbind(x,y),crs), t, data.frame(co2 = rnorm(n))) A1 = Track(stidf) reTrack(A1,timestamp = "1 sec") } <file_sep>/man/as.Track.arrow.Rd \name{as.Track.arrow} \alias{as.Track.arrow} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Convert trajectory pattern to a list of marked point patterns } \description{ Converting a list of Track objects to a list of marked point patterns. Each mark shows the length of movement. } \usage{ as.Track.arrow(X,timestamp,epsilon=epsilon) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ A list of Track objects } \item{timestamp}{based on secs, mins,...} \item{epsilon}{(optional) movements with length less than epsilon are not considered in the calculation} } \details{ Converting a list of Track objetcs to a list of marked point patterns. Marks show the length of movement with respect to the previous location. } \value{ a list of marked point patterns. } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{rTrack}, \link{as.Track.ppp} } \examples{ if (require(spatstat.geom)) { X <- list() for(i in 1:10){ m <- matrix(c(0,10,0,10),nrow=2,byrow = TRUE) X[[i]] <- rTrack(bbox = m,transform = TRUE) } Y <- as.Track.arrow(X,timestamp="120 secs") } } <file_sep>/R/Class-Tracks.R # The first class is "Track", and contains a single track, or trip, followed by # a person, animal or object. This means that consecutive location/time stamps # are not interrupted by a period of substantially other activity. This object # extends "STIDF", where locations and times as well as attributes measured at # these locations and times, such as elevation, are stored. The function "Track" # can now be used to build such an object from its components. The slot # "connections" contains data about the segments between consecutive ST points. setClass("Track", contains = "STIDF", # Locations, times and attribute data about the points. representation(connections = "data.frame"), # With attribute data BETWEEN points: speed, direction etc. validity = function(object) { stopifnot(nrow(object@connections) + 1 == nrow(object@data)) return(TRUE) } ) directions_ll = function(cc, ll) { # cc a 2-column matrix with points, [x y] or [long lat] # ll a boolean, indicating longlat (TRUE) or not (FALSE) if (! ll) { dcc = matrix(apply(cc, 2, diff), ncol = ncol(cc)) ((atan2(dcc[,1], dcc[,2]) / pi * 180) + 360) %% 360 } else { # longlat: # http://www.movable-type.co.uk/scripts/latlong.html # initial bearing: cc = cc * pi / 180 lat1 = head(cc[,2], -1) lat2 = tail(cc[,2], -1) lon1 = head(cc[,1], -1) lon2 = tail(cc[,1], -1) dlon = lon2 - lon1 az = atan2(sin(dlon)*cos(lat2), cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(dlon)) ((az / pi * 180) + 360) %% 360 } } TrackStats = function(track) { duration = diff(as.numeric(index(track@time))) # seconds stopifnot(!any(duration == 0)) if (!is(track@sp, "SpatialPoints")) data.frame(matrix(nrow = length(track@sp) - 1, ncol = 0)) # empty else { cc = coordinates(track@sp) ll = identical(is.projected(track), FALSE) distance = LineLength(cc, ll, FALSE) # for sp 1.1-1: use spDists with segments = TRUE if (ll) # distance is in km, transform to m: distance = distance * 1000.0 speed = distance / duration # per second direction = directions_ll(cc, ll) data.frame(distance = distance, duration = duration, speed = speed, direction = direction) } } # Computes segment lengths. Track = function(track, df = fn(track), fn = TrackStats) { if (is(track, "STI") && !is(track, "STIDF")) track = STIDF(track@sp, track@time, data.frame(ones = rep(1, length(track))), track@endTime) duration = diff(as.numeric(index(track@time))) # seconds if (any(duration == 0)) { sel = (c(1, duration) != 0) n = sum(!sel) warning(paste("deselecting", n, "secondary point(s) of zero duration interval(s)")) if (sum(sel) < 2) stop("less than two unique time instances") track = Track(as(track, "STIDF")[sel,]) } new("Track", track, connections = df) } # A collection of Track objects for single ID (car, person etc.). setClass("Tracks", representation(tracks = "list", tracksData = "data.frame"), validity = function(object) { stopifnot(all(sapply(object@tracks, function(x) is(x, "Track")))) stopifnot(nrow(object@tracksData) == length(object@tracks)) stopifnot(length(object@tracks) > 0) stopifnot(!is.null(names(object@tracks))) stopifnot(identicalCRS(object@tracks)) if (length(object@tracks) > 1) { # verify non-overlap of time intervals: TR = t(sapply(object@tracks, function(x) range(index(x)))) # time range matrix overlap = which(head(TR[,2], -1) > tail(TR[,1], -1)) if (length(overlap) > 0) warning(paste("tracks with overlapping time intervals:",paste(overlap, collapse=", "))) } return(TRUE) } ) TrackSummary = function(track) { ix = index(track@time) bb = bbox(track@sp) conn = track@connections data.frame( xmin = bb[1,1], xmax = bb[1,2], ymin = bb[2,1], ymax = bb[2,2], tmin = min(ix), tmax = max(ix), n = length(track@sp), distance = sum(conn$distance), medspeed = quantile(conn$speed, 0.5) # TODO Compute some mean direction? ) } # Pre-computes elements of tracksData. Tracks = function(tracks, tracksData = data.frame(row.names=names(tracks)), fn = TrackSummary) { stopifnot(is.list(tracks)) if (is.null(names(tracks)) && length(tracks) > 0) names(tracks) = paste("Track", 1:length(tracks), sep = "") new("Tracks", tracks = tracks, tracksData = cbind(tracksData, do.call(rbind, lapply(tracks, fn)))) } # Collection of Tracks for several IDs. setClass("TracksCollection", representation(tracksCollection = "list", tracksCollectionData = "data.frame"), validity = function(object) { stopifnot(all(sapply(object@tracksCollection, inherits, "Tracks"))) stopifnot(length(object@tracksCollection) == nrow(object@tracksCollectionData)) stopifnot(length(object@tracksCollection) > 0) names = names(object@tracksCollection) stopifnot(!(is.null(names) || any(is.na(names)))) stopifnot(identicalCRS(object@tracksCollection)) return(TRUE) } ) # unTracksCollection <- function(x, recursive=TRUE, use.names=TRUE) { # # TracksCollection(Tracks(lapply(x@tracksCollection, # function(tracksObj) { # unlist(tracksObj@tracks) # }))) # # } TracksSummary = function(tracksCollection) { tc = tracksCollection df = data.frame(n = sapply(tc, function(x) length(x@tracks))) df$xmin = sapply(tc, function(x) min(x@tracksData$xmin)) df$xmax = sapply(tc, function(x) max(x@tracksData$xmax)) df$ymin = sapply(tc, function(x) min(x@tracksData$ymin)) df$ymax = sapply(tc, function(x) max(x@tracksData$ymax)) df$tmin = as.POSIXct(unlist(lapply(lapply(tc, function(x) x@tracksData$tmin), min)), origin = "1970-01-01", tz=attr(tc[[1]]@tracks[[1]]@time, "tz")) # do.call(c, lapply(lapply(tc, function(x) x@tracksData$tmin), min)) # reported by RH df$tmax = as.POSIXct(unlist(lapply(lapply(tc, function(x) x@tracksData$tmax), max)), origin = "1970-01-01", tz=attr(tc[[1]]@tracks[[1]]@time, "tz")) # do.call(c, lapply(lapply(tc, function(x) x@tracksData$tmax), max)) # reported by RH row.names(df) = names(tracksCollection) df } TracksCollection = function(tracksCollection, tracksCollectionData = NULL, fn = TracksSummary) { stopifnot(is.list(tracksCollection)) if (is.null(names(tracksCollection))) names(tracksCollection) = paste("Tracks", 1:length(tracksCollection), sep = "") ts = TracksSummary(tracksCollection) if (is.null(tracksCollectionData)) tracksCollectionData = ts else tracksCollectionData = cbind(tracksCollectionData, ts) new("TracksCollection", tracksCollection = tracksCollection, tracksCollectionData = tracksCollectionData) } <file_sep>/man/plot.gTrack.Rd \name{plot.gTrack} \alias{plot.gTrack} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Methods for class "gTrack" } \description{ plot method} \usage{ \method{plot}{gTrack}(x, type = "l", col = "grey70",cex=1,line=2.2, ...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{x}{ an object of class "gTrack" } \item{type}{ line type} \item{col}{ line color} \item{cex}{used for size of legend} \item{line}{specifying a value for line overrides the default placement of labels, and places them this many lines outwards from the plot edge} \item{...}{ passed on to plot} } \author{ <NAME> <<EMAIL>>} <file_sep>/man/downsample.Rd \name{downsample} \docType{methods} \alias{downsample} \alias{downsample,Track-method} \title{Downsample a \code{Track}} \description{ Downsamples a \code{Track} to the size (amount of points) of another \code{Track}. } \usage{% \S4method{downsample}{Track}(track1, track2) } \arguments{ \item{track1}{\code{Track} that will be downsampled.} \item{track2}{Reference \code{Track}.} } \value{A \code{Track} object. The downsampled track1.} \author{ <NAME> <<EMAIL>> } \keyword{downsample} <file_sep>/man/Track.idw.Rd \name{Track.idw} \alias{Track.idw} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Movement smoothing of trajectory pattern } \description{ Movement smoothing of trajectory pattern } \usage{ Track.idw(X,timestamp,epsilon=epsilon,...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ a list of objects of class "Track" } \item{timestamp}{ based on secs,mins, ... } \item{epsilon}{(optional) movements with length less than epsilon are not considered in the calculation} \item{...}{passed to arguments of fucntion idw in spatstat} } \details{ Performs spatial smoothing to the movements of a list of tracks. } \value{ an image of class "im". } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{as.Track.arrow}, \link[spatstat.explore]{idw}} \examples{ if (require(spatstat.geom)) { X <- list() for(i in 1:10){ m <- matrix(c(0,10,0,10),nrow=2,byrow = TRUE) X[[i]] <- rTrack(bbox = m,transform = TRUE) } Track.idw(X,timestamp="180 secs") } } <file_sep>/man/stbox.Rd \name{stbox} \alias{stbox} \alias{stbox,Tracks-method} \alias{stbox,TracksCollection-method} \title{ obtain ranges of space and time coordinates } \description{ obtain ranges of space and time coordinates } \section{Methods}{ \describe{ \item{stbox}{\code{signature(x = "Tracks")}: obtain st range from object} \item{stbox}{\code{signature(x = "TracksCollection")}: obtain st range from object} } } \usage{ stbox(obj) } \arguments{ \item{obj}{ object of a class deriving from \code{Tracks} or \code{TracksCollection}.} } \value{ \code{stbox} returns a \code{data.frame}, with three columns representing x-, y- and time-coordinates, and two rows containing min and max values. \code{bbox} gives a matrix with coordinate min/max values, compatible to \link{bbox}} \keyword{dplot} <file_sep>/R/stplot.R tracksPanel = function(x, y, sp.layout, ...) { sppanel(sp.layout, panel.number()) panel.xyplot(x, y, ...) } segPanel = function(x, y, subscripts, ..., x0, y0, x1, y1, arrows, length, col, sp.layout) { sppanel(sp.layout, panel.number()) if (arrows) panel.arrows(x0[subscripts], y0[subscripts], x1[subscripts], y1[subscripts], length = length, col = col[subscripts], ...) else panel.segments(x0[subscripts], y0[subscripts], x1[subscripts], y1[subscripts], col = col[subscripts], ...) } stplotTracksCollection = function(obj, ..., by, groups, scales = list(draw = FALSE), segments = TRUE, attr = NULL, ncuts = length(col.regions), col.regions = bpy.colors(), cuts, xlab = NULL, ylab = NULL, arrows = FALSE, length = 0.1, xlim = bbexpand(bbox(obj)[1,], 0.04), ylim = bbexpand(bbox(obj)[2,], 0.04), sp.layout = NULL) { sp = obj@tracksCollection[[1]]@tracks[[1]]@sp scales = longlat.scales(sp, scales, xlim, ylim) args = list(..., asp = mapasp(sp, xlim, ylim), scales = scales, xlab = xlab, ylab = ylab, arrows = arrows, length = length, xlim = xlim, ylim = ylim, sp.layout = sp.layout) if (!is.null(attr)) { df = as(obj, "segments") args$x0 = df$x0 args$y0 = df$y0 args$x1 = df$x1 args$y1 = df$y1 # compute color: z = df[[attr]] attr = na.omit(z) if (missing(cuts)) cuts = seq(min(attr), max(attr), length.out = ncuts) if (ncuts != length(col.regions)) { cols = round(1 + (length(col.regions) - 1) * (0:(ncuts - 1))/(ncuts - 1)) fill = col.regions[cols] } else fill = col.regions grps = cut(as.matrix(z), cuts, dig.lab = 4, include.lowest = TRUE) args$col = fill[grps] # set colorkey: args$legend = list(right = list(fun = draw.colorkey, args = list(key = list(col = col.regions, at = cuts), draw = FALSE))) if (is.null(args$panel)) args$panel = "segPanel" cn = c("x0", "y0") } else { if (is.null(args$panel)) args$panel = "tracksPanel" df = as(obj, "data.frame") cn = coordnames(obj) args$type = "l" } if (!missing(by)) args$x = as.formula(paste(cn[2], "~", cn[1], "|", by)) else args$x = as.formula(paste(cn[2], cn[1], sep = " ~ ")) if (!missing(groups)) args$groups = df[[groups]] args$data = df do.call(xyplot, args) } setMethod("stplot", "TracksCollection", stplotTracksCollection) <file_sep>/man/pcfinhom.Track.Rd \name{pcfinhom.Track} \alias{pcfinhom.Track} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Pair correlation funcrion of trajectory pattern } \description{ Pair correlation funcrion of trajectory pattern } \usage{ pcfinhom.Track(X,timestamp,correction = c("translate", "Ripley"),q, sigma=c("default","bw.diggle","bw.ppl","bw.scott"),...) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ A list of Track objects } \item{timestamp}{based on secs,mins,...} \item{correction}{the type of correction to be used in computing pair correlation function} \item{q}{(optional) a numeric value between 0 and 1. quantile to be applied to calculate the variability area} \item{sigma}{method to be used in computing intensity function} \item{...}{passed to the arguments of pcfinhom} } \details{ This calculates the variability area of pair correlation function over time. If sigma=default, it calculates the variability area using the defaults of pcfinhom, otherwise it first estimate the intensity function using the given sigma as bandwidth selection method and then using the estimated intensity function, it estimates the variability area. } \value{ an object of class "gTrack" } \author{ <NAME> <<EMAIL>> } %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{rTrack}, \link{as.Track.ppp}, \link[spatstat.explore]{pcfinhom}} \examples{ if (require(spatstat.explore)) { X <- list() for(i in 1:100){ m <- matrix(c(0,10,0,10),nrow=2,byrow = TRUE) X[[i]] <- rTrack(bbox = m,transform = TRUE) } g <- pcfinhom.Track(X,timestamp = "180 sec") plot(g) } } <file_sep>/man/dists.Rd \name{dists } \docType{methods} \alias{dists} \alias{dists,Tracks,Tracks-method} \title{Calculate distances between two \code{Tracks} objects} \description{ Calculates a distance matrix with distances for each pair of tracks. } \usage{% \S4method{dists}{Tracks,Tracks}(tr1, tr2, f, ...) } \arguments{ \item{tr1}{An object of class \code{Tracks}.} \item{tr2}{An object of class \code{Tracks}.} \item{f}{A function to calculate distances. Default is \code{mean}.} \item{...}{Additional parameters passed to \code{f}.} } \value{A matrix with distances between each pair of tracks or \code{NA} if they don't overlap in time.} \details{ \code{f} can be any function applicable to a numerical vector or \link{frechetDist}. } \examples{ ## example tracks library(sp) library(xts) data(A3) track2 <- A3 index(track2@time) <- index(track2@time) + 32 track2@sp@coords <- track2@sp@coords + 0.003 ## create Tracks objects tracks1 <- Tracks(list(A3, track2)) tracks2 <- Tracks(list(track2, A3)) ## calculate distances \dontrun{ dists(tracks1, tracks2) dists(tracks1, tracks2, sum) dists(tracks1, tracks2, frechetDist) } } \keyword{dists} <file_sep>/R/generalize.R # Provide generalize methods. generalize.Track <- function(t, FUN = mean, ..., timeInterval, distance, n, tol, toPoints) { if (sum(!c(missing(timeInterval), missing(distance), missing(n))) != 1) stop("exactly one parameter from (timeInterval, distance, n) has to be specified") if(!missing(timeInterval)) { origin = index(t@time) cut = cut(origin, timeInterval) segmentLengths = rle(as.numeric(cut))$lengths } if (!missing(distance)) { # Total distances from each point to the first one. origin = c(0, cumsum(t@connections$distance)) cut = floor(origin / distance) segmentLengths = rle(cut)$lengths } if (!missing(n)) { dim = dim(t)["geometries"] if(n != 1 && dim / n > 1) { rep = floor((dim-n)/(n-1) + 1) mod = (dim-n) %% (n-1) if(mod == 0) segmentLengths = rep(n, rep) else segmentLengths = c(rep(n, rep), mod + 1) } else segmentLengths = dim } # Update segment lengths to consider all segments for generalisation. In # case the cut-point falls between two points of the track to be # generalised, attach the next point to the current segment. If the cut- # point matches a point of the track, leave everything as is. toIndex = cumsum(segmentLengths) segmentLengths_ = integer() for(i in seq_along(segmentLengths)) { if (i == length(segmentLengths) || (!missing(timeInterval) && origin[toIndex[i]] %in% seq(origin[1], origin[length(origin)], timeInterval)) || (!missing(distance) && origin[toIndex[i]] > 0 && origin[toIndex[i]] %% distance == 0) || (!missing(n))) segmentLengths_[i] = segmentLengths[i] else { segmentLengths_[i] = segmentLengths[i] + 1 if(i == length(segmentLengths) - 1 && segmentLengths[i+1] == 1) break() } } segmentLengths = segmentLengths_ # Aggregate over each segment. stidfs = list() endTime = NULL for(i in seq_along(segmentLengths)) { from = if(i == 1) 1 else tail(cumsum(segmentLengths[1:(i-1)]), n = 1) - (i-2) to = from + segmentLengths[i] - 1 if(!missing(toPoints) && toPoints) sp = t@sp[(from+to)/2] else { l = Lines(list(Line(t@sp[from:to])), paste("L", i, sep = "")) sp = SpatialLines(list(l), proj4string = t@sp@proj4string) if(!missing(tol) && nrow(coordinates(sp)[[1]][[1]]) > 1) { if (!requireNamespace("sf", quietly = TRUE)) stop("sf required for tolerance") sfc = sf::st_simplify(sf::st_as_sfc(sp), preserveTopology = TRUE, dTolerance = tol) sp = as(sfc, "Spatial") # sp = rgeos::gSimplify(spgeom = sp, tol = tol, topologyPreserve = TRUE) } } time = t@time[from] if (is.null(endTime)) { endTime = t@endTime[to] tz = attr(endTime, "tzone") } else endTime = c(endTime, t@endTime[to]) data = data.frame(lapply(t@data[from:to, , drop = FALSE], FUN, ...)) # EP added ... #stidfs = c(stidfs, STIDF(sp, time, data, t@endTime[to])) stidfs = c(stidfs, STIDF(sp, time, data)) } stidf = do.call(rbind, stidfs) # Provide a workaround, since rbind'ing objects of class POSIXct as used # in the "endTime" slot of STIDF objects does not work properly. attr(endTime, "tzone") = tz stidf@endTime = endTime Track(stidf) } if(!isGeneric("generalize")) setGeneric("generalize", function(t, FUN = mean, ...) standardGeneric("generalize")) setMethod("generalize", signature(t = "Track"), generalize.Track) setMethod("generalize", signature(t = "Tracks"), function(t, FUN = mean, ...) { t@tracks = lapply(t@tracks, function(x) generalize(x, FUN, ...)) t } ) setMethod("generalize", signature(t = "TracksCollection"), function(t, FUN = mean, ...) { t@tracksCollection = lapply(t@tracksCollection, function(x) generalize(x, FUN, ...)) t } ) <file_sep>/README.md trajectories ============ [![CRAN](http://www.r-pkg.org/badges/version/trajectories)](http://cran.rstudio.com/package=trajectories) [![Downloads](http://cranlogs.r-pkg.org/badges/trajectories?color=brightgreen)](http://www.r-pkg.org/pkg/trajectories) R package for handling and analyzing trajectories ### TODO * LocateAlong and LocateBetween (see [Simple Feature Access](http://www.opengeospatial.org/standards/sfa), 6.1.2.6) <file_sep>/demo/storms.R require(XML); library(sp); library(spacetime); library(trajectories) extract.track=function(year = 2012, p = TRUE) { # based on # <NAME> # http://freakonometrics.hypotheses.org/17113 loc <- paste("http://weather.unisys.com/hurricane/atlantic/",year,"/index.php",sep="") tabs <- readHTMLTable(htmlParse(loc)) storms <- unlist(strsplit(as.character(tabs[[1]]$Name),split=" ")) index <- storms %in% c("Tropical","Storm", paste("Hurricane-",1:6,sep=""), "Depression","Subtropical","Extratropical","Low", paste("Storm-",1:6,sep=""), "Xxx") nstorms <- storms[!index] tracks = list() for(i in length(nstorms):1) { loc=paste("http://weather.unisys.com/hurricane/atlantic/", year, "/", nstorms[i], "/track.dat", sep="") track=read.fwf(loc, skip=3, widths = c(4,6,8,12,4,6,20)) names(track)=c("ADV", "LAT", "LON", "TIME", "WIND", "PR", "STAT") track$LAT=as.numeric(as.character(track$LAT)) track$LON=as.numeric(as.character(track$LON)) track$WIND=as.numeric(as.character(track$WIND)) track$PR=as.numeric(as.character(track$PR)) track$year=year pts = SpatialPoints(cbind(track$LON, track$LAT), CRS("+proj=longlat +datum=WGS84 +datum=WGS84")) time = as.POSIXct(paste(year, track$TIME, sep="/"), format="%Y/ %m/%d/%HZ ",tz="UTC") tr = Track(STIDF(pts, time, track)) tracks[nstorms[i]] = tr if (p==TRUE) cat(year,i,nstorms[i],nrow(track),"\n") } return(Tracks(tracks)) } #m=extract.track(2012) #m=extract.track(2011:2012) TOTTRACK=list() #for(y in 2012:1851) for(y in 2012:2009) #TOTTRACK=rbind(TOTTRACK, extract.track(y)) # http://robertgrantstats.wordpress.com/2014/10/01/transparent-hurricane-paths-in-r/ if (!inherits(try(x <- extract.track(y)), "try-error")) TOTTRACK[as.character(y)] = x storms = TracksCollection(TOTTRACK) library(maps) map("world",xlim=c(-80,-40),ylim=c(10,50),col="light yellow",fill=TRUE) plot(storms, col = sp::bpy.colors(4, alpha = .25), lwd = 8, add = TRUE) plot(storms) x = approxTracksCollection(storms, by = "30 min", FUN = spline) plot(x, col = 'red', add = TRUE) TOTTRACK = as(storms, "data.frame") library(ks) U=TOTTRACK[,c("LON","LAT")] U=U[!is.na(U$LON),] H=diag(c(.2,.2)) # note that this might be not meaningful, as coords are longlat: fat=kde(U,H,xmin=c(min(U[,1]),min(U[,2])),xmax=c(max(U[,1]),max(U[,2]))) z=fat$estimate long = fat$eval.points[[1]] lat = fat$eval.points[[2]] image(long, lat, z) plot(storms, add=TRUE) map("world",add=TRUE) plotLLSlice = function(obj, xlim, ylim, newCRS, maps = TRUE, gridlines = TRUE,..., mar = par('mar') - 2, f = .05) { stopifnot(require(rgdal)) stopifnot(require(rgeos)) l.out = 100 # length.out # draw outer box: p = rbind(cbind(xlim[1], seq(ylim[1],ylim[2],length.out = l.out)), cbind(seq(xlim[1],xlim[2],length.out = l.out),ylim[2]), cbind(xlim[2],seq(ylim[2],ylim[1],length.out = l.out)), cbind(seq(xlim[2],xlim[1],length.out = l.out),ylim[1])) LL = CRS("+init=epsg:4326") bb = SpatialPolygons(list(Polygons(list(Polygon(list(p))),"bb")), proj4string = LL) expBboxLL = function(x, f = f) { x@bbox[,1] = bbox(x)[,1] - f * apply(bbox(x), 1, diff); x } plot(expBboxLL(spTransform(bb, newCRS), f), mar = mar) if (gridlines) plot(spTransform(gridlines(bb), newCRS), add = TRUE) if (maps) { stopifnot(require(maps)) m = map(xlim = xlim, ylim = ylim, plot = FALSE, fill = TRUE) IDs <- sapply(strsplit(m$names, ":"), function(x) x[1]) library(maptools) m.sp <- map2SpatialPolygons(m, IDs=IDs, proj4string = LL) m = gIntersection(m.sp, bb) # cut map slice in WGS84 plot(spTransform(m, newCRS), add = TRUE, col = grey(0.8)) } if (is(obj, "TracksCollection")) obj = as(obj, "SpatialLinesDataFrame") obj = spTransform(obj, CRS(proj4string(bb))) # to WGS84, might be obsolete obj = gIntersection(obj, bb) # cut Slice plot(spTransform(obj, newCRS), add = TRUE, ...) text(labels(gridlines(bb), newCRS)) } laea = CRS("+proj=laea +lat_0=30 +lon_0=-80") data(storms) plotLLSlice(storms, xlim = c(-100.01,-19.99), ylim = c(10, 55), laea, col = 'orange', lwd = 2) plotLLSlice(storms, xlim = c(-90,-80), ylim = c(20, 30), laea, col = 'orange', lwd = 2) <file_sep>/man/as.Track.ppp.Rd \name{as.Track.ppp} \alias{as.Track.ppp} %- Also NEED an '\alias' for EACH other topic documented here. \title{ Conver trajectory pattern to a list of objects of class ppp } \description{ This function converts a list of Tracks to a list of point patterns (class "ppp")} \usage{ as.Track.ppp(X,timestamp) } %- maybe also 'usage' for other objects documented here. \arguments{ \item{X}{ a list of Track objects } \item{timestamp}{based on secs, mins,...} } \details{ as.Track.ppp converts a list of Track objetcs to a list of ppp objetcs.} \value{ A list of point patterns, objects of class "ppp". } \author{ <NAME> <<EMAIL>>} %% ~Make other sections like Warning with \section{Warning }{....} ~ \seealso{ \link{avedistTrack}, \link[spatstat.geom]{as.ppp} } \examples{ if (require(spatstat.geom)) { X <- list() for(i in 1:10){ m <- matrix(c(0,10,0,10),nrow=2,byrow = TRUE) X[[i]] <- rTrack(bbox = m,transform = TRUE) } Y <- as.Track.ppp(X,timestamp="120 secs") } } <file_sep>/R/compare-methods.R ## compare tracks setGeneric( name = "compare", def = function(tr1, tr2) standardGeneric("compare") ) ## get distances between 2 Track objects for each point in time where they overlap ## extend each track with these points ## create corresponding lines ## returns a difftrack object compare.track <- function(tr1, tr2) { if (!requireNamespace("xts", quietly = TRUE)) stop("package xts required for track comparison") if (!(xts::first(tr1@endTime) < xts::last(tr2@endTime) && xts::first(tr2@endTime) < xts::last(tr1@endTime))) stop("Time itervals don't overlap!") if (!identicalCRS(tr1, tr2)) stop("CRS are not identical!") crs <- tr1@sp@proj4string track1.df <- cbind(as.data.frame(tr1)[c(coordnames(tr1), "time")]) track2.df <- cbind(as.data.frame(tr2)[c(coordnames(tr2), "time")]) # intervals timestamps fall in ivs1 <- findInterval(track1.df$time, track2.df$time) ivs2 <- findInterval(track2.df$time, track1.df$time) # find points and create new extended data frames newTrack1.df <- findPoints(track2.df, track1.df, ivs2) newTrack2.df <- findPoints(track1.df, track2.df, ivs1) # points on the original conns12 <- merge(newTrack2.df, track1.df, "time") conns21 <- merge(track2.df, newTrack1.df, "time") conns12 <- lineConnections(conns12, crs) conns21 <- lineConnections(conns21, crs) # extended tracks newTrack1 <- STIDF(SpatialPoints(cbind(newTrack1.df$x, newTrack1.df$y), crs), newTrack1.df$time, data.frame(1:nrow(newTrack1.df))) newTrack2 <- STIDF(SpatialPoints(cbind(newTrack2.df$x, newTrack2.df$y), crs), newTrack2.df$time, data.frame(1:nrow(newTrack2.df))) newTrack1 <- Track(newTrack1) newTrack2 <- Track(newTrack2) new("difftrack", track1 = newTrack1, track2 = newTrack2, conns1 = conns12, conns2 = conns21) } setMethod("compare", signature("Track"), compare.track) ## distances between 2 Tracks objects setGeneric( name = "dists", def = function(tr1, tr2, ...) standardGeneric("dists") ) ## returns a matrix with the distance between each pair of tracks dists.tracks <- function(tr1, tr2, f = mean, ...) { cols <- dim(tr1)[[1]] rows <- dim(tr2)[[1]] dists <- matrix(nrow=rows, ncol=cols) # matrix with NA's for (i in 1:cols) { for (j in 1:rows) { if (identical(f, frechetDist)) { dists[j,i] <- f(tr1[i], tr2[j]) } else try({ ## try in case compare gives an error because tracks don't overlap in time difftrack <- compare(tr1[i], tr2[j]) dists[j,i] <- f(c(difftrack@conns1@data$dists, difftrack@conns2@data$dists), ...) }) } } dists } setMethod("dists", signature(tr1 = "Tracks", tr2 = "Tracks"), dists.tracks) ## finds corresponding points for track1 on track2 findPoints <- function(tr1, tr2, ivs) { x <- tr2[,1] y <- tr2[,2] time <- tr2[,3] for (i in 1:nrow(tr1)) { if (!ivs[i] == 0 && !ivs[i] == nrow(tr2)) { iv <- ivs[i] # tdiff1 <- tr1$time[i] - tr2$time[iv] # diff between timestamp and start of the interval it falls in tdiff1 <- difftime(tr1$time[i], tr2$time[iv]) # tdiff2 <- tr2$time[iv+1] - tr2$time[iv] # diff between timestamps (calculated here because it often varies) tdiff2 <- difftime(tr2$time[iv+1], tr2$time[iv], units = units(tdiff1)) ratio <- as.numeric(tdiff1)/as.numeric(tdiff2) x1 <- tr2[iv,1] # segment coordinates y1 <- tr2[iv,2] x2 <- tr2[iv+1,1] y2 <- tr2[iv+1,2] x <- c(x, x1 + ratio * (x2 - x1)) #find point y <- c(y, y1 + ratio * (y2 - y1)) time <- c(time, tr1$time[i]) } } newTrack <- data.frame(x, y, time) newTrack <- newTrack[!duplicated(newTrack),] # remove duplicates newTrack <- newTrack[order(newTrack$time),] # sort by timestamp newTrack } ## creates SpatialLines lineConnections <- function(conns, crs) { Lines <- list() coords1 <- cbind(conns[,2], conns[,3]) coords2 <- cbind(conns[,4], conns[,5]) for (i in 1:nrow(conns)) { Lines <- c(Lines, list(Lines(Line(rbind(coords1[i,], coords2[i,])), ID = i))) } sl <- SpatialLines(Lines, crs) dists <- SpatialLinesLengths(sl) sl <- SpatialLinesDataFrame(sl, data.frame(time = conns$time, dists), FALSE) sl } frechetDist <- function(track1, track2) { stopifnot(is(track1, "Track"), is(track2, "Track")) if (!requireNamespace("xts", quietly = TRUE)) stop("package xts required for frechetDist comparison") if (!identicalCRS(track1, track2)) stop("CRS are not identical!") dists <- spDists(track1@sp, track2@sp) #dists between all points dists[,1] <- cummax(dists[,1]) # cases where one of the trajectories is a point dists[1,] <- cummax(dists[1,]) for (i in 2:nrow(dists)) { # build rest of frechet distance matrix for (j in 2:ncol(dists)) { dists[i,j] <- max(dists[i,j], min(dists[i-1,j], dists[i-1,j-1], dists[i,j-1])) } } max(xts::last(xts::last(dists))) } ## downsamples a track to the length of another one setGeneric( name = "downsample", def = function(track1, track2, ...) standardGeneric("downsample") ) # track1: track that will be downsampled # track2: to the dimension of track2 downsample.track <- function(track1, track2) { if(!identicalCRS(track1, track2)) stop("CRS are not identical!") if(dim(track1) == dim(track2)) stop("Dimensions are euqal!") tr <- track1 xy <- coordinates(track1) time <- index(track1@time) crs <- track1@sp@proj4string while(dim(track1) > dim(track2)) { d1 <- track1$distance # distances n <- length(d1) - 1 # number of segments between every second point xy1 <- cbind(head (xy, n), tail (xy, n)) d2.long <- head(d1, n) + tail(d1, n) xy.new <- list() for(i in 1:n) {xy.new[[i]] <- rbind(head(xy, n)[i,], tail(xy, n)[i,])} d2.short <- sapply (xy.new, function(x) spDists(as.matrix(x), longlat=TRUE)[1,2]) remove <- which.min(d2.long - d2.short) + 1 xy <- xy[- remove,] time <- time[- remove] stidf <- STIDF(SpatialPoints (xy, crs), time, data.frame(extraDat=rnorm(n))) track1 <- Track (stidf) } track1 } setMethod("downsample", signature("Track"), downsample.track)
5d5452d4126b8d169234630a3106eaf329a174bb
[ "Markdown", "R" ]
57
R
edzer/trajectories
2b98d9caa5fdb3e37ddc255f97b4383931b26659
61aeac016338aec56588976b5a4191feb561b7a1
refs/heads/master
<file_sep>package com.ricelink.coolead.model; import java.io.Serializable; import com.lidroid.xutils.db.annotation.Id; import com.lidroid.xutils.db.annotation.NoAutoIncrement; /** * 基础Model * * @author gavin.xiong * */ public class BaseModel implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id(column = "_id") @NoAutoIncrement private String _id; public String get_Id() { return _id; } public void set_Id(String _id) { this._id = _id; } }<file_sep>package com.ricelink.coolead.app.fragment; import java.util.ArrayList; import java.util.List; import com.lidroid.xutils.db.sqlite.Selector; import com.lidroid.xutils.exception.DbException; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.app.activity.InspectionItemActivity; import com.ricelink.coolead.app.adapter.InspectionAdapter; import com.ricelink.coolead.helper.ConfigUtil; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.model.WorkOrder; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.view.View; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * 巡检列表页面 * * @author gavin.xiong * */ public class InspectionListTodayFragment extends BaseFragment { private SwipeRefreshLayout swipeRefreshLayout; private ListView xlist; private InspectionAdapter adapter; private List<WorkOrder> inspectionList = new ArrayList<WorkOrder>(); private List<WorkOrder> inspectionListAll = new ArrayList<WorkOrder>(); // 默认不能上拉加载更多 private boolean haveMore = false; private int offset = 0; private int limit = 15; public InspectionListTodayFragment() { super(R.layout.fragment_inspection_list); } @Override public void initViews() { swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); xlist = (ListView) findViewById(R.id.listview); adapter = new InspectionAdapter(mActivity, inspectionListAll); xlist.setAdapter(adapter); } @Override public void initData() { if (ConfigUtil.getConfig(mActivity).isOffline()) { // 当前为离线模式 try { inspectionList = AppContext.dbUtils.findAll(Selector.from(WorkOrder.class).where("projectCode", "=", mActivity.getProject().getShortCode())); if (null != inspectionList) { inspectionListAll.clear(); inspectionListAll.addAll(inspectionList); adapter.notifyDataSetChanged(); } } catch (DbException e) { e.printStackTrace(); showToast(R.string.toast_get_failed); } finally { swipeRefreshLayout.setRefreshing(false); } } else { // 非离线模式 offset = 0; // getInspectionTodayListOnline(false); getInspectionNew(null, mActivity.getProject().getShortCode()); } } @Override public void bindViews() { xlist.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Bundle bundle = new Bundle(); bundle.putSerializable(Constants.INTENT_EXTRA_INSPECTION, inspectionListAll.get(arg2)); bundle.putInt(Constants.INTENT_EXTRA_INSPECTION_TODAY, Constants.INTENT_EXTRA_INSPECTION_FLAG_TODAY); JumpToActivity(InspectionItemActivity.class, bundle); } }); xlist.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub if (OnScrollListener.SCROLL_STATE_IDLE == scrollState) { // 手指按下并开始滑动 // TODO Auto-generated method stub } else if (OnScrollListener.SCROLL_STATE_TOUCH_SCROLL == scrollState) { // 手指松开且完全停止滑动 // TODO Auto-generated method stub } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // 滑到倒数第二项时加载更多 if (haveMore && totalItemCount <= firstVisibleItem + visibleItemCount) { offset += limit; // getInspectionTodayListOnline(true); } } }); swipeRefreshLayout.setColorSchemeColors(getIntArr(R.array.swipeRefreshLayout_color)); swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { initData(); } }); } /** * 获取巡检 新 * * @param date * @param projectCode */ private void getInspectionNew(String date, String projectCode) { NetManager.getInstance(mActivity).getInspectionNew(date, projectCode, 1, offset, limit, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { inspectionList = JsonUtil.convertJsonToList(responeModel.getResult(), WorkOrder.class); inspectionListAll.clear(); if (null != inspectionList && 0 < inspectionList.size()) { inspectionListAll.addAll(inspectionList); } adapter.notifyDataSetChanged(); } else { showToast(R.string.toast_get_failed); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); showToast(R.string.toast_get_failed); } @Override public void onFinish() { super.onFinish(); swipeRefreshLayout.setRefreshing(false); } }); } @Override public void refreshPage(RefreshModel refreshModel) { if (refreshModel.all || refreshModel.inspection_today) { initData(); } } } <file_sep>package com.ricelink.coolead.app.activity; import java.io.File; import java.util.ArrayList; import org.apache.http.Header; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.app.adapter.AssignDealwithDetailsAdapter; import com.ricelink.coolead.app.adapter.AssignDealwithDetailsAdapter.OnDeleteCallBack; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.helper.DateHelper; import com.ricelink.coolead.helper.FileUtils; import com.ricelink.coolead.helper.L; import com.ricelink.coolead.helper.SPUtil; import com.ricelink.coolead.helper.ToBigImageClickListener; import com.ricelink.coolead.model.DealWithDetail; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.model.WorkOrder; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; /** * 处理人处理页面 * * @author gavin.xiong * */ public class AssignDealwithActivity extends BaseActivity implements OnClickListener { private HeaderBar title; private LinearLayout ll_photos; private LinearLayout ll_details; private ListView lv_details; private AssignDealwithDetailsAdapter adapter; private ArrayList<DealWithDetail> detailList = new ArrayList<DealWithDetail>(); private EditText et_remark; private Uri photoUrl; private ArrayList<Uri> urlList = new ArrayList<Uri>(); private int urlIndex; private WorkOrder workOrder; public AssignDealwithActivity() { super(R.layout.activity_assign_dealwith); } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); ll_photos = (LinearLayout) findViewById(R.id.ll_photos); ll_details = (LinearLayout) findViewById(R.id.ll_details); lv_details = (ListView) findViewById(R.id.lv_details); et_remark = (EditText) findViewById(R.id.et_remark); } @Override public void initData() { Bundle bundle = getIntent().getExtras(); if (null != bundle) { workOrder = (WorkOrder) bundle.getSerializable(Constants.INTENT_EXTRA_WORKORDER); } } @Override public void bindViews() { title.setTitle(R.string.label_assign_dealwith); Drawable drawableR = ContextCompat.getDrawable(this, R.drawable.ic_initiate); drawableR.setBounds(0, 0, drawableR.getMinimumWidth(), drawableR.getMinimumHeight()); // 必须设置图片大小,否则不显示 title.top_right_btn.setCompoundDrawablePadding(2); title.top_right_btn.setCompoundDrawablePadding(8); title.top_right_btn.setCompoundDrawables(drawableR, null, null, null); title.top_right_btn.setText(R.string.label_assign_dealwith_detail); title.top_right_btn.setOnClickListener(this); adapter = new AssignDealwithDetailsAdapter(this, detailList); adapter.setOnClickListener(new OnDeleteCallBack() { @Override public void onDelete(int position) { detailList.remove(position); adapter.notifyDataSetChanged(); if (0 == detailList.size()) { ll_details.setVisibility(View.GONE); } } }); lv_details.setAdapter(adapter); } /** * 点击事件监听 */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_take_photo: // 拍照 takePhotos(); break; case R.id.btn_top_right: // 明细 JumpToActivityForResult(AddDealwithDetailActivity.class, Constants.REQUEST_CODE_ADD_DEALWITH_DETAIL); break; case R.id.btn_wechat: // 微信 showSureDialog(getString(R.string.label_wechat_enter), getString(R.string.label_wechat_enter_now), new OnSurePress() { @Override public void onClick(View view) { try { // Intent intent = new Intent(); // intent.setComponent(new // ComponentName("com.tencent.mm", // "com.tencent.mm.ui.LauncherUI")); // intent.setAction(Intent.ACTION_VIEW); // startActivity(intent); Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm"); startActivity(intent); } catch (NullPointerException e) { showToast(R.string.label_wechat_null); } catch (ActivityNotFoundException e) { showToast(R.string.label_wechat_null); } catch (Exception e) { e.printStackTrace(); showToast(R.string.label_wechat_enter_failed); } } }); break; case R.id.btn_back: // 返回 onBackPressed(); break; case R.id.btn_submit: // 提交 if (null != detailList && 0 < detailList.size()) { addMaterial(); } else { assignDealWith(et_remark.getText().toString()); } break; } } /** * 调用照相机 */ protected void takePhotos() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // photoUrl = Uri.fromFile(new File(Constants.SdCard.getImageDir(), // System.currentTimeMillis() + ".jpg")); photoUrl = Uri.fromFile(new File(Constants.SdCard.getImageDir(), DateHelper.getStringDate() + ".jpg")); L.i(DateHelper.getStringDate()); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUrl); startActivityForResult(intent, Constants.REQUEST_CODE_AVATAR_TAKE_PHOTO); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == Constants.REQUEST_CODE_AVATAR_TAKE_PHOTO && null != photoUrl) { // 拍照回来 FileUtils.getSmallPicture(photoUrl.getPath(), 256, 256); saveImage(photoUrl); return; } if (requestCode == Constants.REQUEST_CODE_ADD_DEALWITH_DETAIL) { // 完成新增处理明细 Bundle bundle = data.getExtras(); if (null != bundle && null != bundle.getSerializable(Constants.INTENT_EXTRA_DEALWITH_DETAIL)) { detailList.add((DealWithDetail) bundle.getSerializable(Constants.INTENT_EXTRA_DEALWITH_DETAIL)); adapter.notifyDataSetChanged(); ll_details.setVisibility(View.VISIBLE); } return; } } } private void saveImage(Uri photoUrl) { String path = photoUrl.getPath(); L.v(path); if (!TextUtils.isEmpty(path)) { File file = new File(path); if (!file.exists()) { file = null; return; } file = null; urlList.add(photoUrl); L.d("add", urlList); bindPhotos(); } } /** * 加载已选照片 */ private void bindPhotos() { ll_photos.removeAllViews(); for (int i = 0; i < urlList.size(); i++) { final Uri url = urlList.get(i); final View view = getResLayout(R.layout.item_photo_list, null); ImageView iv_photo = (ImageView) view.findViewById(R.id.iv_photo); AppContext.setImage(url.toString(), iv_photo); iv_photo.setOnClickListener(new ToBigImageClickListener(this, urlList.toString(), i)); ImageView iv_delete = (ImageView) view.findViewById(R.id.iv_delete); iv_delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { urlList.remove(url); ll_photos.removeView(view); } }); ll_photos.addView(view); } } /** * 批量添加明细 */ private void addMaterial() { NetManager.getInstance(this).addMaterial(workOrder.getId(), detailList, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { assignDealWith(et_remark.getText().toString()); } else { showToast(R.string.toast_submit_failed); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) { super.onFailure(statusCode, headers, responseBytes, throwable); showToast(R.string.toast_submit_failed); } }); } /** * 提交处理结果 */ private void assignDealWith(String remark) { NetManager.getInstance(this).assignDealWith(workOrder.getCurrentId(), remark, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { if (null != photoUrl) { urlIndex = 0; uploadImages(); } else { // showToast(R.string.toast_submit_success); // AssignDealwithActivity.this.finish(); onChangeSueecss(); } } else { showToast(R.string.toast_submit_failed); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) { super.onFailure(statusCode, headers, responseBytes, throwable); showToast(R.string.toast_submit_failed); } }); } /** * 上传图片 * * @param orderId * @param step */ private void uploadImages() { if (urlIndex < urlList.size()) { uploadImageTask(workOrder.getId(), Constants.WORKORDER_STEP_HANDLE, urlList.get(urlIndex).getPath()); urlIndex++; } else { onChangeSueecss(); } } /** * 上传图片 * * @param orderId * @param step * @param imgPath */ private void uploadImageTask(long orderId, String step, String imgPath) { NetManager.getInstance(this).upLoadImage(orderId, step, imgPath, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { // showToast(R.string.toast_submit_success); // AssignDealwithActivity.this.finish(); // onChangeSueecss(); uploadImages(); } else { showToast(R.string.toast_submit_failed); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); showToast(R.string.toast_submit_failed); } }); } private void onChangeSueecss() { showToast(R.string.toast_submit_success); RefreshModel rm = new RefreshModel(); rm.workOrder_backlog = true; rm.workOrder_list = true; rm.workOrder_info = true; rm.workOrder_progerss = true; SPUtil.saveObjectToShare(RefreshModel.class.getName(), rm); this.finish(); } } <file_sep>package com.ricelink.coolead.app.activity; import java.util.ArrayList; import java.util.List; import com.lidroid.xutils.db.sqlite.Selector; import com.lidroid.xutils.db.sqlite.WhereBuilder; import com.lidroid.xutils.exception.DbException; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.app.adapter.InspectionContentAdapter; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.helper.ConfigUtil; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.helper.NetUtil; import com.ricelink.coolead.helper.StringUtils; import com.ricelink.coolead.model.EqRouteIdsModel; import com.ricelink.coolead.model.InspectionContent; import com.ricelink.coolead.model.InspectionContentResponse; import com.ricelink.coolead.model.InspectionItem; import com.ricelink.coolead.model.SaveInspectionContentModel; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; /** * 操作巡检页面 * * @author gavin.xiong * */ public class InspectionContentActivity extends BaseActivity { private HeaderBar title; private RadioGroup rg_status; private RadioButton rb_run, rb_stop, rb_fix; private ListView lv_content; private LinearLayout ll_status; private InspectionContentAdapter adapter; private InspectionContentResponse contentResponse; private List<InspectionContent> contentList = new ArrayList<InspectionContent>(); private InspectionItem cInspectionItem; private String workorderStatus; private int dateFlag; public InspectionContentActivity() { super(R.layout.activity_inspection_content); } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); ll_status = (LinearLayout) findViewById(R.id.ll_status); lv_content = (ListView) findViewById(R.id.listview); rg_status = (RadioGroup) findViewById(R.id.rg_status); rb_run = (RadioButton) findViewById(R.id.rb_run); rb_stop = (RadioButton) findViewById(R.id.rb_stop); rb_fix = (RadioButton) findViewById(R.id.rb_fix); } @Override public void initData() { checkNetStatus = false; adapter = new InspectionContentAdapter(this, contentList); lv_content.setAdapter(adapter); Bundle bundle = getIntent().getExtras(); if (null != bundle) { cInspectionItem = (InspectionItem) bundle.getSerializable(Constants.INTENT_EXTRA_INSPECTION_ITEM); workorderStatus = bundle.getString(Constants.INTENT_EXTRA_WORKORDER_STATUS, ""); adapter.setWorkorderStatus(workorderStatus); dateFlag = bundle.getInt(Constants.INTENT_EXTRA_INSPECTION_TODAY, 0); adapter.setContentType(cInspectionItem.getObjectType()); if (dateFlag > 0 && ConfigUtil.getConfig(this).isOffline()) { // 当前为离线模式 try { List<InspectionContent> contents = AppContext.dbUtils.findAll(Selector.from(InspectionContent.class) // .where("objectCode", "=", cInspectionItem.getObjectCode()) // .and("orderId", "=", cInspectionItem.getOrderId())); contentList.addAll(contents); adapter.notifyDataSetChanged(); if (Constants.INSPECTION_DEVICE_STATUS_INUSE.equals(cInspectionItem.getEqStatus())) { rb_run.setChecked(true); } else if (Constants.INSPECTION_DEVICE_STATUS_STOP.equals(cInspectionItem.getEqStatus())) { rb_stop.setChecked(true); } else if (null == cInspectionItem.getEqStatus()) { // } else { rb_fix.setChecked(true); } } catch (DbException e) { e.printStackTrace(); showToast(R.string.toast_get_failed); } } else { // 非离线模式 List<EqRouteIdsModel> ids = new ArrayList<EqRouteIdsModel>(); EqRouteIdsModel erim = new EqRouteIdsModel(); erim.setObjectCode(cInspectionItem.getObjectCode()); erim.setOrderId(cInspectionItem.getOrderId()); erim.setObjectType(cInspectionItem.getObjectType()); erim.setRouteId(cInspectionItem.getRouteId()); ids.add(erim); getInspectionEqContent(ids); } } } @Override public void bindViews() { if (null != cInspectionItem) { title.setTitle(cInspectionItem.getObjectName()); title.top_right_btn.setText(getString(R.string.public_finish)); title.top_right_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 为空判断 for (InspectionContent ic : contentList) { if (StringUtils.isEmpty(ic.getResult()) || (("Y".equals(ic.getIsTranscribing()) || "1".equalsIgnoreCase(ic.getIsTranscribing())) && StringUtils.isEmpty(ic.getTranscribingData()))) { showToast(R.string.toast_dealwith_data_not_null); return; } } if (!Constants.INSPECTION_CONTENT_TYPE_YNDW.equals(cInspectionItem.getObjectType())) { if (rg_status.getCheckedRadioButtonId() > 0) { if (!NetUtil.isNetworkAvailable(InspectionContentActivity.this)) { // 当前网络未连接时保存在本地 // if (ConfigUtil.getConfig(this).isOffline()) { saveStatus2Sqlite(1); } else { saveStatus2Net(); } } else { showToast(R.string.toast_dealwith_stauts_not_null); } } else { if (!NetUtil.isNetworkAvailable(InspectionContentActivity.this)) { // 当前网络未连接时保存在本地 // if (ConfigUtil.getConfig(this).isOffline()) { saveStatus2Sqlite(1); } else { saveStatus2Net(); } } } }); if (Constants.WORKORDER_STATUS_HANDLE.equals(workorderStatus)) { title.top_right_btn.setVisibility(View.VISIBLE); } else { title.top_right_btn.setVisibility(View.GONE); rg_status.setEnabled(false); rb_run.setEnabled(false); rb_stop.setEnabled(false); rb_fix.setEnabled(false); } if (Constants.INSPECTION_CONTENT_TYPE_YNDW.equals(cInspectionItem.getObjectType())) { ll_status.setVisibility(View.GONE); } } } /** * 保存巡检数据到本地 */ private void saveStatus2Sqlite(int waitUpload) { try { AppContext.dbUtils.updateAll(contentList, "transcribingData", "result", "expDescription", "endTime"); cInspectionItem.setWaitUpload(waitUpload); cInspectionItem.setStatus("Y"); cInspectionItem.setEqStatus(getEqStatus()); AppContext.dbUtils.update(cInspectionItem, WhereBuilder.b("orderId", "=", cInspectionItem.getOrderId()) .and("objectCode", "=", cInspectionItem.getObjectCode()), "status", "eqStatus", "waitUpload"); showToast(R.string.toast_dealwith_data_save_sucess); setResult(Activity.RESULT_OK); InspectionContentActivity.this.finish(); } catch (DbException e) { showToast(R.string.toast_dealwith_data_save_failed); e.printStackTrace(); } } /** * 保存数据到网络 */ private void saveStatus2Net() { List<SaveInspectionContentModel> sicms = new ArrayList<SaveInspectionContentModel>(); SaveInspectionContentModel sicm = new SaveInspectionContentModel(); sicm.setInspectionEquipmentContents(contentList); sicm.setEqCode(cInspectionItem.getObjectCode()); // 设置设备状态 sicm.setStatus(getEqStatus()); sicms.add(sicm); saveInspectionStatus(sicms); } private String getEqStatus() { if (Constants.INSPECTION_CONTENT_TYPE_YNDW.equals(cInspectionItem.getObjectType())) return null; switch (rg_status.getCheckedRadioButtonId()) { case R.id.rb_run: return Constants.INSPECTION_DEVICE_STATUS_INUSE; case R.id.rb_stop: return Constants.INSPECTION_DEVICE_STATUS_STOP; case R.id.rb_fix: return Constants.INSPECTION_DEVICE_STATUS_BROKEN; } return null; } /** * 查询设备巡检内容 */ private void getInspectionEqContent(List<EqRouteIdsModel> ids) { NetManager.getInstance(this).getInspectionEqContent(ids, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { List<InspectionContentResponse> icrs = JsonUtil.convertJsonToList(responeModel.getResult(), InspectionContentResponse.class); if (null != icrs && 0 < icrs.size()) { contentResponse = icrs.get(0); contentList.clear(); // if (null == contentResponse){ // return; // } List<InspectionContent> ios = contentResponse.getEqContentArrayList(); for (InspectionContent io : ios) { io.setOrderId(cInspectionItem.getOrderId()); } contentList.addAll(ios); adapter.notifyDataSetChanged(); if (null != contentResponse) { if (Constants.INSPECTION_DEVICE_STATUS_INUSE.equals(contentResponse.getStatus())) { rb_run.setChecked(true); } else if (Constants.INSPECTION_DEVICE_STATUS_STOP.equals(contentResponse.getStatus())) { rb_stop.setChecked(true); } else if (null == contentResponse.getStatus()) { // } else { rb_fix.setChecked(true); } } } } else { // 失败 showToast(getString(R.string.toast_get_failed) + responeModel.getMessage()); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); showToast(R.string.toast_get_failed); } @Override public void onFinish() { super.onFinish(); } }); } /** * 保存巡检数据到网络 */ private void saveInspectionStatus(List<SaveInspectionContentModel> contentList) { NetManager.getInstance(this).saveInspectionStatus(contentList, true, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { if (dateFlag > 0 && ConfigUtil.getConfig(context).isOffline()) { // 当前为离线模式 saveStatus2Sqlite(0); } else { setResult(Activity.RESULT_OK); InspectionContentActivity.this.finish(); } } else { if (dateFlag > 0 && ConfigUtil.getConfig(context).isOffline()) { // 当前为离线模式 saveStatus2Sqlite(1); } else { showToast(R.string.toast_submit_failed); } } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); if (dateFlag > 0 && ConfigUtil.getConfig(context).isOffline()) { // 当前为离线模式 saveStatus2Sqlite(1); } else { showToast(R.string.toast_submit_failed); } } }); } /** * 数据改变 */ public void setData(int index, String data) { contentList.get(index).setTranscribingData(data); setEndTime(index); } /** * 状态更改 */ public void setStatus(int index, boolean isNor) { contentList.get(index).setResult(isNor ? "1" : "2"); setEndTime(index); } /** * 详情描述 */ public void setDescription(int index, String description) { contentList.get(index).setExpDescription(description); setEndTime(index); } /** * 结束时间 */ private void setEndTime(int index) { contentList.get(index).setEndTime("" + System.currentTimeMillis()); } } <file_sep>package com.ricelink.coolead.app.fragment; import java.util.Date; import java.util.List; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.app.activity.AboutActivity; import com.ricelink.coolead.app.activity.BaseActivity.OnSurePress; import com.ricelink.coolead.app.activity.ChangePasswordActivity; import com.ricelink.coolead.app.activity.LoginActivity; import com.ricelink.coolead.app.activity.MainActivity; import com.ricelink.coolead.app.view.SlipButton; import com.ricelink.coolead.app.view.SlipButton.OnChangedListener; import com.ricelink.coolead.helper.ConfigUtil; import com.ricelink.coolead.helper.DateUtil; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.helper.NetUtil; import com.ricelink.coolead.helper.VersionHelper; import com.ricelink.coolead.model.AppInfo; import com.ricelink.coolead.model.ConfigModel; import com.ricelink.coolead.model.InspectionItem; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.model.User; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.net.Urls; import com.ricelink.coolead.service.CachingService; import com.ricelink.coolead.v.R; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; /** * 更多页面 * * @author gavin.xiong * */ public class MoreFragment extends BaseFragment implements OnClickListener { private ImageView civ_headimg; private TextView tv_name, tv_code; private SlipButton sb_off_line; private TextView tv_version_name; private ImageView tv_version_tip; public MoreFragment() { super(R.layout.fragment_more); } @Override public void initViews() { civ_headimg = (ImageView) findViewById(R.id.civ_headimg); tv_name = (TextView) findViewById(R.id.tv_name); tv_code = (TextView) findViewById(R.id.tv_code); sb_off_line = (SlipButton) findViewById(R.id.sb_off_line); tv_version_name = (TextView) findViewById(R.id.tv_version_name); tv_version_tip = (ImageView) findViewById(R.id.tv_version_tip); } @Override public void initData() { // 自动检测更新 (一天只进行一次) if (!DateUtil.getDate(new Date()).equals(ConfigUtil.getNotifyUpdateDate(mActivity))) { checkVersions(true, false); } } @Override public void bindViews() { AppContext.setImage(Urls.IMAGE_URL + getUser().getAvater(), civ_headimg, R.drawable.def_avatar); tv_name.setText(getUser().getUserName()); tv_code.setText(getUser().getUserCode()); try { sb_off_line.setPager(((MainActivity) getActivity()).getSlidingSwitchViewPager()); } catch (ClassCastException e) { // sb_off_line.setPager(((MainDemoActivity)getActivity()).getSlidingSwitchViewPager()); } sb_off_line.setCheck(ConfigUtil.getConfig(mActivity).isOffline()); sb_off_line.SetOnChangedListener(new OnChangedListener() { @Override public void OnChanged(boolean checkState) { ConfigModel config = ConfigUtil.getConfig(mActivity); config.setOffline(checkState); ConfigUtil.saveConfig(mActivity, config); showToast(checkState ? R.string.toast_off_line_mode_open : R.string.toast_off_line_mode_close); } }); findViewById(R.id.rl_caching_data).setOnClickListener(this); findViewById(R.id.rl_version_updating).setOnClickListener(this); findViewById(R.id.rl_update_password).setOnClickListener(this); findViewById(R.id.rl_about).setOnClickListener(this); findViewById(R.id.btn_logout).setOnClickListener(this); } /** * 点击事件 * * @param v */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.rl_caching_data: // 缓存巡检数据 List<InspectionItem> items = CachingService.getWaitUploadInspectionItem(); if (null == items || 0 == items.size()) { // 如果没有待上传的巡检数据 CachingService.startCaching(mActivity); } else { // 如果还有离线巡检数据尚未上传 showToast(R.string.label_caching_data_inspection_not_null_2); CachingService.onNetChange(mActivity, NetUtil.getNetworkInfo(mActivity)); } break; case R.id.rl_version_updating: // 检测新版本 checkVersions(true, true); break; case R.id.rl_update_password: // 修改密码 JumpToActivity(ChangePasswordActivity.class); break; case R.id.rl_about: // 关于 JumpToActivity(AboutActivity.class); break; case R.id.btn_logout: // 注销登录 logout(); break; } } /** * 登出 */ private void logout() { // 退出 AppContext.connectionManager.disconnect(); AppContext.settingManager.writeSetting(Constants.SP_KEY_IS_Login, false); User user = mActivity.getUser(); if (null != user) { user.setLogin(false); AppContext.saveUser(user); } JumpToActivity(LoginActivity.class); mActivity.finish(); } /** * 检测新版本 */ private void checkVersions(final boolean updateNow, final boolean showLoadingDialog) { NetManager.getInstance(mActivity).checkVersions(showLoadingDialog, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { List<AppInfo> ais = JsonUtil.convertJsonToList(responeModel.getResult(), AppInfo.class); final AppInfo newVersion = ais.get(0); if (newVersion.getVersionCode() > 0 && newVersion.getVersionCode() > getCurrVersionCode()) { showVersionTip(newVersion.getVersionName()); ConfigModel config = ConfigUtil.getConfig(mActivity); config.setHasNewVersion(true); config.setNewVersionName(newVersion.getVersionName()); config.setNotifyUpdateDate(DateUtil.getDate(new Date())); ConfigUtil.saveConfig(mActivity, config); if (updateNow) { mActivity.showSureDialog(getString(R.string.label_found_the_new_version), getString(R.string.label_version_updating_now), new OnSurePress() { @Override public void onClick(View view) { newVersion.setUrl(Urls.APP_DOWNLOAD); VersionHelper.downloadApk(mActivity, newVersion); ConfigUtil.setHasNewVersion(mActivity, false); } }); } } else { if (showLoadingDialog) { showToast(R.string.toast_version_already_new); } } } else { showToast(R.string.toast_get_failed); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); showToast(R.string.toast_get_failed); } }); } /** * 显示角标并记录 */ private void showVersionTip(String newVersionName) { tv_version_tip.setVisibility(View.VISIBLE); tv_version_name.setVisibility(View.VISIBLE); tv_version_name.setText(newVersionName); ((MainActivity) getActivity()).setTabTip(3, ""); } /** * 获取版本号 * * @return 当前应用的版本号 */ public int getCurrVersionCode() { try { PackageManager manager = mActivity.getPackageManager(); PackageInfo info = manager.getPackageInfo(mActivity.getPackageName(), 0); return info.versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return -1; } @Override public void refreshPage(RefreshModel refreshModel) { // TODO Auto-generated method stub } } <file_sep>package com.ricelink.coolead.model; public class ServiceMessage { private long id; private long questionId; private String answerContent; private String answerUser; private String addTime; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getQuestionId() { return questionId; } public void setQuestionId(long questionId) { this.questionId = questionId; } public String getAnswerContent() { return answerContent; } public void setAnswerContent(String answerContent) { this.answerContent = answerContent; } public String getAnswerUser() { return answerUser; } public void setAnswerUser(String answerUser) { this.answerUser = answerUser; } public String getAddTime() { return addTime; } public void setAddTime(String addTime) { this.addTime = addTime; } } <file_sep>package com.ricelink.coolead.model; import java.util.List; public class InspectionContentResponse { private int stop; private int broken; private int inUse; private int suspension; private int maintenance; private int sum; private String status; private String transactor; private long routeId; private String eqCode; private List<InspectionContent> eqContentArrayList; public int getStop() { return stop; } public void setStop(int stop) { this.stop = stop; } public int getBroken() { return broken; } public void setBroken(int broken) { this.broken = broken; } public int getInUse() { return inUse; } public void setInUse(int inUse) { this.inUse = inUse; } public int getSuspension() { return suspension; } public void setSuspension(int suspension) { this.suspension = suspension; } public int getMaintenance() { return maintenance; } public void setMaintenance(int maintenance) { this.maintenance = maintenance; } public int getSum() { return sum; } public void setSum(int sum) { this.sum = sum; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getTransactor() { return transactor; } public void setTransactor(String transactor) { this.transactor = transactor; } public List<InspectionContent> getEqContentArrayList() { return eqContentArrayList; } public void setEqContentArrayList(List<InspectionContent> eqContentArrayList) { this.eqContentArrayList = eqContentArrayList; } public long getRouteId() { return routeId; } public void setRouteId(long routeId) { this.routeId = routeId; } public String getEqCode() { return eqCode; } public void setEqCode(String eqCode) { this.eqCode = eqCode; } } <file_sep>package com.ricelink.coolead.model; public class ProgressModel { private String id; private String name; private String person; private String endTime; private String remark; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPerson() { return person; } public void setPerson(String person) { this.person = person; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } } <file_sep>package com.ricelink.coolead.model; import java.util.List; /** * 批量获取设备巡检项的id集 * * @author gavin.xiong * */ public class CachingInspectionItemModel { private long id; private long orderId; private List<InspectionItem> routeObjects; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public List<InspectionItem> getRouteObjects() { return routeObjects; } public void setRouteObjects(List<InspectionItem> routeObjects) { this.routeObjects = routeObjects; } } <file_sep>package com.ricelink.coolead.app.activity; import java.io.File; import java.util.ArrayList; import org.apache.http.Header; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.helper.DateHelper; import com.ricelink.coolead.helper.FileUtils; import com.ricelink.coolead.helper.L; import com.ricelink.coolead.helper.SPUtil; import com.ricelink.coolead.helper.ToBigImageClickListener; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.model.WorkOrder; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; /** * 验收人处理页面 * * @author gavin.xiong * */ public class AcceptorDealwithActivity extends BaseActivity implements OnClickListener { private HeaderBar title; private LinearLayout ll_photos; private RadioButton rb_timely, rb_timely_n, rb_qualified_n, rb_qualified; private EditText et_remark; private Uri photoUrl; private ArrayList<Uri> urlList = new ArrayList<Uri>(); private int urlIndex; private WorkOrder workOrder; public AcceptorDealwithActivity() { super(R.layout.activity_acceptor_dealwith); } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); ll_photos = (LinearLayout) findViewById(R.id.ll_photos); rb_qualified = (RadioButton) findViewById(R.id.rb_qualified); rb_qualified_n = (RadioButton) findViewById(R.id.rb_qualified_n); rb_timely = (RadioButton) findViewById(R.id.rb_timely); rb_timely_n = (RadioButton) findViewById(R.id.rb_timely_n); et_remark = (EditText) findViewById(R.id.et_remark); } @Override public void initData() { Bundle bundle = getIntent().getExtras(); if (null != bundle) { workOrder = (WorkOrder) bundle.getSerializable(Constants.INTENT_EXTRA_WORKORDER); } } @Override public void bindViews() { title.setTitle(R.string.label_acceptor_dealwith_pass); rb_qualified.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { rb_qualified.setTextColor(AcceptorDealwithActivity.this.getResColor(R.color.color_white)); } else { rb_qualified.setTextColor(AcceptorDealwithActivity.this.getResColor(R.color.color_green)); } } }); rb_qualified_n.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { rb_qualified_n.setTextColor(AcceptorDealwithActivity.this.getResColor(R.color.color_white)); } else { rb_qualified_n.setTextColor(AcceptorDealwithActivity.this.getResColor(R.color.color_red)); } } }); rb_qualified.setChecked(true); rb_timely.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { rb_timely.setTextColor(AcceptorDealwithActivity.this.getResColor(R.color.color_white)); } else { rb_timely.setTextColor(AcceptorDealwithActivity.this.getResColor(R.color.color_green)); } } }); rb_timely_n.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { rb_timely_n.setTextColor(AcceptorDealwithActivity.this.getResColor(R.color.color_white)); } else { rb_timely_n.setTextColor(AcceptorDealwithActivity.this.getResColor(R.color.color_red)); } } }); rb_timely.setChecked(true); } /** * 点击事件监听 */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_take_photo: // 拍照 takePhotos(); break; case R.id.btn_wechat: // 微信 showSureDialog(getString(R.string.label_wechat_enter), getString(R.string.label_wechat_enter_now), new OnSurePress() { @Override public void onClick(View view) { try { // Intent intent = new Intent(); // intent.setComponent(new ComponentName("com.tencent.mm", // "com.tencent.mm.ui.LauncherUI")); // intent.setAction(Intent.ACTION_VIEW); // startActivity(intent); Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm"); startActivity(intent); } catch (NullPointerException e) { showToast(R.string.label_wechat_null); } catch (ActivityNotFoundException e) { showToast(R.string.label_wechat_null); } catch (Exception e) { e.printStackTrace(); showToast(R.string.label_wechat_enter_failed); } } }); break; case R.id.btn_finish: // 结束 acceptorDealWith(rb_timely.isChecked() ? "Y" : "N", rb_qualified.isChecked() ? "Y" : "N", et_remark.getText().toString()); break; } } /** * 调用照相机 */ protected void takePhotos() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); photoUrl = Uri.fromFile(new File(Constants.SdCard.getImageDir(), DateHelper.getStringDate() + ".jpg")); L.i(DateHelper.getStringDate()); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUrl); startActivityForResult(intent, Constants.REQUEST_CODE_AVATAR_TAKE_PHOTO); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == Constants.REQUEST_CODE_AVATAR_TAKE_PHOTO && null != photoUrl) { // 拍照回来 FileUtils.getSmallPicture(photoUrl.getPath(), 256, 256); saveImage(photoUrl); return; } } } private void saveImage(Uri photoUrl) { String path = photoUrl.getPath(); L.v(path); if (!TextUtils.isEmpty(path)) { File file = new File(path); if (!file.exists()) { file = null; return; } file = null; urlList.add(photoUrl); L.d("add", urlList); bindPhotos(); } } /** * 加载已选照片 */ private void bindPhotos() { ll_photos.removeAllViews(); for (int i = 0; i < urlList.size(); i++) { final Uri url = urlList.get(i); final View view = getResLayout(R.layout.item_photo_list, null); ImageView iv_photo = (ImageView) view.findViewById(R.id.iv_photo); AppContext.setImage(url.toString(), iv_photo); iv_photo.setOnClickListener(new ToBigImageClickListener(this, urlList.toString(), i)); ImageView iv_delete = (ImageView) view.findViewById(R.id.iv_delete); iv_delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { urlList.remove(url); ll_photos.removeView(view); } }); ll_photos.addView(view); } } /** * 提交处理结果 */ private void acceptorDealWith(String is_in_time, String is_qualified, String remark) { NetManager.getInstance(this).acceptorDealWith(workOrder.getCurrentId(), is_in_time, is_qualified, remark, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { if (null != photoUrl) { urlIndex = 0; uploadImages(); } else { // showToast(R.string.toast_submit_success); // AcceptorDealwithActivity.this.finish(); onChangeSueecss(); } } else { showToast(R.string.toast_submit_failed); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) { super.onFailure(statusCode, headers, responseBytes, throwable); showToast(R.string.toast_submit_failed); } }); } /** * 上传图片 * * @param orderId * @param step */ private void uploadImages() { if (urlIndex < urlList.size()) { uploadImageTask(workOrder.getId(), Constants.WORKORDER_STEP_ACCEPT, urlList.get(urlIndex).getPath()); urlIndex++; } else { onChangeSueecss(); } } /** * 上传图片 * * @param orderId * @param step * @param imgPath */ private void uploadImageTask(long orderId, String step, String imgPath) { NetManager.getInstance(this).upLoadImage(orderId, step, imgPath, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { // showToast(R.string.toast_submit_success); // AcceptorDealwithActivity.this.finish(); // onChangeSueecss(); uploadImages(); } else { showToast(R.string.toast_submit_failed); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); showToast(R.string.toast_submit_failed); } }); } private void onChangeSueecss() { showToast(R.string.toast_submit_success); RefreshModel rm = new RefreshModel(); rm.workOrder_backlog = true; rm.workOrder_list = true; rm.workOrder_info = true; rm.workOrder_progerss = true; SPUtil.saveObjectToShare(RefreshModel.class.getName(), rm); this.finish(); } } <file_sep>package com.ricelink.coolead.app.fragment; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.github.mikephil.charting.charts.BarChart; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.MarkerView; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.XAxis.XAxisPosition; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.CandleEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.formatter.LargeValueFormatter; import com.github.mikephil.charting.formatter.ValueFormatter; import com.github.mikephil.charting.formatter.YAxisValueFormatter; import com.github.mikephil.charting.highlight.Highlight; import com.github.mikephil.charting.utils.Utils; import com.github.mikephil.charting.utils.ViewPortHandler; import com.ricelink.coolead.app.activity.LoginActivity; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.helper.UserUtil; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.model.StatisticsModel; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import android.content.Context; import android.graphics.Color; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; /** * 巡检统计页面 * * @author gavin.xiong * */ public class InspectionStatisticsFragment extends BaseFragment implements OnClickListener { private SwipeRefreshLayout swipeRefreshLayout; private TextView tv_month_num, tv_month_finish, tv_month_passed, tv_month_timely; private TextView tv_year_num, tv_year_finish, tv_year_passed, tv_year_timely; // 柱状图+线形图 private BarChart topBarChart; private LineChart lineChart; // 柱状图 private BarChart barChart; @SuppressWarnings("unused") private MyMarkerView markerView; public InspectionStatisticsFragment() { super(R.layout.fragment_inspection_statistics); } @Override public void initViews() { markerView = new MyMarkerView(getContext(), R.layout.marker, R.id.tv); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); topBarChart = (BarChart) findViewById(R.id.barChart1); lineChart = (LineChart) findViewById(R.id.lineChart); tv_month_num = (TextView) findViewById(R.id.tv_month_num); tv_month_finish = (TextView) findViewById(R.id.tv_month_rale_finishing); tv_month_passed = (TextView) findViewById(R.id.tv_month_rale_qualified); tv_month_timely = (TextView) findViewById(R.id.tv_month_rale_timely); tv_year_num = (TextView) findViewById(R.id.tv_all_num); tv_year_finish = (TextView) findViewById(R.id.tv_all_rale_finishing); tv_year_passed = (TextView) findViewById(R.id.tv_all_rale_qualified); tv_year_timely = (TextView) findViewById(R.id.tv_all_rale_timely); barChart = (BarChart) findViewById(R.id.barChart); } @Override public void initData() { getMonthInspection(); getInspectionStatistics(); } @Override public void bindViews() { swipeRefreshLayout.setColorSchemeColors(getIntArr(R.array.swipeRefreshLayout_color)); swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { initData(); } }); initCombinedChartView(); initLineChart(); initBarChartView(); } private void initLineChart() { lineChart.setNoDataText(""); lineChart.setDescription(""); lineChart.setPinchZoom(false); lineChart.setDrawGridBackground(false); lineChart.setScaleYEnabled(false); lineChart.setScaleXEnabled(false); lineChart.animateY(1000); lineChart.setHighlightPerTapEnabled(false); lineChart.setHighlightPerDragEnabled(false); // lineChart.setMarkerView(markerView); Legend l = lineChart.getLegend(); l.setPosition(LegendPosition.ABOVE_CHART_LEFT); l.setYOffset(0f); l.setXOffset(90f); l.setYEntrySpace(0f); l.setTextSize(10f); YAxis rightAxis = lineChart.getAxisRight(); rightAxis.setDrawGridLines(false); rightAxis.setSpaceTop(20f); rightAxis.setAxisMaxValue(100); rightAxis.setDrawAxisLine(false); rightAxis.setTextColor(getResColor(R.color.text_gray_6)); rightAxis.setValueFormatter(new MyYAxisValueFormatter2()); YAxis leftAxis = lineChart.getAxisLeft(); leftAxis.setDrawGridLines(false); leftAxis.setSpaceTop(20f); leftAxis.setAxisMaxValue(100); leftAxis.setTextColor(Color.parseColor("#00000000")); leftAxis.setDrawAxisLine(false); leftAxis.setValueFormatter(new LargeValueFormatter("00")); XAxis xAxis = lineChart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setDrawGridLines(false); xAxis.setTextColor(Color.parseColor("#00000000")); xAxis.setTextSize(8.0f); xAxis.setAxisLineColor(Color.parseColor("#00000000")); } private void initCombinedChartView() { topBarChart.setDescription(""); topBarChart.setPinchZoom(false); topBarChart.setDrawGridBackground(false); topBarChart.setDrawBarShadow(false); topBarChart.setScaleYEnabled(false); topBarChart.setScaleXEnabled(false); topBarChart.animateY(1000); topBarChart.setHighlightPerTapEnabled(false); topBarChart.setHighlightPerDragEnabled(false); Legend l = topBarChart.getLegend(); l.setPosition(LegendPosition.ABOVE_CHART_LEFT); l.setYOffset(0f); l.setYEntrySpace(0f); l.setTextSize(10f); YAxis rightAxis = topBarChart.getAxisRight(); rightAxis.setDrawGridLines(false); rightAxis.setTextColor(Color.parseColor("#00000000")); rightAxis.setSpaceTop(20f); rightAxis.setDrawAxisLine(false); rightAxis.setAxisMaxValue(100f); rightAxis.setValueFormatter(new MyYAxisValueFormatter()); YAxis leftAxis = topBarChart.getAxisLeft(); leftAxis.setDrawGridLines(false); leftAxis.setTextColor(getResColor(R.color.text_gray_6)); leftAxis.setSpaceTop(20f); leftAxis.setValueFormatter(new MyYAxisValueFormatter3()); leftAxis.setDrawAxisLine(false); XAxis xAxis = topBarChart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setDrawGridLines(false); xAxis.setTextColor(getResColor(R.color.black)); xAxis.setTextSize(8.0f); xAxis.setAxisLineColor(Color.parseColor("#48a8e0")); } private void initBarChartView() { barChart.setDescription(""); barChart.setPinchZoom(false); barChart.setDrawBarShadow(false); barChart.setDrawGridBackground(false); barChart.setScaleYEnabled(false); barChart.setScaleXEnabled(false); barChart.animateY(1000); barChart.setHighlightPerTapEnabled(false); barChart.setHighlightPerDragEnabled(false); // barChart.setMarkerView(markerView); // 柱状图说明 Legend l = barChart.getLegend(); l.setPosition(LegendPosition.ABOVE_CHART_LEFT); l.setYOffset(0f); l.setYEntrySpace(0f); l.setTextSize(10f); XAxis xAxis = barChart.getXAxis(); xAxis.setPosition(XAxisPosition.BOTTOM); xAxis.setTextColor(getResColor(R.color.black)); xAxis.setDrawGridLines(false); xAxis.setAxisLineColor(Color.parseColor("#48a8e0")); YAxis leftAxis = barChart.getAxisLeft(); leftAxis.setValueFormatter(new MyYAxisValueFormatter()); leftAxis.setTextColor(getResColor(R.color.text_gray_6)); leftAxis.setDrawGridLines(false); leftAxis.setSpaceTop(20f); leftAxis.setDrawAxisLine(false); barChart.getAxisRight().setEnabled(false); } /** * 点击事件 * * @param v */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_logout: // 注销登录 logout(); break; } } /** * 登出 */ private void logout() { UserUtil.clearUser(mActivity); JumpToActivity(LoginActivity.class); mActivity.finish(); } /** * 加载统计文字数据 */ private void bindAveTextView(StatisticsModel monthStatistics, StatisticsModel yearStatistics) { tv_month_num.setText(getString(R.string.label_inspection_month_num) + " " + monthStatistics.getInsSum() + " 单"); tv_month_finish.setText(getString(R.string.label_inspection_month_rale_finishing) + " " + (null == monthStatistics.getFinishRate() ? "0.0%" : monthStatistics.getFinishRate())); tv_month_passed.setText(getString(R.string.label_inspection_month_rale_qualified) + " " + (null == monthStatistics.getPassRate() ? "0.0%" : monthStatistics.getPassRate())); tv_month_timely.setText(getString(R.string.label_inspection_month_rale_timely) + " " + (null == monthStatistics.getInTimeRate() ? "0.0%" : monthStatistics.getInTimeRate())); tv_year_num.setText(getString(R.string.label_inspection_all_num) + " " + yearStatistics.getInsSum() + " 单"); tv_year_finish.setText(getString(R.string.label_inspection_all_rale_finishing) + " " + (null == yearStatistics.getFinishRate() ? "0.0%" : yearStatistics.getFinishRate())); tv_year_passed.setText(getString(R.string.label_inspection_all_rale_qualified) + " " + (null == yearStatistics.getPassRate() ? "0.0%" : yearStatistics.getPassRate())); tv_year_timely.setText(getString(R.string.label_inspection_all_rale_timely) + " " + (null == yearStatistics.getInTimeRate() ? "0.0%" : yearStatistics.getInTimeRate())); } /** * 巡检单单数统计图(月) */ private void bindcombinedChartData(List<StatisticsModel> statisticsList) { // 倒序 Collections.reverse(statisticsList); ArrayList<String> xVals = new ArrayList<String>(); ArrayList<BarEntry> barEntries = new ArrayList<BarEntry>(); ArrayList<Entry> lineEntries = new ArrayList<Entry>(); int i = 0; for (StatisticsModel model : statisticsList) { xVals.add(model.getMonth()); barEntries.add(new BarEntry(model.getInsSum(), i)); String valueS = model.getFinishRate(); float value = Float.parseFloat(valueS.substring(0, valueS.length() - 1)); lineEntries.add(new Entry(value, i)); i++; } BarData barData = new BarData(xVals, getBarData(barEntries)); topBarChart.setData(barData); topBarChart.invalidate(); LineData lineData = new LineData(xVals, getLineData(lineEntries)); lineChart.setData(lineData); lineChart.invalidate(); } private BarDataSet getBarData(ArrayList<BarEntry> barEntries) { BarDataSet set = new BarDataSet(barEntries, "巡检总单数"); set.setColor(Color.parseColor("#48a8e0")); set.setValueFormatter(new LargeValueFormatter()); return set; } private LineDataSet getLineData(ArrayList<Entry> lineEntries) { LineDataSet set = new LineDataSet(lineEntries, "完成率"); set.setColor(Color.parseColor("#eb5931")); set.setLineWidth(1.5f); set.setCircleColor(Color.parseColor("#eb5931")); set.setCircleSize(3f); set.setFillColor(Color.parseColor("#ffffff")); set.setValueTextSize(6f); set.setValueTextColor(Color.parseColor("#0000ff")); set.setDrawCubic(true); set.setDrawValues(true); set.setValueFormatter(new MyValueFormatter()); return set; } /** * 巡检单比例统计图 */ private void bindbarChartData(List<StatisticsModel> statisticsList) { // 横向名称 String[] name = getResources().getStringArray(R.array.statistics_ave_rate_name); List<String> xVals = Arrays.asList(name); ArrayList<BarEntry> year = new ArrayList<BarEntry>(); ArrayList<BarEntry> currentMonth = new ArrayList<BarEntry>(); for (StatisticsModel model : statisticsList) { if (TextUtils.isEmpty(model.getMonth())) { // 年 // 完成率 String valueS = model.getFinishRate(); float value = Float.parseFloat(valueS.substring(0, valueS.length() - 1)); year.add(new BarEntry(value, 0)); // 合格率 valueS = model.getPassRate(); value = Float.parseFloat(valueS.substring(0, valueS.length() - 1)); year.add(new BarEntry(value, 1)); // 及时率 valueS = model.getInTimeRate(); value = Float.parseFloat(valueS.substring(0, valueS.length() - 1)); year.add(new BarEntry(value, 2)); } else { // 月 // 完成率 String valueS = model.getFinishRate(); float value = Float.parseFloat(valueS.substring(0, valueS.length() - 1)); currentMonth.add(new BarEntry(value, 0)); // 合格率 valueS = model.getPassRate(); value = Float.parseFloat(valueS.substring(0, valueS.length() - 1)); currentMonth.add(new BarEntry(value, 1)); // 及时率 valueS = model.getInTimeRate(); value = Float.parseFloat(valueS.substring(0, valueS.length() - 1)); currentMonth.add(new BarEntry(value, 2)); } } // 2个分类颜色 BarDataSet set1 = new BarDataSet(year, "年度单数平均值"); set1.setColor(Color.parseColor("#48a8e0")); set1.setBarSpacePercent(0f); BarDataSet set2 = new BarDataSet(currentMonth, "当月单数平均值"); set2.setColor(Color.parseColor("#eb5931")); set2.setBarSpacePercent(0f); ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>(); dataSets.add(set1); dataSets.add(set2); BarData data = new BarData(xVals, dataSets); data.setValueFormatter(new MyValueFormatter()); data.setValueTextSize(10.0f); barChart.setData(data); barChart.invalidate(); } /** * 获取月巡检统计数据 */ private void getMonthInspection() { NetManager.getInstance(mActivity).getMonthInspection(mActivity.getProject().getShortCode(), new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { // 成功 List<StatisticsModel> statisticsList = JsonUtil.convertJsonToList(responeModel.getResult(), StatisticsModel.class); if (null != statisticsList) { bindcombinedChartData(statisticsList); } } else { // 失败 showToast(getResString(R.string.toast_get_failed)); // TODO topBarChart.setNoDataText("无统计数据"); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); // TODO topBarChart.setNoDataText("无统计数据"); } @Override public void onFinish() { super.onFinish(); swipeRefreshLayout.setRefreshing(false); } }); } /** * 获取巡检统计数据 */ private void getInspectionStatistics() { NetManager.getInstance(mActivity).getInspectionStatistics(mActivity.getProject().getShortCode(), new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { // 成功 List<StatisticsModel> statisticsList = JsonUtil.convertJsonToList(responeModel.getResult(), StatisticsModel.class); if (null != statisticsList && 1 < statisticsList.size()) { bindAveTextView(statisticsList.get(0), statisticsList.get(1)); bindbarChartData(statisticsList); } } else { // 失败 showToast(getResString(R.string.toast_get_failed)); // TODO barChart.setNoDataText("无统计数据"); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); // TODO barChart.setNoDataText("无统计数据"); } @Override public void onFinish() { super.onFinish(); swipeRefreshLayout.setRefreshing(false); } }); } private class MyYAxisValueFormatter implements YAxisValueFormatter { @Override public String getFormattedValue(float value, YAxis yAxis) { return (int) value + "%"; } } private class MyYAxisValueFormatter2 implements YAxisValueFormatter { @Override public String getFormattedValue(float value, YAxis yAxis) { return " " + (int) value + "%"; } } private class MyYAxisValueFormatter3 implements YAxisValueFormatter { private DecimalFormat mFormat; public MyYAxisValueFormatter3() { mFormat = new DecimalFormat("###,###,###,##0.0"); } @Override public String getFormattedValue(float value, YAxis yAxis) { return value > 1 ? value + "" : mFormat.format(value); } } private class MyValueFormatter implements ValueFormatter { private DecimalFormat mFormat; public MyValueFormatter() { mFormat = new DecimalFormat("###,###,###,##0.0"); } @Override public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) { return mFormat.format(value) + "%"; } } private class MyMarkerView extends MarkerView { private TextView tvContent; public MyMarkerView(Context context, int layoutResource, int tvID) { super(context, layoutResource); tvContent = (TextView) findViewById(tvID); } // callbacks everytime the MarkerView is redrawn, can be used to update // the // content (user-interface) @Override public void refreshContent(Entry e, Highlight highlight) { if (e instanceof CandleEntry) { CandleEntry ce = (CandleEntry) e; tvContent.setText(Utils.formatNumber(ce.getHigh(), 1, false) + "%"); } else { tvContent.setText(Utils.formatNumber(e.getVal(), 1, false) + "%"); } } @Override public int getXOffset(float xpos) { // this will center the marker-view horizontally return -(getWidth() / 2); } @Override public int getYOffset(float ypos) { // this will cause the marker-view to be above the selected value return -getHeight(); } } @Override public void refreshPage(RefreshModel refreshModel) { if (refreshModel.all) { initData(); } } } <file_sep>package com.ricelink.coolead.helper; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Environment; import android.view.Gravity; import android.widget.Toast; import com.ricelink.coolead.app.AppManager; import com.ricelink.coolead.app.activity.LoginActivity; import com.ricelink.coolead.v.R; /** * Activity帮助类 * * @author gavin.xiong */ public class UIHelper { public static int noticeSize; private static Toast toast; /** * @Description: 弹出提示信息 */ public static void ShowMessage(Context context, String message) { toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } /** * 得到当前时间 * * @return */ @SuppressLint("SimpleDateFormat") private static String getDate() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis()); return formatter.format(curDate); } /** * 刪除通知 * * @param context * 上下文 */ public static void clearNotification(Context context) { // 启动后删除之前我们定义的通知 NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE); notificationManager.cancel(0); } public static String GetFilePath(Context context) { String savePath = ""; // 判断是否挂载了SD卡 String storageState = Environment.getExternalStorageState(); if (storageState.equals(Environment.MEDIA_MOUNTED)) { savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/gavin.xiong/image";// 存放照片的文件夹 File savedir = new File(savePath); if (!savedir.exists()) { savedir.mkdirs(); } } // 没有挂载SD卡,无法保存文件 if (StringUtils.isEmpty(savePath)) { ShowMessage(context, "无法保存照片,请检查SD卡是否挂载"); return null; } else { return savePath; } } /** * 发送App异常崩溃报告 * * @param cont * @param crashReport */ public static void sendAppCrashReport(final Context cont, final String crashReport) { AlertDialog.Builder builder = new AlertDialog.Builder(cont); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(R.string.app_error); builder.setMessage(R.string.app_error_message); builder.setPositiveButton(R.string.submit_report, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // 发送异常报告 Intent i = new Intent(Intent.ACTION_SEND); // i.setType("text/plain"); //模拟器 i.setType("message/rfc822"); // 真机 i.putExtra(Intent.EXTRA_EMAIL, new String[] { "<EMAIL>" }); i.putExtra(Intent.EXTRA_SUBJECT, "开源中国Android客户端 - 错误报告"); i.putExtra(Intent.EXTRA_TEXT, crashReport); cont.startActivity(Intent.createChooser(i, "发送错误报告")); // 退出 AppManager.getAppManager().AppExit(cont); } }); builder.setNegativeButton(R.string.sure, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // 退出 AppManager.getAppManager().AppExit(cont); } }); builder.show(); } /** * 发送通知 * * @param context * 上下文 * @param title * 标题 * @param text * 内容 */ @SuppressLint("NewApi") private void showNotification(Context context, String ticker, String title, String content) { // 创建一个NotificationManager的引用 NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE); // 定义Notification的各种属性 Intent intent = new Intent(context, LoginActivity.class); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);// 关键的一步,设置启动模式 PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); Notification.Builder mBuilder = new Notification.Builder(context); mBuilder.setContentIntent(pendingIntent) // 点击事件 .setTicker(ticker) // 通知首次出现在通知栏,带上升动画效果的 // .setNumber(number) //设置通知集合的数量 .setContentTitle(title).setContentText(content).setSmallIcon(R.drawable.ic_launcher) // .setLargeIcon(bitmap) .setWhen(System.currentTimeMillis())// 通知产生的时间,会在通知信息里显示,一般是系统获取到的时间 .setPriority(Notification.PRIORITY_DEFAULT) // 设置该通知优先级 .setAutoCancel(true)// 设置这个标志当用户单击面板就可以让通知将自动取消 .setOngoing(false)// ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接) .setDefaults(Notification.DEFAULT_VIBRATE)// 向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合 // Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 添加声音 // // requires VIBRATE permission .setSmallIcon(R.drawable.ic_launcher); Notification notification = mBuilder.build();// 设置通知小ICON // Notification.FLAG_SHOW_LIGHTS //三色灯提醒,在使用三色灯提醒时候必须加该标志符 // Notification.FLAG_ONGOING_EVENT //发起正在运行事件(活动中) // Notification.FLAG_INSISTENT //让声音、振动无限循环,直到用户响应 (取消或者打开) // Notification.FLAG_ONLY_ALERT_ONCE //发起Notification后,铃声和震动均只执行一次 // Notification.FLAG_AUTO_CANCEL //用户单击通知后自动消失 // Notification.FLAG_NO_CLEAR //只有全部清除时,Notification才会清除 // ,不清楚该通知(QQ的通知无法清除,就是用的这个) // Notification.FLAG_FOREGROUND_SERVICE //表示正在运行的服务 notification.flags |= Notification.FLAG_AUTO_CANCEL; // 将此通知放到通知栏的"Ongoing"即"正在运行"组中 notification.flags |= Notification.FLAG_NO_CLEAR; // 表明在点击了通知栏中的"清除通知"后,此通知不清除,经常与FLAG_ONGOING_EVENT一起使用 notification.flags |= Notification.FLAG_SHOW_LIGHTS; notificationManager.notify(0, notification); } public static boolean isInBackground(Context context) { @SuppressWarnings("deprecation") List<RunningTaskInfo> tasksInfo = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1); if (tasksInfo.size() > 0) { if (context.getPackageName().equals(tasksInfo.get(0).topActivity.getPackageName())) { return false; } } return true; } } <file_sep>package com.ricelink.coolead.app.activity; import java.util.ArrayList; import java.util.List; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.adapter.DeviceAdapter; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.model.Device; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.ListResponeModel; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.ListView; /** * 设备选择页面 * * @author gavin.xiong * */ public class DeviceSelectActivity extends BaseActivity { private HeaderBar title; private EditText et_text; private ListView lv_device; private DeviceAdapter adapter; private List<Device> deviceList = new ArrayList<Device>(); public DeviceSelectActivity() { super(R.layout.activity_device_select); } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); et_text = (EditText) findViewById(R.id.et_text); lv_device = (ListView) findViewById(R.id.listview); } @Override public void initData() { adapter = new DeviceAdapter(this, deviceList); lv_device.setAdapter(adapter); getDeviceList(""); } @Override public void bindViews() { title.setTitle(R.string.label_select_device); lv_device.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putSerializable(Constants.INTENT_EXTRA_DEVICE, deviceList.get(arg2)); intent.putExtras(bundle); setResult(Activity.RESULT_OK, intent); DeviceSelectActivity.this.finish(); } }); et_text.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void afterTextChanged(Editable s) { getDeviceList(s.toString()); } }); } /** * 查询设备巡检内容 */ private void getDeviceList(String text) { NetManager.getInstance(this).getDeviceList(text, getProject().getShortCode(), new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); ListResponeModel listResponse = JsonUtil.convertJsonToObject(responeModel.getResult(), ListResponeModel.class); if (null != listResponse) { // 成功 List<Device> list = JsonUtil.convertJsonToList(listResponse.getList(), Device.class); deviceList.clear(); if (null == list){ list = new ArrayList<Device>(); } deviceList.addAll(list); adapter.notifyDataSetChanged(); } else { // 失败 showToast(getString(R.string.toast_get_failed) + responeModel.getMessage()); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); } @Override public void onFinish() { super.onFinish(); } }); } } <file_sep>package com.ricelink.coolead.app.view; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * 开关 */ public class SlipButton extends View { private boolean NowChoose = false;// 记录当前按钮是否打开,true为打开,flase为关闭 private boolean isChecked; private boolean OnSlip = false;// 记录用户是否在滑动的变量 private float NowX;// 按下时的x,当前的x private RectF rectF, rectF_slip; private boolean isChgLsnOn = false; private OnChangedListener ChgLsn; private Paint paint; private final int colo_bg_on = 0xFF4092d7; private final int colo_bg_off = 0xFFb2b2b2; private final int colo_bg_slip = Color.WHITE; // 是否在viewpager中,如果在需要拦截触摸事件 private ViewPager pager; public SlipButton(Context context) { super(context); init(); } public SlipButton(Context context, AttributeSet attrs) { super(context, attrs); init(); } public SlipButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void setPager(ViewPager pager) { this.pager = pager; } private void init() {// 初始化 paint = new Paint(); paint.setAntiAlias(true); rectF = new RectF(); rectF_slip = new RectF(); } public float dip2Px(Context context, float defDip) { float f = context.getResources().getDisplayMetrics().density; return defDip * f + 0.5f; } private int viewW, viewH; @Override protected void onDraw(Canvas canvas) {// 绘图函数 super.onDraw(canvas); // 清屏 canvas.drawColor(Color.TRANSPARENT); viewW = getWidth(); viewH = getHeight(); // 背景矩形大小 rectF.left = 0; rectF.top = 0; rectF.right = viewW; rectF.bottom = viewH; float x; if (!NowChoose) { // 画出关闭时的背景 paint.setColor(colo_bg_off); canvas.drawRoundRect(rectF, viewH / 2, viewH / 2, paint); } else { // 画出打开时的背景 paint.setColor(colo_bg_on); canvas.drawRoundRect(rectF, viewH / 2, viewH / 2, paint); } if (OnSlip)// 是否是在滑动状态, { if (NowX >= viewW)// 是否划出指定范围,不能让游标跑到外头,必须做这个判断 x = viewW - viewH / 2;// 减去游标1/2的长度... else if (NowX < 0) { x = 0; } else { x = NowX - viewH / 2; } } else {// 非滑动状态 if (NowChoose)// 根据现在的开关状态设置画游标的位置 { x = viewW - viewH; // 初始状态为true时应该画出打开状态图片 paint.setColor(colo_bg_on); canvas.drawRoundRect(rectF, viewH / 2, viewH / 2, paint); paint.setColor(Color.WHITE); } else { x = 0; paint.setColor(colo_bg_off); canvas.drawRoundRect(rectF, viewH / 2, viewH / 2, paint); } } if (isChecked) { paint.setColor(colo_bg_on); canvas.drawRoundRect(rectF, viewH / 2, viewH / 2, paint); paint.setColor(Color.WHITE); x = viewW - viewH; isChecked = !isChecked; } if (x < 0)// 对游标位置进行异常判断... x = 0; else if (x > viewW - viewH) x = viewW - viewH; // 游标的矩形 rectF_slip.left = x + 2; rectF_slip.top = 2; rectF_slip.right = x + viewH - 2; rectF_slip.bottom = viewH - 2; paint.setColor(colo_bg_slip); canvas.drawRoundRect(rectF_slip, viewH / 2, viewH / 2, paint); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { if (!isEnabled()) { return false; } switch (event.getAction()){ // 根据动作来执行代码 case MotionEvent.ACTION_MOVE:// 滑动 if (pager != null) { pager.requestDisallowInterceptTouchEvent(true); } OnSlip = true; NowX = event.getX(); break; case MotionEvent.ACTION_DOWN:// 按下 if (event.getX() > viewW || event.getY() > viewH) return false; // DownX = event.getX(); // NowX = DownX; break; case MotionEvent.ACTION_CANCEL: // 移到控件外部 OnSlip = false; boolean choose = NowChoose; if (NowX >= (viewW / 2)) { NowX = viewW - viewH / 2; NowChoose = true; } else { NowX = NowX - viewH / 2; NowChoose = false; } if (isChgLsnOn && (choose != NowChoose)) // 如果设置了监听器,就调用其方法.. { ChgLsn.OnChanged(NowChoose); } if (pager != null) { pager.requestDisallowInterceptTouchEvent(false); } break; case MotionEvent.ACTION_UP:// 松开 OnSlip = false; boolean LastChoose = NowChoose; NowChoose = !NowChoose; if (isChgLsnOn && (LastChoose != NowChoose)) // 如果设置了监听器,就调用其方法.. ChgLsn.OnChanged(NowChoose); break; default: } invalidate();// 重画控件 return true; } public void SetOnChangedListener(OnChangedListener l) {// 设置监听器,当状态修改的时候 isChgLsnOn = true; ChgLsn = l; } public interface OnChangedListener { abstract void OnChanged(boolean checkState); } public void setCheck(boolean isChecked) { this.isChecked = isChecked; NowChoose = isChecked; } }<file_sep>package com.ricelink.coolead.helper; import android.annotation.SuppressLint; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @SuppressLint("SimpleDateFormat") public class DateUtil { public static Date date = null; public static DateFormat dateFormat = null; public static Calendar calendar = null; public static String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; public static Date getDate(String dateTime, String formet) { java.text.SimpleDateFormat format = new java.text.SimpleDateFormat( formet); Date date = null; try { date = format.parse(dateTime); return date; } catch (ParseException e) { e.printStackTrace(); } return null; } public static Date parseDate(String dateStr, String format) { try { dateFormat = new SimpleDateFormat(format); String dt = dateStr.replaceAll("-", "/"); if ((!dt.equals("")) && (dt.length() < format.length())) { dt += format.substring(dt.length()).replaceAll("[YyMmDdHhSs]", "0"); } date = (Date) dateFormat.parse(dt); } catch (Exception e) { } return date; } public static Date parseDate(String dateStr) { return parseDate(dateStr, "yyyy-MM-dd"); } public static String format(Date date, String format) { String result = ""; try { if (date != null) { dateFormat = new SimpleDateFormat(format); result = dateFormat.format(date); } } catch (Exception e) { } return result; } public static String format(Date date) { return format(date, "yyyy-MM-dd"); } public static int getYear(Date date) { calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.YEAR); } public static int getMonth(Date date) { calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.MONTH) + 1; } public static int getDay(Date date) { calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_MONTH); } public static int getHour(Date date) { calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.HOUR_OF_DAY); } public static int getMinute(Date date) { calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.MINUTE); } public static int getSecond(Date date) { calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.SECOND); } public static long getMillis(Date date) { calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.getTimeInMillis(); } public static String getDate(Date date) { return format(date, "yyyy-MM-dd"); } public static String getTime(Date date) { return format(date, "HH:mm:ss"); } public static String getDateTime(Date date) { return format(date, "yyyy-MM-dd HH:mm:ss"); } public static String getDateMonth(Date date, String string) { return format(date, string); } /** * 判断开始时间和结束时间哪个大 * * @param str * @return */ public static boolean isFirstLagre(String startTime, String endTime, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); Date d = null; Date d2 = null; try { d = sdf.parse(startTime); d2 = sdf.parse(endTime); long startLong = d.getTime(); long endLong = d2.getTime(); return startLong > endLong ? true : false; } catch (java.text.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } /** * 判断当前时间是否比当前时间大 * * @param str * @return */ public static boolean isCurrentLagre(String anyTime, String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); Date d = null; try { d = sdf.parse(anyTime); long currentLong = System.currentTimeMillis(); long endLong = d.getTime(); return currentLong > endLong ? true : false; } catch (java.text.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } public static Date addDate(Date date, int day) { calendar = Calendar.getInstance(); long millis = getMillis(date) + ((long) day) * 24 * 3600 * 1000; calendar.setTimeInMillis(millis); return calendar.getTime(); } public static Date addDate_m(Date date, int minute) { calendar = Calendar.getInstance(); long millis = getMillis(date) + ((long) minute) * 60 * 1000; calendar.setTimeInMillis(millis); return calendar.getTime(); } public static int diffDate(Date date, Date date1) { return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000)); } public static String getMonthBegin(String strdate) { date = parseDate(strdate); return format(date, "yyyy-MM") + "-01"; } public static String getMonthEnd(String strdate) { date = parseDate(getMonthBegin(strdate)); calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, 1); calendar.add(Calendar.DAY_OF_YEAR, -1); return formatDate(calendar.getTime()); } public static String formatDate(Date date) { return formatDateByFormat(date, "yyyy-MM-dd"); } public static String formatDateByFormat(Date date, String format) { String result = ""; if (date != null) { try { SimpleDateFormat sdf = new SimpleDateFormat(format); result = sdf.format(date); } catch (Exception ex) { ex.printStackTrace(); } } return result; } public static String getWeek(String pTime) { String Week = ""; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); try { c.setTime(format.parse(pTime)); } catch (ParseException e) { e.printStackTrace(); } Week = weekDays[c.get(Calendar.DAY_OF_WEEK) - 1]; // if (c.get(Calendar.DAY_OF_WEEK) == 1) { // Week += "星期天"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 2) { // Week += "星期一"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 3) { // Week += "星期二"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 4) { // Week += "星期三"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 5) { // Week += "星期四"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 6) { // Week += "星期五"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 7) { // Week += "星期六"; // } return Week; } public static String getWeek(Calendar c) { String Week = ""; // if (c.get(Calendar.DAY_OF_WEEK) == 1) { // Week += "星期天"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 2) { // Week += "星期一"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 3) { // Week += "星期二"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 4) { // Week += "星期三"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 5) { // Week += "星期四"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 6) { // Week += "星期五"; // } // if (c.get(Calendar.DAY_OF_WEEK) == 7) { // Week += "星期六"; // } Week = weekDays[c.get(Calendar.DAY_OF_WEEK) - 1]; return Week; } } <file_sep>package com.ricelink.coolead.model; import com.lidroid.xutils.db.annotation.Column; import com.lidroid.xutils.db.annotation.Id; import com.lidroid.xutils.db.annotation.NoAutoIncrement; import com.lidroid.xutils.db.annotation.Table; /** * 项目 * * @author gavin.xiong * */ @Table(name = "project") public class Project extends BaseModel { /** * */ private static final long serialVersionUID = 1L; /** * id */ @Id @NoAutoIncrement private long id; @Column(column = "divisionId") private long divisionId; @Column(column = "communityId") private long communityId; @Column(column = "fullCode") private String fullCode; @Column(column = "name") private String name; @Column(column = "shortCode") private String shortCode; @Column(column = "shortName") private String shortName; @Column(column = "fullName") private String fullName; @Column(column = "sortNum") private int sortNum; @Column(column = "isActive") private int isActive; @Column(column = "createUser") private String createUser; @Column(column = "createTime") private long createTime; @Column(column = "type") private String type; @Column(column = "users") private String users; @Column(column = "children") private String children; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getDivisionId() { return divisionId; } public void setDivisionId(long divisionId) { this.divisionId = divisionId; } public long getCommunityId() { return communityId; } public void setCommunityId(long communityId) { this.communityId = communityId; } public String getFullCode() { return fullCode; } public void setFullCode(String fullCode) { this.fullCode = fullCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getShortCode() { return shortCode; } public void setShortCode(String shortCode) { this.shortCode = shortCode; } public String getShortName() { return shortName; } public void setShortName(String shortName) { this.shortName = shortName; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public int getSortNum() { return sortNum; } public void setSortNum(int sortNum) { this.sortNum = sortNum; } public int getIsActive() { return isActive; } public void setIsActive(int isActive) { this.isActive = isActive; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getUsers() { return users; } public void setUsers(String users) { this.users = users; } public String getChildren() { return children; } public void setChildren(String children) { this.children = children; } @Override public String toString() { return "Project [id=" + id + ", divisionId=" + divisionId + ", communityId=" + communityId + ", fullCode=" + fullCode + ", name=" + name + ", shortCode=" + shortCode + ", shortName=" + shortName + ", fullName=" + fullName + ", sortNum=" + sortNum + ", isActive=" + isActive + ", createUser=" + createUser + ", createTime=" + createTime + ", type=" + type + ", users=" + users + ", children=" + children + "]"; } } <file_sep>package com.ricelink.coolead.net; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.AndFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.Registration; import org.jivesoftware.smack.packet.XMPPError; import org.json.JSONException; import org.json.JSONObject; import com.loopj.android.http.RequestParams; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.helper.JsonHelper; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.helper.L; import com.ricelink.coolead.model.DealWithDetail; import com.ricelink.coolead.model.EqRouteIdsModel; import com.ricelink.coolead.model.MaterialModel; import com.ricelink.coolead.model.OrderRouteIdsModel; import com.ricelink.coolead.model.SaveInspectionContentModel; import android.content.Context; public class NetManager { private static final String TAG = "NetManager"; // private static final String TAG = "NetManager"; // 内部全局唯一实例 private static NetManager mInstance; private static CustomAsyncHttpClient httpClient; static public NetManager getInstance(Context context) { httpClient = new CustomAsyncHttpClient(context); if (mInstance == null) { // 只有第一次才彻底执行这里的代码 synchronized (NetManager.class) { // 再检查一次 if (mInstance == null) mInstance = new NetManager(); } } return mInstance; } /** * IM登陆 * * @param userName * 用户名 * @param password * 密码 * @return */ public static int loginIM(String userName, String password) { L.v(TAG, "loginIM()"); try { XMPPConnection connection = AppContext.connectionManager.getConnection(); if (!connection.isConnected()) { connection.connect(); } connection.login(userName, password, connection.getServiceName()); // OfflineMsgManager.getInstance(activitySupport).dealOfflineMsg(connection);//处理离线消息 // 默认在线状态 connection.sendPacket(new Presence(Presence.Type.available)); return Constants.LOGIN_SECCESS; } catch (XMPPException xe) { XMPPError error = xe.getXMPPError(); int errorCode = 0; if (error != null) { errorCode = error.getCode(); } if (errorCode == 401) { return Constants.LOGIN_ERROR_ACCOUNT_PASS; } else if (errorCode == 403) { return Constants.LOGIN_ERROR_ACCOUNT_PASS; } else { return Constants.SERVER_UNAVAILABLE; } } catch (Exception e) { return Constants.LOGIN_ERROR; } finally { // SkyChatApplication.connectionManager.disconnect(); } } /** * IM注册 * * @param userName * 账号 * @param password * 密码 */ public IQ registerIM(String userName, String password) { Registration registration = new Registration(); registration.setType(IQ.Type.SET); registration.setTo(AppContext.connectionManager.getConnection().getServiceName()); // registration.setUsername(account); // registration.setPassword(<PASSWORD>); Map<String, String> map = new HashMap<String, String>(); map.put("username", userName); map.put("password", <PASSWORD>); // registration.addAttribute("android", // "geolo_createUser_android"); registration.setAttributes(map); System.out.println("reg:" + registration); IQ iq = null; try { if (!AppContext.connectionManager.getConnection().isConnected()) { AppContext.connectionManager.getConnection().connect(); } PacketFilter filter = new AndFilter(new PacketIDFilter(registration.getPacketID()), new PacketTypeFilter(IQ.class)); PacketCollector collector = AppContext.connectionManager.getConnection().createPacketCollector(filter); AppContext.connectionManager.getConnection().sendPacket(registration); iq = (IQ) collector.nextResult(Constants.CONNECT_TIMEOUT); collector.cancel(); } catch (XMPPException e) { e.printStackTrace(); } return iq; } /** * 上传图片 */ public void upLoadImage(long orderId, String step, String imgPath, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); params.put("orderId", orderId); params.put("step", step); try { params.put("image", new File(imgPath)); } catch (FileNotFoundException e) { e.printStackTrace(); } requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.APP_UPLOAD_IMAGE); requestModel.setParams(params); requestModel.setEntity(null); httpClient.post(requestModel, handler); } /** * 检测新版本 */ public void checkVersions(boolean showDiolog, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("code", "mobileapp"); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(showDiolog); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.APP_CHECK_VERSIONS); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 登陆 * * @param userName * 账号 * @param password * 密码 */ public void login(String userName, String password, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("userName", userName); jsonObject.put("password", <PASSWORD>); jsonObject.put("grantType", "password"); jsonObject.put("refreshToken", null); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.USER_LOGIN); requestModel.setJson(jsonObject.toString()); requestModel.setCheckToken(false); httpClient.postJson(requestModel, handler); } /** * 获取用户权限 * * @param handler */ public void getUserRole(CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); requestModel.setShowDialog(false); requestModel.setShowErrorMessage(false); requestModel.setUrl(Urls.USER_GET_ROLE); requestModel.setParams(params); httpClient.get(requestModel, handler); } /** * 修改密码 * * @param userName * 账号 * @param password * 密码 */ public void updatePassword(long userId, String passWord, String newPassWord, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("userId", userId); jsonObject.put("passWord", <PASSWORD>); jsonObject.put("newPassWord", <PASSWORD>); L.v(jsonObject); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.USER_UPDATE_PASSWORD); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 获取项目列表 */ public void getProjectList(boolean showDialog, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); requestModel.setShowDialog(showDialog); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.WORKORDER_GET_PROJECT_LIST); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 获取设备列表 */ public void getDeviceList(String name, String projectCode, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); JSONObject jsonObject2 = new JSONObject(); try { jsonObject2.put("name", name); jsonObject2.put("projectCode", projectCode); jsonObject.put("entity", jsonObject2); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(true); requestModel.setShowErrorMessage(false); requestModel.setUrl(Urls.WORKORDER_GET_EQUIPMENT_LIST); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 获取待办工单列表 */ public void getWorkOrderBacklog(String projectCode, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); requestModel.setShowDialog(false); requestModel.setShowErrorMessage(false); requestModel.setUrl(String.format(Urls.WORKORDER_GET_WORKORDER_BACKLOG, projectCode)); httpClient.get(requestModel, handler); } /** * 认领任务 */ public void claimTask(long taskId, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); requestModel.setShowDialog(true); requestModel.setShowErrorMessage(false); requestModel.setUrl(String.format(Urls.WORKORDER_CLAIM_TASKS, taskId)); httpClient.get(requestModel, handler); } /** * 根据状态获取所有工单列表 */ public void getWorkOrderList(String status, String projectCode, boolean padding, int offset, int limit, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("offset", offset); jsonObject.put("limit", limit); JSONObject entity = new JSONObject(); if (null != status) entity.put("status", status); entity.put("padding", padding); entity.put("projectCode", projectCode); entity.put("isMobile", true); jsonObject.put("entity", entity); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.WORKORDER_GET_WORKORDER_LIST_MY); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 获取工单详情 */ public void getWorkorderDetails(long id, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(String.format(Urls.WORKORDER_GET_WORKORDER_DETAILS, id + "")); requestModel.setParams(params); httpClient.get(requestModel, handler); } /** * 获取工单进度 */ public void getWorkorderProgress(long id, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); requestModel.setShowDialog(false); requestModel.setShowErrorMessage(false); requestModel.setUrl(String.format(Urls.WORKORDER_GET_WORKORDER_PROGRESS, id + "")); requestModel.setParams(params); httpClient.get(requestModel, handler); } /** * 获取工单可派发人员列表 */ public void managerGetCandidates(long workFlowId, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(String.format(Urls.WORKORDER_GET_CANDIDATES, workFlowId + "")); requestModel.setParams(params); httpClient.get(requestModel, handler); } /** * 主管处理 */ public void managerDealWith(long workFlowId, int distribution_type, String candidate, String eq_code, String plan_end_time, String remark, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("candidate", candidate); jsonObject.put("ysl", null); // ??? if (null != eq_code) jsonObject.put("eq_code", eq_code); jsonObject.put("distribution_type", distribution_type + ""); jsonObject.put("plan_end_time", plan_end_time); jsonObject.put("remark", remark); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(String.format(Urls.WORKORDER_HANDLE, workFlowId + "")); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 处理人处理 */ public void assignDealWith(long orderId, String remark, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("remark", remark); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(String.format(Urls.WORKORDER_HANDLE, orderId + "")); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 验收人处理 */ public void acceptorDealWith(long orderId, String is_in_time, String is_qualified, String remark, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("remark", remark); jsonObject.put("is_in_time", is_in_time); jsonObject.put("is_qualified", is_qualified); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(String.format(Urls.WORKORDER_HANDLE, orderId + "")); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 结束巡检 */ public void finishInspection(long orderId, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(String.format(Urls.WORKORDER_HANDLE, orderId + "")); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 批量添加明细 */ public void addMaterial(long orderId, List<DealWithDetail> details, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); MaterialModel mm = new MaterialModel(); mm.setOrderId(orderId); mm.setList(details); requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.WORKORDER_ADD_MATERIAL); requestModel.setJson(JsonUtil.convertObjectToJson(mm)); httpClient.postJson(requestModel, handler); } /** * 获取发起工单准备数据 */ public void getAppData(CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); requestModel.setShowDialog(true); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.WORKORDER_GET_WORKORDER_DATA); requestModel.setParams(params); httpClient.get(requestModel, handler); } /** * 发起工单 * * @param projectId * @param address * @param reporter * @param title * @param imgUrl * @param handler */ public void addWorkOrder(String project_code, String title, String address, String resource, int level, String reporter, String content, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("project_code", project_code); jsonObject.put("title", title); jsonObject.put("address", address); jsonObject.put("resource", resource); jsonObject.put("level", level); jsonObject.put("reporter", reporter); jsonObject.put("content", content); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(true); requestModel.setShowErrorMessage(false); requestModel.setUrl(Urls.WORKORDER_ADD_WORKORDER); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 获取今日巡检列表 */ public void getInspectionTodayList(int projectId, int offset, int limit, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("offset", offset); jsonObject.put("limit", limit); JSONObject entity = new JSONObject(); entity.put("projectId", projectId); jsonObject.put("entity", entity); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.INSPECTION_GET_INSPECTIONS_TODAY); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 获取历史巡检列表 */ public void getInspectionHistoryList(String date, int projectId, int offset, int limit, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("offset", offset); jsonObject.put("limit", limit); JSONObject entity = new JSONObject(); entity.put("planTime", date); entity.put("projectId", projectId); jsonObject.put("entity", entity); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.INSPECTION_GET_INSPECTIONS_HISTORY); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 获取巡检列表 新 */ public void getInspectionNew(String date, String projectCode, int dateType, int offset, int limit, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("projectCode", projectCode); jsonObject.put("dateType", dateType); if (dateType == 2) { jsonObject.put("startDate", date); jsonObject.put("endDate", date); } } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.INSPECTION_GET_INSPECTIONS_2); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 获取巡检统计数据(按月分) */ public void getMonthInspection(String projectCode, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("projectCode", projectCode); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.INSPECTION_GET_MONTH_STATISTICS); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 获取巡检统计数据(下方) */ public void getInspectionStatistics(String projectCode, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(String.format(Urls.INSPECTION_GET_INSPECTIONS_STATISTICS, projectCode)); requestModel.setParams(params); httpClient.get(requestModel, handler); } /** * 巡检线路设备详情 */ public void getInspectionRoute(List<OrderRouteIdsModel> ids, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); requestModel.setShowDialog(true); requestModel.setShowErrorMessage(false); requestModel.setUrl(Urls.INSPECTION_GET_INSPECTIONS_ROUTE); requestModel.setJson(JsonUtil.convertObjectToJson(ids)); httpClient.postJson(requestModel, handler); } /** * 查询设备巡检内容 */ public void getInspectionEqContent(List<EqRouteIdsModel> ids, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); requestModel.setShowDialog(true); requestModel.setShowErrorMessage(false); requestModel.setUrl(Urls.INSPECTION_GET_INSPECTIONS_EQUIPMENT_CONTENT); requestModel.setJson(JsonUtil.convertObjectToJson(ids)); httpClient.postJson(requestModel, handler); } /** * 上传巡检数据 */ public void saveInspectionStatus(List<SaveInspectionContentModel> contentList, boolean showDialog, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); requestModel.setShowDialog(showDialog); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.INSPECTION_SAVE_INSPECTIONS_EQUIPMENT_CONTENT_DATA); requestModel.setJson(JsonHelper.tojson(contentList)); requestModel.setCheckNetStatus(false); httpClient.postJson(requestModel, handler); } /** * 我的需求 */ public void getMyServer(int offset, int limit, String questionUser, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("offset", offset); jsonObject.put("limit", limit); JSONObject entity = new JSONObject(); entity.put("questionUser", questionUser); jsonObject.put("entity", entity); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.ONLINE_GET_SERVER_MY); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } /** * 需求添加 - 发起互动 */ public void addServer(String projectCode, String questionTitle, String questionContent, String file, String image, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); params.put("projectCode", projectCode); params.put("questionTitle", questionTitle); params.put("questionContent", questionContent); if (null != file) params.put("file", file); if (null != image) params.put("image", image); requestModel.setShowDialog(true); requestModel.setShowErrorMessage(false); requestModel.setUrl(Urls.ONLINE_ADD_SERVER); requestModel.setParams(params); httpClient.post(requestModel, handler); } /** * 获取所有参与的未关闭的房间id */ public void getServerAllIds(String userCode, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(String.format(Urls.ONLINE_GET_SERVER_ALL_IDS, userCode)); requestModel.setParams(params); httpClient.get(requestModel, handler); } /** * 获取需求详情 */ public void getServerInfo(String id, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); RequestParams params = new RequestParams(); requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(String.format(Urls.ONLINE_GET_SERVER_INFO, id)); requestModel.setParams(params); httpClient.get(requestModel, handler); } /** * 同步消息 */ public void syncMessage(String questionId, String answerContent, String answerUser, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("questionId", questionId); jsonObject.put("answerContent", answerContent); jsonObject.put("answerUser", answerUser); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(false); requestModel.setShowErrorMessage(true); requestModel.setUrl(Urls.ONLINE_SYNC_MESSAGE); requestModel.setJson("[" + jsonObject.toString() + "]"); httpClient.postJson(requestModel, handler); } /** * 获取消息列表 */ public void getServiceMessageList(long questionId, int limit, int offset, CustomAsyncResponehandler handler) { RequestModel requestModel = new RequestModel(); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("limit", limit); jsonObject.put("offset", offset); JSONObject entity = new JSONObject(); entity.put("questionId", questionId); jsonObject.put("entity", entity); } catch (JSONException e) { e.printStackTrace(); } requestModel.setShowDialog(true); requestModel.setShowErrorMessage(false); requestModel.setUrl(Urls.ONLINE_GET_SERVER_MESSAGE_LIST); requestModel.setJson(jsonObject.toString()); httpClient.postJson(requestModel, handler); } } <file_sep>package com.ricelink.coolead.model; /** * 批量获取设备巡检项的id集 * * @author gavin.xiong * */ public class OrderRouteIdsModel { private long orderId; private long routeId; public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public long getRouteId() { return routeId; } public void setRouteId(long routeId) { this.routeId = routeId; } } <file_sep>package com.ricelink.coolead.model; /** * 用户配置 model * * 用于存 SharedPreferences * * @author gavin.xiong * */ public class ConfigModel { /** * 离线模式是否开启 */ private boolean isOffline; private boolean hasNewVersion; private String newVersionName; private String notifyUpdateDate; public boolean isOffline() { return isOffline; } public void setOffline(boolean isOffline) { this.isOffline = isOffline; } public boolean isHasNewVersion() { return hasNewVersion; } public void setHasNewVersion(boolean hasNewVersion) { this.hasNewVersion = hasNewVersion; } public String getNewVersionName() { return newVersionName; } public void setNewVersionName(String newVersionName) { this.newVersionName = newVersionName; } public String getNotifyUpdateDate() { return notifyUpdateDate; } public void setNotifyUpdateDate(String notifyUpdateDate) { this.notifyUpdateDate = notifyUpdateDate; } } <file_sep>package com.ricelink.coolead.app; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import com.lidroid.xutils.DbUtils; import com.lidroid.xutils.DbUtils.DaoConfig; import com.lidroid.xutils.DbUtils.DbUpgradeListener; import com.lidroid.xutils.exception.DbException; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer; import com.ricelink.coolead.Constants; import com.ricelink.coolead.helper.SettingManager; import com.ricelink.coolead.helper.UserUtil; import com.ricelink.coolead.model.IMMessage; import com.ricelink.coolead.model.InspectionContent; import com.ricelink.coolead.model.InspectionItem; import com.ricelink.coolead.model.User; import com.ricelink.coolead.model.WorkOrder; import com.ricelink.coolead.v.R; import com.ricelink.coolead.xmpp.XmppConnectionManager; import android.app.Application; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.media.AudioManager; import android.widget.ImageView; /** * 全局应用程序类:用于保存和调用全局应用配置及访问网络数据 * * @author gavin.xiong */ public class AppContext extends Application { public static final int NETTYPE_WIFI = 0x01; public static final int NETTYPE_CMWAP = 0x02; public static final int NETTYPE_CMNET = 0x03; public static final int PAGE_SIZE = 20;// 默认分页大小 public static final int YES = 1; public static final int NOT = 2; private static AppContext application; public static ImageLoader imageLoader; public static DisplayImageOptions options; public static DbUtils dbUtils; public final String DB_NAME = "coolead.db"; public final int DB_VERSION = 1; public static User user = new User(); /** 参数配置 */ public static SettingManager settingManager; /** xmpp连接管理对象 */ public static XmppConnectionManager connectionManager; @Override public void onCreate() { super.onCreate(); application = this; initDbUtils(); initImageLoader(); settingManager = SettingManager.getInstance(this, Constants.SHAREDPREFERENCESNAME); connectionManager = XmppConnectionManager.getInstance(); } /** * 初始化数据库 */ private void initDbUtils() { // sqlite 数据库 DaoConfig mDaoConfig = new DaoConfig(application); mDaoConfig.setDbName(DB_NAME); mDaoConfig.setDbVersion(DB_VERSION); mDaoConfig.setDbUpgradeListener(new DbUpgradeListener() { @Override public void onUpgrade(DbUtils arg0, int arg1, int arg2) {} }); dbUtils = AppContext.getDbUtils(mDaoConfig); dbUtils.configDebug(true); // 创建和表 try { // 消息 dbUtils.createTableIfNotExist(IMMessage.class); // 巡检 dbUtils.createTableIfNotExist(WorkOrder.class); // 巡检路线 dbUtils.createTableIfNotExist(InspectionItem.class); // 巡检内容 dbUtils.createTableIfNotExist(InspectionContent.class); } catch (DbException e) { e.printStackTrace(); } } /** * 初始化 imageLoader */ private void initImageLoader() { imageLoader = ImageLoader.getInstance(); imageLoader.init(ImageLoaderConfiguration.createDefault(this)); // ImageLoader.getInstance().init(config); options = new DisplayImageOptions.Builder()// // .showImageOnLoading(R.drawable.loding_img) // // .showImageForEmptyUri(R.drawable.ic_logo_bg_01) // // .showImageOnFail(R.drawable.ic_logo_bg_01) // .resetViewBeforeLoading(false) // default .delayBeforeLoading(0).cacheInMemory(true) // default .cacheOnDisk(true) // default .considerExifParams(false) // default .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default .bitmapConfig(Bitmap.Config.RGB_565) // default .displayer(new SimpleBitmapDisplayer()) // default // .handler(new Handler()) // default .build(); } @Override public void onTerminate() { dbUtils.close(); dbUtils = null; super.onTerminate(); } public static AppContext getApplication() { return application; } /** * 检测当前系统声音是否为正常模式 * * @return */ public boolean isAudioNormal() { AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE); return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL; } /** * 应用程序是否发出提示音 * * @return */ public boolean isAppSound() { return isAudioNormal(); } /** * 判断当前版本是否兼容目标版本的方法 * * @param VersionCode * @return */ public static boolean isMethodsCompat(int VersionCode) { int currentVersion = android.os.Build.VERSION.SDK_INT; return currentVersion >= VersionCode; } /** * 获取App安装包信息 * * @return */ public PackageInfo getPackageInfo() { PackageInfo info = null; try { info = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException e) { e.printStackTrace(System.err); } if (info == null) info = new PackageInfo(); return info; } /** * 保存磁盘缓存 * * @param key * @param value * @throws IOException */ public void setDiskCache(String key, String value) throws IOException { FileOutputStream fos = null; try { fos = openFileOutput("cache_" + key + ".data", Context.MODE_PRIVATE); fos.write(value.getBytes()); fos.flush(); } finally { try { fos.close(); } catch (Exception e) {} } } /** * 获取磁盘缓存数据 * * @param key * @return * @throws IOException */ public String getDiskCache(String key) throws IOException { FileInputStream fis = null; try { fis = openFileInput("cache_" + key + ".data"); byte[] datas = new byte[fis.available()]; fis.read(datas); return new String(datas); } finally { try { fis.close(); } catch (Exception e) {} } } public static void setImage(String url, ImageView imageView) { imageLoader.displayImage(url, imageView, options); } public static void setImage(String url, ImageView imageView, int res) { DisplayImageOptions options = new DisplayImageOptions.Builder() // // .showImageOnLoading(res) // .showImageForEmptyUri(res) // .showImageOnFail(res) // .cacheInMemory(true) // .cacheOnDisk(true) // .bitmapConfig(Bitmap.Config.RGB_565) // .build(); imageLoader.displayImage(url, imageView, options); } /** * 获取当前用户信息 * * @return */ public static User getUser() { return UserUtil.getUser(application); } /** * 保存当前用户信息 * * @return */ public static void saveUser(User user) { UserUtil.saveUser(application, user); } /** * * @return */ public static DbUtils getDbUtils(DaoConfig mDaoConfig) { if (dbUtils == null) { dbUtils = DbUtils.create(mDaoConfig); } return dbUtils; } /** * 网络配置信息 */ public static String getHeadUrl(){ return application.getString(R.string.head_url); } public static String getImageUrl(){ return application.getString(R.string.image_url); } public static String getImHost(){ return application.getString(R.string.im_host); } public static Integer getImPort(){ return Integer.valueOf(application.getString(R.string.im_port)); } public static String getImServiceName(){ return application.getString(R.string.im_service_name); } } <file_sep>package com.ricelink.coolead.app.activity; import java.util.List; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smackx.muc.MultiUserChat; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.app.adapter.ChatAdapter; import com.ricelink.coolead.app.adapter.ChatAdapter.OnReSendListener; import com.ricelink.coolead.app.view.EditChatLayout; import com.ricelink.coolead.app.view.EditChatLayout.OnWidgetClickListener; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.helper.StringUtils; import com.ricelink.coolead.model.IMMessage; import com.ricelink.coolead.model.IMessage; import com.ricelink.coolead.model.Server; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.view.View; import android.view.View.OnClickListener; import android.widget.ListView; /** * 聊天activity * * @author bruce.chen * */ public class ChatActivity extends BaseChatActivity implements OnWidgetClickListener { // 编辑布局 private EditChatLayout editChatLayout; private SwipeRefreshLayout swipeRefreshLayout; private ListView listView; // adapter private ChatAdapter adapter; private HeaderBar title; private String roomTitle; private boolean isRefresh = false; public ChatActivity() { super(R.layout.activity_chat); } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); listView = (ListView) findViewById(R.id.listview); editChatLayout = (EditChatLayout) findViewById(R.id.edit_chat_layout); } @Override public void initData() { getData(); initChat(); getServerInfo("" + StringUtils.getServerIdByGroupCode(groupCode)); try { roomTitle = MultiUserChat.getRoomInfo(AppContext.connectionManager.getConnection(), groupChatJid) .getSubject(); } catch (XMPPException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } @Override public void bindViews() { title.setTitle(roomTitle); title.top_right_btn.setText("消息记录"); title.top_right_btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Server server = new Server(); server.setId(StringUtils.getServerIdByGroupCode(groupCode)); server.setQuestionTitle(roomTitle); Bundle bundle = new Bundle(); bundle.putSerializable(Constants.INTENT_EXTRA_SERVER, server); JumpToActivity(ServiceMessageListActivity.class, bundle); } }); swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light); swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { if (!isRefresh) { isRefresh = true; new AsyncTask<Void, Void, Boolean>() { private int index; @Override protected Boolean doInBackground(Void... arg0) { index = adapter.getCount(); return addNewMsg(); } protected void onPostExecute(Boolean result) { swipeRefreshLayout.setRefreshing(false); if (!isLoadMsg) { showToast(R.string.toast_message_no_more); } resh(); listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_DISABLED); listView.setSelection(adapter.getCount() - index); isRefresh = false; }; }.execute(); } } }); editChatLayout.setOnSendClickListener(this); adapter = new ChatAdapter(this, getMessages()); adapter.setReSendListener(new OnReSendListener() { @Override public void onReSend(IMMessage message) { showToast(R.string.toast_message_resend); } }); listView.setAdapter(adapter); listView.setSelection(adapter.getCount()); } @Override protected void receiveNewMessage(IMMessage message) {} @Override protected void refreshMessage(List<IMMessage> messages) { adapter.refreshData(messages); } @Override public void onSend(String content) { IMessage message = new IMessage(); message.setTouxiang(getUser().getAvater()); message.setName(getUser().getUserName()); message.setType(IMessage.TYPE_TEXT); message.setContent(content); String contentJson = JsonUtil.convertObjectToJson(message); sendMessage(contentJson, roomTitle); editChatLayout.clearEt(); } @Override public void onChoiceImage() { // TODO Auto-generated method stub } @Override public void onScroll() { listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL); } /** * 获取需求详情 -- 为防止房间未成功创建时使用 * * @param serverId */ private void getServerInfo(String serverId) { NetManager.getInstance(this).getServerInfo(serverId, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); } }); } } <file_sep>package com.ricelink.coolead.service; import java.util.Calendar; import java.util.List; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.MessageTypeFilter; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smackx.muc.MultiUserChat; import com.lidroid.xutils.util.LogUtils; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.app.AppManager; import com.ricelink.coolead.app.activity.BaseActivity; import com.ricelink.coolead.app.activity.ChatActivity; import com.ricelink.coolead.app.activity.LoginActivity; import com.ricelink.coolead.helper.Base64Helper; import com.ricelink.coolead.helper.DateHelper; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.helper.L; import com.ricelink.coolead.helper.NetUtil; import com.ricelink.coolead.helper.NetUtil.OnNetStatusChangeListener; import com.ricelink.coolead.helper.NotificationUtil; import com.ricelink.coolead.helper.StringUtils; import com.ricelink.coolead.helper.ToastUtil; import com.ricelink.coolead.model.IMMessage; import com.ricelink.coolead.model.IMessage; import com.ricelink.coolead.model.Server; import com.ricelink.coolead.model.User; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.net.Urls; import com.ricelink.coolead.v.R; import com.ricelink.coolead.xmpp.IMMessageManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.NetworkInfo; import android.os.IBinder; import android.os.Vibrator; import android.text.TextUtils; /** * 即時通訊服務,包括網絡狀態改變檢測,接收聊天消息,系統消息,好友請求消息等 * * @author bruce.chen * * 2015-8-28 */ public class IMService extends Service implements OnNetStatusChangeListener, PacketListener { private Context context; // XMPPConnect private XMPPConnection connection; // 震動 private Vibrator vibrator; // private final static int SENSOR_SNAKE = 10; private long[] times = new long[] { 100, 200, 100, 200 }; private boolean netFlag = true; private String userCode; @Override public void onCreate() { super.onCreate(); context = this; userCode = AppContext.getUser().getUserCode(); vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); // 註冊网络连接廣播 NetUtil.getInstance().addNetStatusListener(context, this); // 初始化IM消息監聽 initIMMsgListener(); // 加入所有要监听的房间 getServerAllIdsAndJoinRooms(); } private void initIMMsgListener() { connection = AppContext.connectionManager.getConnection(); // 聊天消息 connection.addPacketListener(this, new MessageTypeFilter(Message.Type.groupchat)); connection.addConnectionListener(new ConnectionListener() { @Override public void reconnectionSuccessful() { L.v("reconnectionSuccessful"); } @Override public void reconnectionFailed(Exception arg0) { L.v("reconnectionFailed"); } @Override public void reconnectingIn(int arg0) { L.v("reconnectingIn"); } @Override public void connectionClosedOnError(Exception e) { L.e(e.getMessage()); if ("stream:error (conflict)".equals(e.getMessage())) { // 异地登录 User user = AppContext.getUser(); user.setLogin(false); AppContext.saveUser(user); BaseActivity activity = (BaseActivity) AppManager.getAppManager().currentActivity(); activity.showToast(R.string.toast_conflict); Intent intent = new Intent(context, LoginActivity.class); activity.startActivity(intent); AppManager.getAppManager().finishAllActivity(); } } @Override public void connectionClosed() { L.v("connectionClosed"); } }); } /** * 聊天消息監聽 */ @Override public void processPacket(Packet packet) { L.v("IMService -- 接收到聊天消息-->"); Message message = (Message) packet; if (null != message && null != message.getBody()) { IMMessage imMessage = new IMMessage(); // 內容 String content = Base64Helper.getFromBase64(message.getBody()); L.v("IMService -- 接收到聊天消息-->" + message.getBody()); L.v("IMService -- 接收到聊天消息-->" + content); // id String id = message.getPacketID(); if (TextUtils.isEmpty(id)) { // id = UUIDUtils.getID(6); return; } // 時間 String time = (String) message.getProperty(Constants.IntentExtra.INTENT_EXTRA_IMMESSAGE_TIME); if (null == time) { time = DateHelper.date2Str(Calendar.getInstance(), Constants.Xmpp.MS_FORMART); } imMessage.setFromCode(StringUtils.getFromCode(message.getFrom())); imMessage.setToCode(StringUtils.getToCode(message.getTo())); imMessage.setGroupCode(StringUtils.getGroupCode(message.getFrom())); // imMessage.setFromSubJid(from); // imMessage.setToJid(to); // imMessage.setAttach2(userCode); String title = IMMessageManager.getImMessageManager().getTitle(imMessage.getGroupCode()); imMessage.setTitle(title); imMessage.set_Id(id); imMessage.setContent(content); imMessage.setTime(time); imMessage.setNoticeTime(time); imMessage.setNoticeType(IMMessage.MESSAGE_TYPE_CHAT_MSG); if (null != imMessage.getFromCode() && imMessage.getFromCode().equals(AppContext.getUser().getUserCode())) { imMessage.setNoticeSum(0); imMessage.setReadStatus(IMMessage.READ_STATUS_READ); } else { imMessage.setNoticeSum(1); imMessage.setReadStatus(IMMessage.READ_STATUS_UNREAD); } // 保存 long status = IMMessageManager.getImMessageManager().savaIMMessage(imMessage); if (-1 != status) { // 保存成功 // 發送廣播 Intent intent = new Intent(Constants.ACTION_NEW_MESSAGE); intent.putExtra(Constants.IntentExtra.INTENT_EXTRA_IMMESSAGE_KEY, imMessage); sendBroadcast(intent); // 震動提示 vibrator.vibrate(times, -1); // 發送通知 if (Constants.Xmpp.isChatNotification) { IMessage iMessage = JsonUtil.convertJsonToObject(content, IMessage.class); String string; if (iMessage.getType() == IMessage.TYPE_TEXT) { string = iMessage.getContent(); } else { string = "[图片]"; } NotificationUtil.setNotiType(context, R.drawable.ic_launcher, imMessage.getTitle(), string, ChatActivity.class, imMessage.getGroupCode()); } } } } @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); // 註銷廣播接收器 NetUtil.getInstance().removeNetStatusListener(context, this); connection.removePacketListener(this); } @Override public void onNetChange(NetworkInfo netInfo) { if (null != netInfo && netInfo.isAvailable()) { // 有網絡但是連接斷開,遞歸連接 if (!connection.isConnected()) { reConnect(connection); } else { sendIntentAndPre(Constants.Xmpp.RECONNECT_STATE_SUCCESS); } // 重新监听 if (false == netFlag) { getServerAllIdsAndJoinRooms(); netFlag = true; } CachingService.onNetChange(AppContext.getApplication(), netInfo); } else { ToastUtil.showToast("网络断开,用户已离线!"); netFlag = false; } } /** * 递归重连,直连上为止. * * @param connection */ private void reConnect(final XMPPConnection connection) { new Thread(new Runnable() { @Override public void run() { try { if (!connection.isConnected()) { connection.connect(); if (connection.isConnected()) { Presence presence = new Presence(Presence.Type.available); connection.sendPacket(presence); } } } catch (Exception e) { LogUtils.e("connection failed!" + e.toString()); reConnect(connection); } } }).start(); } /** * 保存状态 * * @param isSuccess */ private void sendIntentAndPre(boolean isSuccess) { // 保存在线连接信息 AppContext.settingManager.writeSetting(Constants.SP_KEY_IS_ONLINE, isSuccess); // 发送广播 Intent intent = new Intent(Constants.ACTION_RECONNECT_STATE); intent.putExtra(Constants.IntentExtra.INTENT_EXTRA_RECONNECT_STATE, isSuccess); sendBroadcast(intent); } /** * 获取所有要接听的房间id */ private void getServerAllIdsAndJoinRooms() { NetManager.getInstance(context).getServerAllIds(userCode, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess() && null != responeModel.getResult()) { joinRooms(JsonUtil.convertJsonToList(responeModel.getResult(), Server.class)); } } }); } /** * 加入房间 */ private void joinRooms(final List<Server> serverList) { if (null != serverList && 0 < serverList.size()) { new Thread(new Runnable() { @Override public void run() { for (Server server : serverList) { String chatWithJid = Constants.SERVER_JID_HEAD + server.getId() + Constants.SERVER_JID_FOOT + Urls.IM_SERVICE_NAME; try { MultiUserChat muc = new MultiUserChat(AppContext.connectionManager.getConnection(), chatWithJid); muc.join(userCode); } catch (XMPPException e) { e.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } } }).start(); } } } <file_sep>package com.ricelink.coolead.app.fragment; import java.util.ArrayList; import java.util.List; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import com.ricelink.coolead.app.adapter.TabFragmentPagerAdapter; import com.ricelink.coolead.app.view.SlidingSwitchViewPager; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.v.R; /** * 工单主页面 * * @author gavin.xiong * */ public class WorkOrderFragment extends BaseFragment implements OnClickListener{ private SlidingSwitchViewPager mViewPager; private TabFragmentPagerAdapter mAdapter; private ArrayList<Fragment> fragments; private List<View> viewTabPanels; private List<TextView> txtTTabs; public WorkOrderFragment() { super(R.layout.fragment_workorder); } @Override public void initViews() { mViewPager = (SlidingSwitchViewPager) findViewById(R.id.content_container); viewTabPanels = new ArrayList<View>(); viewTabPanels.add(findViewById(R.id.mian_tabpanel_1)); viewTabPanels.add(findViewById(R.id.mian_tabpanel_2)); txtTTabs = new ArrayList<TextView>(); txtTTabs.add((TextView) findViewById(R.id.mian_tab_1)); txtTTabs.add((TextView) findViewById(R.id.mian_tab_2)); for (View tab : viewTabPanels) { tab.setOnClickListener(this); } } @Override public void initData() { fragments = new ArrayList<Fragment>(); fragments.add(new WorkOrderBacklogFragment()); fragments.add(new WorkOrderAllFragment()); } @Override public void bindViews() { mViewPager.setSlideable(true); mAdapter = new TabFragmentPagerAdapter(getChildFragmentManager(), fragments); mViewPager.setAdapter(mAdapter); /** * 设置当前页为第一页 */ setTabSelection(0); mViewPager.setCurrentItem(0); mViewPager.setOffscreenPageLimit(5); mViewPager.addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int pageId) { setTabSelection(pageId); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) {} @Override public void onPageScrollStateChanged(int arg0) {} }); } private void setTabSelection(int add) { clearSelection(); TextView txt = txtTTabs.get(add); txt.setTextColor(getResColor(R.color.color_white)); if (add == 0) { txtTTabs.get(0).setBackgroundResource(R.drawable.bg_tab_left_sel); txtTTabs.get(1).setBackgroundResource(R.drawable.bg_tab_right_nor); } else if (add == 1) { txtTTabs.get(0).setBackgroundResource(R.drawable.bg_tab_left_nor); txtTTabs.get(1).setBackgroundResource(R.drawable.bg_tab_right_sel); } } private void clearSelection() { for (int i = 0; i < txtTTabs.size(); i++) { TextView txt = txtTTabs.get(i); txt.setTextColor(getResColor(R.color.main_text_light)); } } /** * 点击事件监听 */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.mian_tabpanel_1: setTabSelection(0); mViewPager.setCurrentItem(0, true); break; case R.id.mian_tabpanel_2: setTabSelection(1); mViewPager.setCurrentItem(1, true); break; } } @Override public void refreshPage(RefreshModel refreshModel) { // TODO Auto-generated method stub } } <file_sep>package com.ricelink.coolead.app.activity; import java.util.ArrayList; import java.util.List; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.adapter.ServiceMessageAdapter; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.model.Server; import com.ricelink.coolead.model.ServiceMessage; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.ListResponeModel; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import android.os.Bundle; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ListView; /** * 项目选择页面 * * @author gavin.xiong * */ public class ServiceMessageListActivity extends BaseActivity { private HeaderBar title; private ListView xlist; private ServiceMessageAdapter adapter; private List<ServiceMessage> serviceMessageList = new ArrayList<ServiceMessage>(); private List<ServiceMessage> serviceMessageListAll = new ArrayList<ServiceMessage>(); private boolean haveMore = false; private boolean loadingMore = false; private int offset = 0; private int limit = 10000; private Server mServer; public ServiceMessageListActivity() { super(R.layout.activity_project_select); } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); xlist = (ListView) findViewById(R.id.listview); } @Override public void initData() { adapter = new ServiceMessageAdapter(this, serviceMessageListAll); xlist.setAdapter(adapter); Bundle bundle = getIntent().getExtras(); if (null != bundle) { mServer = (Server) bundle.getSerializable(Constants.INTENT_EXTRA_SERVER); getServiceMessageList(false); } } @Override public void bindViews() { title.setTitle(null == mServer ? "" : mServer.getQuestionTitle()); xlist.setDividerHeight(0); xlist.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub if (OnScrollListener.SCROLL_STATE_IDLE == scrollState) { // 手指按下并开始滑动 // TODO Auto-generated method stub } else if (OnScrollListener.SCROLL_STATE_TOUCH_SCROLL == scrollState) { // 手指松开且完全停止滑动 // TODO Auto-generated method stub } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // 滑到倒数第二项时加载更多 if (haveMore && !loadingMore && totalItemCount <= firstVisibleItem + visibleItemCount) { loadingMore = true; offset += limit; getServiceMessageList(true); } } }); } /** * 查询设备巡检内容 */ private void getServiceMessageList(final boolean isMore) { NetManager.getInstance(this).getServiceMessageList(mServer.getId(), limit, offset, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); ListResponeModel listResponse = JsonUtil.convertJsonToObject(responeModel.getResult(), ListResponeModel.class); if (null != listResponse) { // 成功 if (listResponse.getTotalCount() > listResponse.getLimit() + listResponse.getOffset()) { haveMore = true; } else { haveMore = false; } serviceMessageList = JsonUtil.convertJsonToList(listResponse.getList(), ServiceMessage.class); if (null != serviceMessageList) { if (!isMore) { serviceMessageListAll.clear(); } serviceMessageListAll.addAll(serviceMessageList); adapter.notifyDataSetChanged(); } } else { // 失败 showToast(getString(R.string.toast_get_failed) + responeModel.getMessage()); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); showToast(R.string.toast_get_failed); } }); } } <file_sep>package com.ricelink.coolead.app.adapter; import java.util.List; import com.ricelink.coolead.app.activity.BaseActivity; import com.ricelink.coolead.helper.StringUtils; import com.ricelink.coolead.model.ProgressModel; import com.ricelink.coolead.v.R; public class WorkOrderScheduleAdapter extends CommonAdapter<ProgressModel> { public WorkOrderScheduleAdapter(BaseActivity mContext, List<ProgressModel> mData) { super(mContext, mData, R.layout.item_workorder_schedule); } @Override public void convert(CommonViewHolder holder, ProgressModel t, int position) { holder.setText(R.id.tv_no, position + 1 + ""); String str = null; try { str = t.getName().substring(0, 2); } catch (IndexOutOfBoundsException e) { str = t.getName(); } holder.setText(R.id.tv_role, str + ":"); holder.setText(R.id.tv_name, t.getPerson()); String time = StringUtils.getTime(Long.parseLong(t.getEndTime()), "yyyy-MM-dd\nHH:mm:ss"); holder.setText(R.id.tv_time, time); holder.setText(R.id.tv_remark, t.getRemark()); } } <file_sep>package com.ricelink.coolead; import java.io.File; import android.os.Environment; /** * 常量类 * * @author gavin.xiong * */ public class Constants { /** * 状态 */ public static final int STATUS_0 = 0; public static final int STATUS_1 = 1; public static final int STATUS_2 = 2; /** * 类型 */ public static final int TYPE_0 = 0; public static final int TYPE_1 = 1; public static final int TYPE_2 = 2; /** * 工单阶段状态 */ public static final String WORKORDER_STATUS_LAUNCH = "launchActivity"; // 发起中的工单 public static final String WORKORDER_STATUS_MANAGER = "managerActivity"; // 待派发工单 public static final String WORKORDER_STATUS_HANDLE = "handleActivity"; // 待处理工单 public static final String WORKORDER_STATUS_CHECK = "checkActivity"; // 待验收工单 public static final String WORKORDER_STATUS_DONE = "doneActivity"; // 已完成工单 public static final String WORKORDER_STATUS_NULL = null; // 全部工单 /** * 工单步骤code (用于上传图片) */ public static final String WORKORDER_STEP_ADD = "start_work_order"; // 发起工单时 public static final String WORKORDER_STEP_DIATRIBUTE = "manager_distribute"; // 主管派发工单时 public static final String WORKORDER_STEP_HANDLE = "maintenanceman_process"; // 维修人员处理工单时 public static final String WORKORDER_STEP_ACCEPT = "acceptance"; // 验收工单时 public static final String WORKORDER_STEP_CLOSE = "endevent"; // 结束工单 /** * 工单来源 */ public static final String WORKORDER_TYPE_BY = "A"; // 保养单 public static final String WORKORDER_TYPE_WX = "B"; // 维修单 public static final String WORKORDER_TYPE_XJ = "C"; // 巡检单 public static final String WORKORDER_TYPE_YJ = "D"; // 预警单 public static final String WORKORDER_TYPE_NAME_BY = "保养单"; // 保养单 public static final String WORKORDER_TYPE_NAME_WX = "维修单"; // 维修单 public static final String WORKORDER_TYPE_NAME_XJ = "巡检单"; // 巡检单 public static final String WORKORDER_TYPE_NAME_YJ = "预警单"; // 预警单 /** * 工单紧急状态 */ public static final int WORKORDER_LEVEL_general = 1; // 一般工单 public static final int WORKORDER_LEVEL_major = 2; // 紧急工单 /** * 工单派发模式 */ public static final int WORKORDER_DISTRIBUTION_TYPE_QD = 1; // 抢单 public static final int WORKORDER_DISTRIBUTION_TYPE_PF = 2; // 派发 /** * 工单属性 */ public static final int WORKORDER_DISTRIBUTION_TYPE_GRAB = 2; // 抢单工单 public static final int WORKORDER_DISTRIBUTION_TYPE_GENERAL = 1; // 一般工单 /** * 设备状态 */ public static final String INSPECTION_DEVICE_STATUS_INUSE = "inuse"; // 使用中 public static final String INSPECTION_DEVICE_STATUS_STOP = "stop"; // 停止中 public static final String INSPECTION_DEVICE_STATUS_BROKEN = "broken"; // 维修中 /** * 用能单位 */ public static final String INSPECTION_CONTENT_TYPE_YNDW = "2"; // 用能单位 /** * 用户权限 */ public static final int USER_ROLE_ID_1 = 1; public static final int USER_ROLE_ID_2 = 2; public static final int USER_ROLE_ID_3 = 3; public static final int USER_ROLE_ID_5 = 5; public static final int USER_ROLE_ID_6 = 6; public static final int USER_ROLE_ID_16 = 16; public static final int USER_ROLE_ID_21 = 21; /** * 权限内容标记 */ public static final int USER_ROLE_CONTENT_WORK_ORDER = 99; // 工单页 public static final int USER_ROLE_CONTENT_INSPECTION = 98; // public static final int USER_ROLE_CONTENT_PROJECT_SELECT = 97; // public static final int USER_ROLE_CONTENT_INITIATE_WORK_ORDER = 96; // public static final int USER_ROLE_CONTENT_DISTRIBUTE_INSPECTION = 95; // 派发巡检 public static final String USER_ROLE_WORK_ORDER = "WORK_ORDER"; // 工单页 public static final String USER_ROLE_INSPECTION = "INSPECTION"; // public static final String USER_ROLE_PROJECT_SELECT = "PROJECT_SELECT"; // public static final String USER_ROLE_INITIATE_WORK_ORDER = "INITIATE_WORK_ORDER"; // public static final String USER_ROLE_DISTRIBUTE_INSPECTION = "DISTRIBUTE_INSPECTION"; // 派发巡检 /** * 服务 - 房间id前缀 */ public static final String SERVER_JID_HEAD = "coolead_room_"; public static final String SERVER_JID_FOOT = "@conference."; public static final int SERVER_STATUS_0 = 0; public static final int SERVER_STATUS_1 = 1; public static final int SERVER_STATUS_2 = 2; /************************** Intent extra Start **************************/ // 展现方式 public static final String INTENT_EXTRA_SHOW_TYPE = "showType"; // 处理明细 public static final String INTENT_EXTRA_DEALWITH_DETAIL = "dealwith_detail"; // 项目 public static final String INTENT_EXTRA_PROJECT = "project"; // 设备 public static final String INTENT_EXTRA_DEVICE = "device"; // 工单 public static final String INTENT_EXTRA_WORKORDER = "workorder"; // 工单状态 public static final String INTENT_EXTRA_WORKORDER_STATUS = "status"; // 今日的巡检 public static final String INTENT_EXTRA_INSPECTION_TODAY = "today"; public static final int INTENT_EXTRA_INSPECTION_FLAG_TODAY = 1; // 巡检 public static final String INTENT_EXTRA_INSPECTION = "inspection"; // 巡检子项 public static final String INTENT_EXTRA_INSPECTION_ITEM = "inspectionItem"; // 服务 public static final String INTENT_EXTRA_SERVER_GROUPCODE = "groupCode"; public static final String INTENT_EXTRA_SERVER = "server"; /************************** Intent extra End **************************/ /************************** request Code Start **************************/ // 从相册中选择请求码 public static final int REQUEST_CODE_PICK_FROM_ALBUM = 999; // 换头像拍照请求码 public static final int REQUEST_CODE_AVATAR_TAKE_PHOTO = 998; // 头像裁剪请求码和和裁剪请求码 public static final int REQUEST_CODE_USER_AVATAR_CROP = 997; // 新增处理明细 public static final int REQUEST_CODE_ADD_DEALWITH_DETAIL = 1; // 项目选择 public static final int REQUEST_CODE_SELECT_PROJECT = 2; // 设备选择 public static final int REQUEST_CODE_SELECT_DEVICE = 3; // 提交巡检数据 public static final int REQUEST_CODE_SUBMIT_INSPCTION_CONTENT = 4; /************************** request Code End ****************************/ /** * SDCRAD相关 * * @author bruce.chen * */ public static class SdCard { /** SDCARD根目录 */ public final static String SDCARD = Environment.getExternalStorageDirectory().getPath(); /** 项目文件夹 */ private static final String STORAGE_DIR = SDCARD + File.separatorChar + "coolead" + File.separatorChar; /** 图片缓存文件夹 保存裁剪后的原图 */ public final static String CACHE = "cache"; /** 图片文件夹 保存压缩后的图片 */ public final static String IMAGE = "image"; public static String getCacheDir() { File file = new File(STORAGE_DIR + CACHE + File.separatorChar); if (!file.exists()) { file.mkdirs(); } String s = file.getAbsolutePath() + File.separatorChar; file = null; return s; } public static String getImageDir() { File file = new File(STORAGE_DIR + IMAGE + File.separatorChar); if (!file.exists()) { file.mkdirs(); } String s = file.getAbsolutePath() + File.separatorChar; file = null; return s; } } public static final String NAME = "name"; public static final String RECEIVER = "receiver"; public static final String PAUSE = "、"; public static final String ASSOCIATE_PEOPLES = "associatePeoples"; public static final String IMG_URL = "imgUrl"; public static final String COMMUNE_DETAIL = "communeDetail"; public static final String JPG = ".jpg"; public static final String ICON = "icon"; public static final String TYPE = "type"; public static final String FLAG = "flag"; public static final int FEEDBACK_USER = 1; public static final int FEEDBACK_ATTENTION = 2; public static final int FEEDBACK_COMMUNE = 3; public static final String IS_SHARE = "isShare"; public static final String IS_EDIT = "isEdit"; public static final String IS_EDIT_INVOICE = "isEditInvoice"; public static final String PHONE = "phone"; public static final String IS_DIS_BAND = "isDisband"; public static final String IS_OFF_LINE = "isOffLine"; public static final String OFF_LINE_CACHE = "offline_cache"; public static final String IS_F_TO_F = "isF2F"; public static final String IS_FIRST_LOGIN = "isFirstLogin"; /** 欢迎页显示时间 */ public static final long WELCOME_TIME = 2500; /** 连接超时时间 30S */ public static final int CONNECT_TIMEOUT = 30 * 1000; /** 在聊天activity加载聊天记录时的每次加载的数量 */ public static final int CHAT_PAGESIZE = 10; /** 配置文件名字 */ public static final String SHAREDPREFERENCESNAME = "SkyChat"; /** 数据库名称 */ public static final String DB_NAME = "skychat.db"; /** 数据库版本 */ public static final int DB_VERSION = 1; /** 所有好友 */ public static final String ALL_FRIEND = "所有好友"; /** 未分组好友 */ public static final String NO_GROUP_FRIEND = "未分组好友"; /** 用户名,判断是否已登录 */ public static final String SP_KEY_USERNAME = "username"; /** 密码 */ public static final String SP_KEY_USERPSWD = "userpswd"; /** 保存密码 */ public static final String SP_KEY_SAVEPSWD = "<PASSWORD>"; /** 登录状态 */ public static final String SP_KEY_IS_ONLINE = "is_online"; /** 登录状态 */ public static final String SP_KEY_IS_Login = "is_login"; /** 从欢迎页进入首页 */ public static final int TYPE_GOMAIN_WELCOME = 0XF2; /** 从登录进入首页 */ public static final int TYPE_GOMAIN_LOGIN = 0XF3; /** 登陆成功 */ public static final int LOGIN_SECCESS = 0XF4; /** 账号或者密码错误 */ public static final int LOGIN_ERROR_ACCOUNT_PASS = <PASSWORD>; /** 无法连接到服务器 */ public static final int SERVER_UNAVAILABLE = 0XF6; /** 连接失败 */ public static final int LOGIN_ERROR = 0XF7; /** 精确到毫秒 */ public static final String MS_FORMART = "yyyy-MM-dd HH:mm:ss SSS"; /** 描述重连接 */ public static final boolean RECONNECT_STATE_SUCCESS = true; public static final boolean RECONNECT_STATE_FAIL = false; /** 新消息action */ public static final String ACTION_NEW_MESSAGE = "roster.newmessage"; /** 重连接状态acttion */ public static final String ACTION_RECONNECT_STATE = "action_reconnect_state"; /** 消息类型关键字 */ public static final String ACTION_SYS_MSG = "action_sys_msg"; // -----------------------请求码 start-------------------------- /** 注册 */ public static final int REQUEST_CODE_REGISTER = 0xf1; /** 登陆 */ public static final int REQUEST_CODE_LOGIN = 0xf8; // -----------------------请求码 end---------------------------- // // ------------------------intent extra key start------------- /** 用户名 */ public static final String INTENT_EXTRA_USERNAME = "username"; /** 密码 */ public static final String INTENT_EXTRA_PSWD = "<PASSWORD>"; /** 从哪里进入登陆界面的标示 */ public static final String INTENT_EXTRA_TYPE2MAIN = "type2main"; /** 描述重连接状态的关键字,寄放的intent的关键字 */ public static final String INTENT_EXTRA_RECONNECT_STATE = "reconnect_state"; /** 新消息 */ public static final String INTENT_EXTRA_IMMESSAGE_KEY = "immessage.key"; /** 消息时间 */ public static final String INTENT_EXTRA_IMMESSAGE_TIME = "immessage.time"; /** 消息的联系人 */ public static final String INTENT_EXTRA_IMMESSAGE_FORM = "immessage.form"; /** 消息来源 */ public static final String INTENT_EXTRA_MESSAGE_TO = "to"; /** 联系人状态改变的key */ public static final String INTENT_EXTRA_ROSTER_PRESENCE_CHANGED = "roster.presence.changed.key"; /** user Key */ public static final String INTENT_EXTRA_USER_KEY = "user"; /** 联系人删除 */ public static final String INTENT_EXTRA_ROSTER_DELETED = "roster.deleted.key"; /** 联系人更新 */ public static final String INTENT_EXTRA_ROSTER_UPDATED = "roster.updated.key"; /** 联系人增加 */ public static final String INTENT_EXTRA_ROSTER_ADDED = "roster.added.key"; /** 好友分组 */ public static final String INTENT_EXTRA_GROUP = "group"; // ------------------------intent extra key END--------------- // ------------------------menu id start--------------- /** 消息列表菜单-->组ID */ public static final int MENU_MESSAGE_GROUPID = 0XFF5; /** 消息列表菜单-->item 删除聊天记录ID */ public static final int MENU_MESSAGE_ITEMID_DELETE_CHATMSG = MENU_MESSAGE_GROUPID + 1; /** 消息列表菜单-->item 删除系统消息记录ID */ public static final int MENU_MESSAGE_ITEMID_DELETE_SYSMSG = MENU_MESSAGE_ITEMID_DELETE_CHATMSG + 1; // /** 联系人列表菜单-->组ID */ public static final int MENU_CONTACT_GROUPID = MENU_MESSAGE_ITEMID_DELETE_SYSMSG + 1; /** 联系人列表菜单-->item 删除好友 */ public static final int MENU_CONTACT_ITEMID_DELETE_FRIEND = MENU_CONTACT_GROUPID + 1; /** 联系人列表菜单-->item 修改好友名字 */ public static final int MENU_CONTACT_ITEMID_CHANGE_RIENF_NAME = MENU_CONTACT_ITEMID_DELETE_FRIEND + 1; /** 联系人列表菜单-->item 修改组名 */ public static final int MENU_CONTACT_ITEMID_CHANGE_GROUP_NAME = MENU_CONTACT_ITEMID_CHANGE_RIENF_NAME + 1; // ------------------------menu id end--------------- /** * intent 攜帶參數key * * @author bruce.chen * */ public static final class IntentExtra { /** 描述重连接状态的关键字,寄放的intent的关键字 */ public static final String INTENT_EXTRA_RECONNECT_STATE = "reconnect_state"; /** 新消息 */ public static final String INTENT_EXTRA_IMMESSAGE_KEY = "immessage.key"; /** 消息时间 */ public static final String INTENT_EXTRA_IMMESSAGE_TIME = "immessage.time"; /** 消息的联系人 */ public static final String INTENT_EXTRA_IMMESSAGE_FORM = "immessage.form"; /** 消息来源 */ public static final String INTENT_EXTRA_MESSAGE_TO = "immessage.to"; /** 联系人状态改变的key */ public static final String INTENT_EXTRA_ROSTER_PRESENCE_CHANGED = "roster.presence.changed.key"; /** user Key */ public static final String INTENT_EXTRA_USER_KEY = "user.key"; /** 联系人删除 */ public static final String INTENT_EXTRA_ROSTER_DELETED = "roster.deleted.key"; /** 联系人更新 */ public static final String INTENT_EXTRA_ROSTER_UPDATED = "roster.updated.key"; /** 联系人增加 */ public static final String INTENT_EXTRA_ROSTER_ADDED = "roster.added.key"; /** 好友分组 */ public static final String INTENT_EXTRA_GROUP = "group.key"; } /** * xmpp即時通訊相關 * * @author bruce.chen * */ public static final class Xmpp { /** 描述重连接 */ public static final boolean RECONNECT_STATE_SUCCESS = true; public static final boolean RECONNECT_STATE_FAIL = false; /** 聊天消息是否通知 */ public static boolean isChatNotification = true; /** 连接超时时间 30S */ public static final int CONNECT_TIMEOUT = 30 * 1000; /** 在聊天activity加载聊天记录时的每次加载的数量 */ public static final int CHAT_PAGESIZE = 10; /** 所有好友 */ public static final String ALL_FRIEND = "所有好友"; /** 未分组好友 */ public static final String NO_GROUP_FRIEND = "未分组好友"; /** 登陆成功 */ public static final int LOGIN_SECCESS = 0XF4; /** 账号或者密码错误 */ public static final int LOGIN_ERROR_ACCOUNT_PASS = <PASSWORD>; /** 无法连接到服务器 */ public static final int SERVER_UNAVAILABLE = 0XF6; /** 连接失败 */ public static final int LOGIN_ERROR = 0XF7; /** 註冊失敗 */ public static final int REGISTER_ERROR = 0XF8; /** 註冊時賬戶存在 */ public static final int REGISTER_ACCOUNT_EXIST = 0XF9; /** 註冊成功 */ public static final int REGISTER_SUCCESS = 0XF10; /** 精确到毫秒 */ public static final String MS_FORMART = "yyyy-MM-dd HH:mm:ss SSS"; } } <file_sep>package com.ricelink.coolead.app.activity; import java.util.Calendar; import java.util.List; import org.apache.http.Header; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.app.view.datetimepicker.fourmob.datetimepicker.date.DatePickerDialog; import com.ricelink.coolead.app.view.datetimepicker.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.helper.SPUtil; import com.ricelink.coolead.helper.StringUtils; import com.ricelink.coolead.model.Candidate; import com.ricelink.coolead.model.Device; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.model.WorkOrder; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; /** * 主管处理页面 * * @author gavin.xiong * */ public class ManageDealwithActivity extends BaseActivity implements OnClickListener { public static final String DATEPICKER_TAG = "datepicker"; private DatePickerDialog datePickerDialog; private Calendar calendar; private HeaderBar title; private TextView tv_candidate; private TextView tv_date; private TextView tv_device; private RadioButton rb_middle, rb_major; private EditText et_remark; private WorkOrder mWorkOrder; private boolean isInspectionOrder; private String planEndTiem; private List<Candidate> candidateList; private String[] candidateNames; private String candidateCode; private Device device; public ManageDealwithActivity() { super(R.layout.activity_manager_dealwith); } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); tv_candidate = (TextView) findViewById(R.id.tv_candidate); tv_date = (TextView) findViewById(R.id.tv_date); tv_device = (TextView) findViewById(R.id.tv_device); rb_middle = (RadioButton) findViewById(R.id.rb_middle); rb_major = (RadioButton) findViewById(R.id.rb_major); et_remark = (EditText) findViewById(R.id.et_remark); } @Override public void initData() { Bundle bundle = getIntent().getExtras(); if (null != bundle) { mWorkOrder = (WorkOrder) bundle.getSerializable(Constants.INTENT_EXTRA_WORKORDER); isInspectionOrder = Constants.WORKORDER_TYPE_XJ.equals(mWorkOrder.getType()) ? true : false; managerGetCandidates(); } } @Override public void bindViews() { title.setTitle(R.string.label_manager_dealwith); // 如果是巡检单 则隐设备选择 findViewById(R.id.ll_device).setVisibility(isInspectionOrder ? View.GONE : View.VISIBLE); rb_middle.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { rb_middle.setTextColor(ManageDealwithActivity.this.getResColor(R.color.color_white)); } else { rb_middle.setTextColor(ManageDealwithActivity.this.getResColor(R.color.color_green)); } } }); rb_major.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { rb_major.setTextColor(ManageDealwithActivity.this.getResColor(R.color.color_white)); } else { rb_major.setTextColor(ManageDealwithActivity.this.getResColor(R.color.color_red)); } } }); rb_middle.setChecked(true); calendar = Calendar.getInstance(); datePickerDialog = DatePickerDialog.newInstance(new OnDateSetListener() { @Override public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) { String mStr = month < 9 ? "0" + (month + 1) : month + 1 + ""; String dStr = day < 10 ? "0" + day : day + ""; planEndTiem = year + "-" + mStr + "-" + dStr; tv_date.setText(planEndTiem); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), true); } /** * 点击事件监听 */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.rl_name_dealwith: // 选择处理人 showSelectDialog(candidateNames, new OnItemClick() { @Override public void onClick(View view, int position) { tv_candidate.setText(candidateNames[position]); candidateCode = candidateList.get(position).getCode(); } }); break; case R.id.rl_device: // 设备选择 JumpToActivityForResult(DeviceSelectActivity.class, Constants.REQUEST_CODE_SELECT_DEVICE); break; case R.id.rl_time: // 结束时间 showDatePickerDialog(); break; case R.id.btn_wechat: // 微信 showSureDialog(getString(R.string.label_wechat_enter), getString(R.string.label_wechat_enter_now), new OnSurePress() { @Override public void onClick(View view) { try { // Intent intent = new Intent(); // intent.setComponent(new ComponentName("com.tencent.mm", // "com.tencent.mm.ui.LauncherUI")); // intent.setAction(Intent.ACTION_VIEW); // startActivity(intent); Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm"); startActivity(intent); } catch (NullPointerException e) { showToast(R.string.label_wechat_null); } catch (ActivityNotFoundException e) { showToast(R.string.label_wechat_null); } catch (Exception e) { e.printStackTrace(); showToast(R.string.label_wechat_enter_failed); } } }); break; case R.id.btn_back: // 返回 onBackPressed(); break; case R.id.btn_submit_pf: // 派发 if (null == candidateCode) { showToast(R.string.toast_add_assign_cant_null); return; } else { if (!StringUtils.isStringNone(planEndTiem)) if (!isInspectionOrder && null == device) showToast(R.string.toast_add_device_cant_null); else managerDealWith(Constants.WORKORDER_DISTRIBUTION_TYPE_QD, et_remark.getText().toString()); else showToast(R.string.toast_add_time_cant_null); } break; case R.id.btn_submit_qd: // 抢单 if (!StringUtils.isStringNone(planEndTiem)) if (!isInspectionOrder && null == device) showToast(R.string.toast_add_device_cant_null); else managerDealWith(Constants.WORKORDER_DISTRIBUTION_TYPE_PF, et_remark.getText().toString()); else showToast(R.string.toast_add_time_cant_null); break; } } /** * 显示日期选择器 */ private void showDatePickerDialog() { datePickerDialog.setVibrate(true); datePickerDialog.setYearRange(1985, 2028); datePickerDialog.setCloseOnSingleTapDay(true); datePickerDialog.show(getSupportFragmentManager(), DATEPICKER_TAG); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case Constants.REQUEST_CODE_SELECT_DEVICE: // 设备选择 // 设备选择 Bundle bundle = data.getExtras(); if (null != bundle) { device = (Device) bundle.getSerializable(Constants.INTENT_EXTRA_DEVICE); tv_device.setText(device.getName()); } break; } } } /** * 获取工单可派发人员列表 */ private void managerGetCandidates() { NetManager.getInstance(this).managerGetCandidates(mWorkOrder.getCurrentId(), new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { candidateList = JsonUtil.convertJsonToList(responeModel.getResult(), Candidate.class); candidateNames = new String[candidateList.size()]; for (int i = 0; i < candidateList.size(); i++) candidateNames[i] = candidateList.get(i).getName(); findViewById(R.id.rl_name_dealwith).setOnClickListener(ManageDealwithActivity.this); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) { super.onFailure(statusCode, headers, responseBytes, throwable); showToast(R.string.toast_get_failed); } }); } /** * 主管处理 (指定派发) */ private void managerDealWith(int distributionType, String remark) { NetManager.getInstance(this).managerDealWith(mWorkOrder.getCurrentId(), distributionType, candidateCode, isInspectionOrder ? null : device.getCode(), planEndTiem, remark, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { // showToast(R.string.toast_submit_success); // ManageDealwithActivity.this.finish(); onChangeSueecss(); } else showToast(R.string.toast_submit_failed); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable) { super.onFailure(statusCode, headers, responseBytes, throwable); showToast(R.string.toast_submit_failed); } }); } private void onChangeSueecss() { showToast(R.string.toast_submit_success); RefreshModel rm = new RefreshModel(); rm.workOrder_backlog = true; rm.workOrder_list = true; rm.workOrder_info = true; rm.workOrder_progerss = true; SPUtil.saveObjectToShare(RefreshModel.class.getName(), rm); this.finish(); } } <file_sep>package com.ricelink.coolead.app.view; import android.annotation.SuppressLint; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; /** * 可以禁滑动的viewpager(并catch图片放大缩小bug的viewpager) * * @author gavin.xiong * */ public class SlidingSwitchViewPager extends ViewPager { private boolean slideable = true; public SlidingSwitchViewPager(Context context) { super(context); } public SlidingSwitchViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { try { return slideable ? super.onInterceptTouchEvent(ev) : slideable; } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } return false; } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent ev) { return slideable ? super.onTouchEvent(ev) : slideable; } public boolean isScrollble() { return slideable; } public void setSlideable(boolean slideable) { this.slideable = slideable; } } <file_sep>package com.ricelink.coolead.app.activity; import java.util.Arrays; import java.util.List; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.app.AppManager; import com.ricelink.coolead.app.adapter.SelectDialogAdapter_z; import com.ricelink.coolead.app.view.MyProgressDialog; import com.ricelink.coolead.helper.NetUtil; import com.ricelink.coolead.helper.SPUtil; import com.ricelink.coolead.helper.StringUtils; import com.ricelink.coolead.helper.UserUtil; import com.ricelink.coolead.model.Project; import com.ricelink.coolead.model.User; import com.ricelink.coolead.v.R; /** * 基类界面 * * @author gavin.xiong */ public abstract class BaseActivity extends FragmentActivity { protected int resId = -1; public AppContext appContext; protected Context context; protected MyProgressDialog loadingDialog; private Toast toast; // 有无动画效果 public boolean withAinm = true; public boolean checkNetStatus = true; public BaseActivity(int resId) { this.resId = resId; } /** * @Description 初始化界面,对界面进行赋值等操作 */ public abstract void initViews(); /** * @Description 初始化界面,对界面进行赋值等操作 */ public abstract void initData(); /** * @Description 初始化界面,对界面进行赋值等操作 */ public abstract void bindViews(); @SuppressLint("ShowToast") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 添加Activity到堆栈 AppManager.getAppManager().addActivity(this); appContext = (AppContext) BaseActivity.this.getApplication(); context = this; if (resId != -1) { setContentView(resId); if (withAinm) { overridePendingTransition(R.anim.z_push_right_in, R.anim.z_push_left_out); } } toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); initViews(); initData(); bindViews(); } @Override protected void onResume() { super.onResume(); if (checkNetStatus && !NetUtil.isNetworkAvailable(context)) { showToast(R.string.network_not_connected); } } public void showToast(String message) { toast.setText(message); toast.setDuration(Toast.LENGTH_SHORT); toast.show(); } public void showToast(int resId) { toast.setText(resId); toast.setDuration(Toast.LENGTH_SHORT); toast.show(); } public void showToastLong(String message) { toast.setText(message); toast.setDuration(Toast.LENGTH_LONG); toast.show(); } public void showToastLong(int resId) { toast.setText(resId); toast.setDuration(Toast.LENGTH_LONG); toast.show(); } /** * 普通的界面跳转,不带动画 * * @param cls */ public void JumpToActivityNoAnim(Class<?> cls) { Intent intent = new Intent(this, cls); startActivity(intent); } /** * @Description 不带参数的Activity界面跳转 * @param cls * 跳转的目标界面 */ public void JumpToActivity(Class<?> cls) { JumpToActivity(cls, null); } /** * @Description 带参数的界面跳转 * @param cls * 跳转的目标界面 * @param bundle * 带过去的界面参数 */ public void JumpToActivity(Class<?> cls, Bundle bundle) { Intent intent = new Intent(this, cls); if (null != bundle) { intent.putExtras(bundle); } // 设置跳转标志为如此Activity存在则把其从任务堆栈中取出放到最上方 // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { startActivity(intent); } catch (ActivityNotFoundException e) { e.printStackTrace(); } } /** * @Description 带返回结果的界面跳转 * @param cls * 界面目标跳转目标界面 * @param requestCode * 请求参数 */ public void JumpToActivityForResult(Class<?> cls, int requestCode) { JumpToActivityForResult(cls, null, requestCode); } /** * @Description 带返回结果的界面跳转 * @param cls * 目标界面 * @param obj * 带过去的参数 * @param requestCode * 请求参数 */ public void JumpToActivityForResult(Class<?> cls, Bundle bundle, int requestCode) { Intent intent = new Intent(this, cls); if (null != bundle) { intent.putExtras(bundle); } // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);// // 设置跳转标志为如此Activity存在则把其从任务堆栈中取出放到最上方 // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { startActivityForResult(intent, requestCode); } catch (ActivityNotFoundException e) { e.printStackTrace(); } } @Override protected void onDestroy() { // 结束Activity&从堆栈中移除 AppManager.getAppManager().finishActivity(this); super.onDestroy(); } public void showLoadingDialog() { if (null == loadingDialog) { loadingDialog = new MyProgressDialog(this, true); loadingDialog.setCanceledOnTouchOutside(true); } loadingDialog.show(); } public void showLoadingDialog(OnCancelListener listener) { if (null == loadingDialog) { loadingDialog = new MyProgressDialog(this, true); loadingDialog.setCanceledOnTouchOutside(true); } loadingDialog.setOnCancelListener(listener); loadingDialog.show(); } public void showLoadingDialog(String title) { if (null == loadingDialog) { loadingDialog = new MyProgressDialog(this, title, true); loadingDialog.setCanceledOnTouchOutside(true); } loadingDialog.show(); } public void dismissLoadingDialog() { if (null != loadingDialog) loadingDialog.dismiss(); } /** * 确认对话框 * * @param title * @param btn * @param sureDo */ public void showSureDialog(String title, String btn, final OnSurePress sureDo) { final Dialog dialog = new Dialog(this, R.style.dialog_sure); View view = View.inflate(this, R.layout.z_dialog_sure, null); dialog.setContentView(view); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); TextView WTitle = (TextView) view.findViewById(R.id.title); WTitle.setText(title); view.findViewById(R.id.btn_dismiss).setOnClickListener(new OnClickListener() { public void onClick(View v) { dialog.dismiss(); } }); Button sureButton = (Button) view.findViewById(R.id.btn_show); if (btn != null && btn.trim().length() > 0) { sureButton.setText(btn); } sureButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { dialog.dismiss(); sureDo.onClick(v); } }); dialog.show(); } /** * 确认对话框 * * @param context * @param title * @param btn * @param sureDo * @param cancel */ @SuppressLint("InflateParams") public void showSureDialog(String title, String btn, final OnSurePress sureDo, OnCancelListener cancel) { final Dialog dialog = new Dialog(this, R.style.dialog_sure); View view = getLayoutInflater().inflate(R.layout.z_dialog_sure, null); dialog.setContentView(view); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); TextView WTitle = (TextView) view.findViewById(R.id.title); WTitle.setText(title); Button sureButton = (Button) view.findViewById(R.id.btn_show); sureButton.setText(btn); sureButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { sureDo.onClick(v); dialog.dismiss(); } }); dialog.setOnCancelListener(cancel); dialog.show(); } /** * 确认选择对话框 * * @param items * @param itemSelected */ public void showSelectDialog(String[] items, final OnItemClick itemSelected) { showSelectDialog(Arrays.asList(items), itemSelected); } /** * 确认选择对话框 * * @param items * @param itemSelected */ public void showSelectDialog(final List<String> items, final OnItemClick onItemClick) { final Dialog dialog = new Dialog(this, R.style.dialog_sure); View view = View.inflate(this, R.layout.z_dialog_select, null); dialog.setContentView(view); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); ListView list = (ListView) view.findViewById(R.id.listview); list.setAdapter(new SelectDialogAdapter_z(this, items)); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { dialog.dismiss(); onItemClick.onClick(view, position); } }); dialog.show(); } public int getResColor(int colId) { return ContextCompat.getColor(this, colId); } public String[] getStrArr(int rid) { return getResources().getStringArray(rid); } public int[] getIntArr(int rid) { return getResources().getIntArray(rid); } /** * 加载布局 * * @param layoutId * @param root * @return */ public View getResLayout(int layoutId, ViewGroup root) { return getLayoutInflater().inflate(layoutId, root); } /** * EditText内容为空提示 * * @param edit * @param showToast */ public boolean cantEmpty(EditText edit, int showToast) { if (StringUtils.isStringNone(edit.getText().toString())) { showToast(showToast); return true; } return false; } /** * 获取用户数据,如果为null代表没有登录 * * @return */ public User getUser() { return UserUtil.getUser(this); } /** * 退出登录 * * @return */ public void clearUser() { UserUtil.clearUser(this); } /** * 获取当前项目 * * @return project */ public Project getProject() { Project project = SPUtil.getObjectFromShare(Project.class.getName()); if (null == project) { project = new Project(); project.setId(-1); project.setShortCode(""); project.setFullCode(""); project.setName(""); project.setShortName(""); project.setFullName(""); } return project; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } /** * 判断两次返回时间间隔,小于两秒则退出程序 */ @Override public void onBackPressed() { super.onBackPressed(); if (withAinm) { overridePendingTransition(R.anim.z_push_left_in, R.anim.z_push_right_out); } } /** * 确认按钮监听接口 * * @author gavin.xiong * */ public interface OnSurePress { void onClick(View view); } /** * 确认按钮监听接口 * * @author gavin.xiong * */ public interface OnSurePressNoView { void onClick(); } /** * 子项选择监听接口 * * @author gavin.xiong * */ public interface OnItemClick { void onClick(View view, int position); } } <file_sep>package com.ricelink.coolead.net; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.message.BasicHeader; import com.loopj.android.http.RequestParams; /** * RequestModel.java * * @author: gavin.xiong * @Function: 网络请求模型 */ public class RequestModel { private String url; // 请求网络地址 private List<Header> headers = new ArrayList<Header>(); private RequestParams params; // 请求参数 private HttpEntity entity; // 请求体 private String json; // 请求体 private Class<?> cls; // 请求转换数据模型类 private boolean showDialog = true; // 是否显示网络加载对话框 private boolean showErrorMessage = false; // 是否显示错误的信息 private boolean checkNetStatus = true; // 是否检查网络状态 private boolean checkToken = true; // 是否检查token public String getUrl() { return url; } public void setUrl(String url) { // @whsy 去除url中的空格 this.url = url.replaceAll(" ", ""); } public List<Header> getHeaders() { return headers; } public void setHeaders(List<Header> headers) { this.headers = headers; } public RequestParams getParams() { return params; } public void setParams(RequestParams params) { this.params = params; } public HttpEntity getEntity() { return entity; } public void setEntity(HttpEntity entity) { this.entity = entity; } public String getJson() { return json; } public void setJson(String json) { this.json = json; } public Class<?> getCls() { return cls; } public void setCls(Class<?> cls) { this.cls = cls; } public boolean isShowDialog() { return showDialog; } public void setShowDialog(boolean showDialog) { this.showDialog = showDialog; } public boolean isShowErrorMessage() { return showErrorMessage; } public void setShowErrorMessage(boolean showErrorMessage) { this.showErrorMessage = showErrorMessage; } public boolean isCheckNetStatus() { return checkNetStatus; } public void setCheckNetStatus(boolean checkNetStatus) { this.checkNetStatus = checkNetStatus; } public boolean isCheckToken() { return checkToken; } public void setCheckToken(boolean checkToken) { this.checkToken = checkToken; } /** * 添加请求头 * * @param header */ public void addHeader(String name, String value) { BasicHeader header = new BasicHeader(name, value); this.headers.add(header); } } <file_sep>package com.ricelink.coolead.app.activity; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.view.View; import android.widget.TextView; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.v.R; /** * 发起工单页面 * * @author gavin.xiong * */ public class AboutActivity extends BaseActivity { private HeaderBar title; private TextView tv_version_name; public AboutActivity() { super(R.layout.activity_about); } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); tv_version_name = (TextView) findViewById(R.id.tv_version_name); } @Override public void initData() { // } @Override public void bindViews() { title.setTitle(R.string.label_about); tv_version_name.setText(getCurrVersionName()); } /** * 点击事件监听 */ public void onClick(View v) { switch (v.getId()) { } } /** * 获取版本号 * * @return 当前应用的版本号 */ public String getCurrVersionName() { try { PackageManager manager = getPackageManager(); PackageInfo info = manager.getPackageInfo(getPackageName(), 0); return info.versionName; } catch (NameNotFoundException e) { e.printStackTrace(); } return ""; } } <file_sep>package com.ricelink.coolead.model; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnore; import com.lidroid.xutils.db.annotation.Column; import com.lidroid.xutils.db.annotation.Id; import com.lidroid.xutils.db.annotation.Table; /** * 子巡检 * * @author gavin.xiong * */ @Table(name = "InspectionItem") public class InspectionItem implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @Column(column = "id") private long id; @Column(column = "objectName") private String objectName; @Column(column = "routeId") private long routeId; @Column(column = "orderId") private long orderId; @Column(column = "serial") private String serial; @Column(column = "objectCode") private String objectCode; @Column(column = "objectType") private String objectType; @Column(column = "status") private String status; @JsonIgnore @Column(column = "waitUpload") private int waitUpload; @JsonIgnore @Column(column = "eqStatus") private String eqStatus; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } public long getRouteId() { return routeId; } public void setRouteId(long routeId) { this.routeId = routeId; } public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } public String getObjectCode() { return objectCode; } public void setObjectCode(String objectCode) { this.objectCode = objectCode; } public String getObjectType() { return objectType; } public void setObjectType(String objectType) { this.objectType = objectType; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public static long getSerialversionuid() { return serialVersionUID; } public int isWaitUpload() { return waitUpload; } public void setWaitUpload(int waitUpload) { this.waitUpload = waitUpload; } public String getEqStatus() { return eqStatus; } public void setEqStatus(String eqStatus) { this.eqStatus = eqStatus; } } <file_sep>package com.ricelink.coolead.app.fragment; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.view.View; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.activity.WorkOrderDetailsActivity; import com.ricelink.coolead.app.adapter.WorkOrderAdapter; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.model.WorkOrder; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.ListResponeModel; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; /** * 工单列表页面 * * @author gavin.xiong * */ public class WorkOrderListFragment extends BaseFragment { private SwipeRefreshLayout swipeRefreshLayout; private ListView xlist; private WorkOrderAdapter adapter; private List<WorkOrder> workOrderList = new ArrayList<WorkOrder>(); private List<WorkOrder> workOrderListAll = new ArrayList<WorkOrder>(); private String workorder_status; private boolean haveMore = false; private boolean loadingMore = false; private int offset = 0; private int limit = 15; public WorkOrderListFragment() { super(R.layout.fragment_workorder_list); } public void setWorkorder_status(String workorder_status) { this.workorder_status = workorder_status; } @Override public void initViews() { swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); xlist = (ListView) findViewById(R.id.listview); adapter = new WorkOrderAdapter(mActivity, workOrderListAll); xlist.setAdapter(adapter); } @Override public void initData() { getWorkOrderList(workorder_status, false); } @Override public void bindViews() { xlist.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Bundle bundle = new Bundle(); bundle.putSerializable(Constants.INTENT_EXTRA_WORKORDER, workOrderListAll.get(arg2)); JumpToActivity(WorkOrderDetailsActivity.class, bundle); } }); xlist.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub if (OnScrollListener.SCROLL_STATE_IDLE == scrollState) { // 手指按下并开始滑动 // TODO Auto-generated method stub } else if (OnScrollListener.SCROLL_STATE_TOUCH_SCROLL == scrollState) { // 手指松开且完全停止滑动 // TODO Auto-generated method stub } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // 滑到倒数第二项时加载更多 if (haveMore && !loadingMore && totalItemCount <= firstVisibleItem + visibleItemCount) { loadingMore = true; offset += limit; getWorkOrderList(workorder_status, true); } } }); swipeRefreshLayout.setColorSchemeColors(getIntArr(R.array.swipeRefreshLayout_color)); swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { offset = 0; getWorkOrderList(workorder_status, false); } }); } /** * 获取历史巡检列表 */ private void getWorkOrderList(String status, final boolean isMore) { NetManager.getInstance(mActivity).getWorkOrderList(status, mActivity.getProject().getShortCode(), false, offset, limit, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); ListResponeModel listResponse = JsonUtil.convertJsonToObject(responeModel.getResult(), ListResponeModel.class); if (null != listResponse) { // 成功 if (listResponse.getTotalCount() > listResponse.getLimit() + listResponse.getOffset()) { haveMore = true; } else { haveMore = false; } workOrderList = JsonUtil.convertJsonToList(listResponse.getList(), WorkOrder.class); if (null != workOrderList) { if (!isMore) { workOrderListAll.clear(); } workOrderListAll.addAll(workOrderList); adapter.notifyDataSetChanged(); } } else { // 失败 showToast(getResString(R.string.toast_get_failed) + responeModel.getMessage()); } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); showToast(getResString(R.string.toast_get_failed)); } @Override public void onFinish() { super.onFinish(); loadingMore = false; swipeRefreshLayout.setRefreshing(false); } }); } @Override public void refreshPage(RefreshModel refreshModel) { if (refreshModel.all || refreshModel.workOrder_list) { initData(); } } } <file_sep>package com.ricelink.coolead.app.activity; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.widget.TextView; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.v.R; /** * 保养内容明细页面 * * @author gavin.xiong * */ public class MaintenanceContentDetailActivity extends BaseActivity { private HeaderBar title; private TextView tv_content; public MaintenanceContentDetailActivity() { super(R.layout.activity_maintenance_content_detail); } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); tv_content = (TextView) findViewById(R.id.tv_content); } @Override public void initData() { } @SuppressWarnings("static-access") @Override public void bindViews() { title.setTitle(R.string.label_maintenance_content_details); // 让 TextView 可滚动 tv_content.setMovementMethod(new ScrollingMovementMethod().getInstance()); } /** * 点击事件监听 */ public void onClick(View v) { switch (v.getId()) { } } } <file_sep>package com.ricelink.coolead.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.lidroid.xutils.db.annotation.Column; import com.lidroid.xutils.db.annotation.Id; import com.lidroid.xutils.db.annotation.Table; /** * 巡检model * * @author gavin.xiong * */ @Table(name = "InspectionContent") public class InspectionContent { @Id @Column(column = "_id") @JsonIgnore private long _id; @Column(column = "id") private long id; @Column(column = "kbId") private long kbId; @JsonIgnore @Column(column = "eqCode") private String eqCode; @Column(column = "endTime") private String endTime; @JsonIgnore @Column(column = "content") private String content; @JsonIgnore @Column(column = "style") private String style; @JsonIgnore @Column(column = "standard") private String standard; @Column(column = "isTranscribing") private String isTranscribing; @JsonIgnore @Column(column = "transcribingUnit") private String transcribingUnit; @JsonIgnore @Column(column = "suggestWorkTime") private long suggestWorkTime; @JsonIgnore @Column(column = "lowerLimit") private String lowerLimit; @JsonIgnore @Column(column = "upperLimit") private String upperLimit; @Column(column = "transcribingData") private String transcribingData; @JsonIgnore @Column(column = "energyReading") private String energyReading; @Column(column = "result") private String result; @Column(column = "expDescription") private String expDescription; @JsonIgnore @Column(column = "routeId") private long routeId; @Column(column = "orderId") private long orderId; @Column(column = "meterId") private String meterId; @JsonIgnore @Column(column = "objectCode") private String objectCode; public long get_id() { return _id; } public void set_id(long _id) { this._id = _id; } public long getId() { return id; } public void setId(long id) { this.id = id; } public long getKbId() { return kbId; } public void setKbId(long kbId) { this.kbId = kbId; } public String getEqCode() { return eqCode; } public void setEqCode(String eqCode) { this.eqCode = eqCode; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getStandard() { return standard; } public void setStandard(String standard) { this.standard = standard; } public String getIsTranscribing() { return isTranscribing; } public void setIsTranscribing(String isTranscribing) { this.isTranscribing = isTranscribing; } public String getTranscribingUnit() { return transcribingUnit; } public void setTranscribingUnit(String transcribingUnit) { this.transcribingUnit = transcribingUnit; } public long getSuggestWorkTime() { return suggestWorkTime; } public void setSuggestWorkTime(long suggestWorkTime) { this.suggestWorkTime = suggestWorkTime; } public String getLowerLimit() { return lowerLimit; } public void setLowerLimit(String lowerLimit) { this.lowerLimit = lowerLimit; } public String getUpperLimit() { return upperLimit; } public void setUpperLimit(String upperLimit) { this.upperLimit = upperLimit; } public String getTranscribingData() { return transcribingData; } public void setTranscribingData(String transcribingData) { this.transcribingData = transcribingData; } public String getEnergyReading() { return energyReading; } public void setEnergyReading(String energyReading) { this.energyReading = energyReading; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public String getExpDescription() { return expDescription; } public void setExpDescription(String expDescription) { this.expDescription = expDescription; } public long getRouteId() { return routeId; } public void setRouteId(long routeId) { this.routeId = routeId; } public String getMeterId() { return meterId; } public void setMeterId(String meterId) { this.meterId = meterId; } public String getObjectCode() { return objectCode; } public void setObjectCode(String objectCode) { this.objectCode = objectCode; } } <file_sep>package com.ricelink.coolead.model; import java.io.Serializable; import java.util.List; import com.lidroid.xutils.db.annotation.Id; import com.lidroid.xutils.db.annotation.NoAutoIncrement; import com.lidroid.xutils.db.annotation.Table; /** * 工单 * * @author gavin.xiong * */ @Table(name = "WorkOrder") public class WorkOrder implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @NoAutoIncrement private long id; private long workFlowId; private String code; private String type; private String source; private String title; private String orderPro; private int level; private String address; private long planEndTime; private String content; private long planTime; private long startTime; private String reporter; private String isQualified; private String isInTime; private String reason; private String checker; private String remark; private String status; private String projectCode; private String projectName; private String orderMatDetail; private String eqCode; private String eqName; private String current; private long currentId; private long routeId; private String transactor; private String currentTransactor; private int distributionType; private String distributionTime; private List<String> attachments; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getWorkFlowId() { return workFlowId; } public void setWorkFlowId(long workFlowId) { this.workFlowId = workFlowId; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getOrderPro() { return orderPro; } public void setOrderPro(String orderPro) { this.orderPro = orderPro; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public long getPlanEndTime() { return planEndTime; } public void setPlanEndTime(long planEndTime) { this.planEndTime = planEndTime; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public long getPlanTime() { return planTime; } public void setPlanTime(long planTime) { this.planTime = planTime; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public String getReporter() { return reporter; } public void setReporter(String reporter) { this.reporter = reporter; } public String getIsQualified() { return isQualified; } public void setIsQualified(String isQualified) { this.isQualified = isQualified; } public String getIsInTime() { return isInTime; } public void setIsInTime(String isInTime) { this.isInTime = isInTime; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getChecker() { return checker; } public void setChecker(String checker) { this.checker = checker; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getProjectCode() { return projectCode; } public void setProjectCode(String projectCode) { this.projectCode = projectCode; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getOrderMatDetail() { return orderMatDetail; } public void setOrderMatDetail(String orderMatDetail) { this.orderMatDetail = orderMatDetail; } public String getEqCode() { return eqCode; } public void setEqCode(String eqCode) { this.eqCode = eqCode; } public String getEqName() { return eqName; } public void setEqName(String eqName) { this.eqName = eqName; } public String getCurrent() { return current; } public void setCurrent(String current) { this.current = current; } public long getCurrentId() { return currentId; } public void setCurrentId(long currentId) { this.currentId = currentId; } public long getRouteId() { return routeId; } public void setRouteId(long routeId) { this.routeId = routeId; } public String getTransactor() { return transactor; } public void setTransactor(String transactor) { this.transactor = transactor; } public String getCurrentTransactor() { return currentTransactor; } public void setCurrentTransactor(String currentTransactor) { this.currentTransactor = currentTransactor; } public int getDistributionType() { return distributionType; } public void setDistributionType(int distributionType) { this.distributionType = distributionType; } public String getDistributionTime() { return distributionTime; } public void setDistributionTime(String distributionTime) { this.distributionTime = distributionTime; } public List<String> getAttachments() { return attachments; } public void setAttachments(List<String> attachments) { this.attachments = attachments; } } <file_sep>package com.ricelink.coolead.app.adapter; import java.util.List; import com.ricelink.coolead.app.activity.BaseActivity; import com.ricelink.coolead.v.R; /** * 选择对对话框适配器 * * @author gavin.xiong * */ public class SelectDialogAdapter_z extends CommonAdapter<String> { public SelectDialogAdapter_z(BaseActivity context, List<String> list) { super(context, list, R.layout.z_item_dialog_select); } @Override public void convert(CommonViewHolder holder, String t, int position) { holder.setText(R.id.only_textview, t); } } <file_sep>package com.ricelink.coolead.model; /** * 设备 * * @author gavin.xiong * */ public class Device extends BaseModel { /** * */ private static final long serialVersionUID = 1L; /** * id */ private long id; /** * 设备名称 */ private String Name; /** * 设备编号 */ private String code; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public void setCode(String code) { this.code = code; } public String getCode() { return code; } } <file_sep>package com.ricelink.coolead.app.fragment; import java.util.ArrayList; import java.util.List; import com.lidroid.xutils.exception.DbException; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.activity.ChatActivity; import com.ricelink.coolead.app.activity.MainActivity; import com.ricelink.coolead.app.adapter.MessageAdapter; import com.ricelink.coolead.app.adapter.MessageAdapter.OnTitleIsNullCallBack; import com.ricelink.coolead.helper.JsonUtil; import com.ricelink.coolead.helper.StringUtils; import com.ricelink.coolead.helper.ToastUtil; import com.ricelink.coolead.helper.ViewHelper; import com.ricelink.coolead.model.IMMessage; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.model.ServerInfo; import com.ricelink.coolead.net.CustomAsyncResponehandler; import com.ricelink.coolead.net.NetManager; import com.ricelink.coolead.net.ResponeModel; import com.ricelink.coolead.v.R; import com.ricelink.coolead.xmpp.IMMessageManager; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * 我的互动页 * * @author gavin.xiong * */ public class MultiMessageFragment extends BaseFragment implements OnItemClickListener { private SwipeRefreshLayout swipeRefreshLayout; private ListView listView; private MessageAdapter mAdapter; private List<IMMessage> noticeList; public MultiMessageFragment() { super(R.layout.fragment_message); } @Override public void initViews() { swipeRefreshLayout = ViewHelper.get(mView, R.id.swipe_container); listView = ViewHelper.get(mView, R.id.fragment_message_lv); } @Override public void initData() { noticeList = new ArrayList<IMMessage>(); mAdapter = new MessageAdapter(mActivity, noticeList); mAdapter.setOnTitleIsNullCallBack(new OnTitleIsNullCallBack() { @Override public void onTitleNull(String groupCode) { getServerInfo(groupCode, "" + StringUtils.getServerIdByGroupCode(groupCode)); } }); listView.setAdapter(mAdapter); } @Override public void bindViews() { swipeRefreshLayout.setColorSchemeColors(getIntArr(R.array.swipeRefreshLayout_color)); swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { new GetDataTask().execute(); } }); listView.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { IMMessage message = mAdapter.getItem(arg2); System.out.println(message); try { if (null != message) { if (IMMessage.MESSAGE_TYPE_CHAT_MSG == message.getNoticeType()) { Bundle bundle = new Bundle(); bundle.putString(Constants.INTENT_EXTRA_SERVER_GROUPCODE, message.getGroupCode()); JumpToActivity(ChatActivity.class, bundle); } else if (IMMessage.MESSAGE_TYPE_SYS_MSG == message.getNoticeType()) { ToastUtil.showToast("系统消息"); } } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onContextItemSelected(MenuItem item) { IMMessage message = (IMMessage) item.getIntent().getSerializableExtra(Constants.INTENT_EXTRA_IMMESSAGE_KEY); if (item.getItemId() == Constants.MENU_MESSAGE_ITEMID_DELETE_CHATMSG) { if (null != message) { if (IMMessageManager.getImMessageManager().deleteMsgWhereGroupCode(message.getGroupCode())) { // 删除成功 刷新列表 new GetDataTask().execute(); } } } else if (item.getItemId() == Constants.MENU_MESSAGE_ITEMID_DELETE_SYSMSG) { if (null != message) { if (IMMessageManager.getImMessageManager().deleteMsgWhereType(IMMessage.MESSAGE_TYPE_SYS_MSG)) { // 删除成功 刷新列表 new GetDataTask().execute(); } } } return true; } /** * 收到新消息 * * @param notice */ public void msgReceive(IMMessage message) { boolean isAdd = false; System.out.println(message); for (IMMessage imm : noticeList) { if (imm.getGroupCode().equals(message.getGroupCode()) && imm.getNoticeType().equals(message.getNoticeType())) { noticeList.remove(imm); imm.setContent(message.getContent()); imm.setTime(message.getTime()); Integer x = null == imm.getNoticeSum() ? 0 : imm.getNoticeSum(); imm.setNoticeSum(x + message.getNoticeSum()); noticeList.add(0, imm); isAdd = true; break; } } if (!isAdd) { if (noticeList == null) { noticeList = new ArrayList<IMMessage>(); } noticeList.add(0, message); } mAdapter.refreshData(noticeList); showMessageTip(); } /** * 显示首页未读消息条数 */ private void showMessageTip() { int msgCount = 0; for (IMMessage imm : noticeList) { msgCount += imm.getNoticeSum(); } ((MainActivity) mActivity).setTabTip(2, 0 == msgCount ? null : (msgCount + "")); } @Override public void onResume() { super.onResume(); new GetDataTask().execute(); } /** * 后台获取消息记录 * * @author gavin.xiong * */ private class GetDataTask extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... arg0) { try { noticeList = IMMessageManager.getImMessageManager().getRecentContactsWithLastMsg(); if (null != noticeList && noticeList.size() > 0) { return true; } else { return false; } } catch (DbException e) { e.printStackTrace(); return false; } } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); swipeRefreshLayout.setRefreshing(false); if (result) { if (mAdapter == null) { mAdapter = new MessageAdapter(mActivity, noticeList); listView.setAdapter(mAdapter); } else { mAdapter.refreshData(noticeList); } } showMessageTip(); } } /** * 获取需求详情 * * @param serverId */ private void getServerInfo(final String groupCode, String serverId) { NetManager.getInstance(mActivity).getServerInfo(serverId, new CustomAsyncResponehandler() { @Override public void onSuccess(ResponeModel responeModel) { super.onSuccess(responeModel); if (responeModel.isSuccess()) { ServerInfo servierInfo = JsonUtil.convertJsonToObject(responeModel.getResult(), ServerInfo.class); for (IMMessage imm : noticeList) { if (StringUtils.isEmpty(imm.getTitle())) { imm.setTitle(servierInfo.getQuestionTitle()); mAdapter.refreshData(noticeList); IMMessageManager.getImMessageManager().setTitle(groupCode, imm); return; } } } } @Override public void onFailure(Throwable error, String resultString) { super.onFailure(error, resultString); } }); } @Override public void refreshPage(RefreshModel refreshModel) { // TODO Auto-generated method stub } } <file_sep>package com.ricelink.coolead.model; import java.io.Serializable; /** * 权限内容 * * @author gavin.xiong * */ public class RoleContent implements Serializable { /** * */ private static final long serialVersionUID = 1L; public boolean SHOW_WORK_ORDER; // 工单 public boolean SHOW_INSPECTION; // 巡检 public boolean SHOW_PROJECT_SELECT; // 项目选择 public boolean SHOW_INITIATE_WORK_ORDER; // 发起工单 public boolean SHOW_DISTRIBUTE_INSPECTION; // 派发巡检 @Override public String toString() { return "RoleContent [SHOW_WORK_ORDER=" + SHOW_WORK_ORDER + ", SHOW_INSPECTION=" + SHOW_INSPECTION + ", SHOW_PROJECT_SELECT=" + SHOW_PROJECT_SELECT + ", SHOW_INITIATE_WORK_ORDER=" + SHOW_INITIATE_WORK_ORDER + ", SHOW_DISTRIBUTE_INSPECTION=" + SHOW_DISTRIBUTE_INSPECTION + "]"; } } <file_sep>package com.ricelink.coolead.app.activity; import java.util.ArrayList; import java.util.List; import org.jivesoftware.smack.packet.Presence; import com.ricelink.coolead.Constants; import com.ricelink.coolead.app.AppContext; import com.ricelink.coolead.app.adapter.TabFragmentPagerAdapter; import com.ricelink.coolead.app.fragment.InspectionFragment; import com.ricelink.coolead.app.fragment.InteractionFragment; import com.ricelink.coolead.app.fragment.MoreFragment; import com.ricelink.coolead.app.fragment.WorkOrderFragment; import com.ricelink.coolead.app.view.HeaderBar; import com.ricelink.coolead.app.view.SlidingSwitchViewPager; import com.ricelink.coolead.helper.DisplayUtils; import com.ricelink.coolead.helper.L; import com.ricelink.coolead.helper.SPUtil; import com.ricelink.coolead.helper.ToastUtil; import com.ricelink.coolead.model.IMMessage; import com.ricelink.coolead.model.RefreshModel; import com.ricelink.coolead.model.RoleContent; import com.ricelink.coolead.service.IMService; import com.ricelink.coolead.v.R; import com.ricelink.coolead.xmpp.XmppManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; /** * 主页面 * * @author gavin.xiong * */ public class MainActivity extends BaseActivity implements OnClickListener { private static final String TAG = "MainActivity"; private HeaderBar title; private LinearLayout llContainer; private SlidingSwitchViewPager mViewPager; private TabFragmentPagerAdapter mAdapter; private ArrayList<Fragment> fragments; private List<View> viewTabPanels; private List<TextView> txtTTabs; private List<ImageView> imgTabs; private List<TextView> txtTips; private int type = -1; private RoleContent roleContent; // 广播 private ContacterReceiver receiver; // 通知数量,未读消息数量 public int noticeNum = 0; private InteractionFragment interactionFragment; public MainActivity() { super(R.layout.activity_main); } public SlidingSwitchViewPager getSlidingSwitchViewPager() { return mViewPager; } @Override public void initViews() { title = (HeaderBar) findViewById(R.id.title); mViewPager = (SlidingSwitchViewPager) findViewById(R.id.content_container); llContainer = (LinearLayout) findViewById(R.id.rg_container_2); LinearLayout.LayoutParams llCOntainerParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, DisplayUtils.getRealHeight(this, 180)); llContainer.setLayoutParams(llCOntainerParams); viewTabPanels = new ArrayList<View>(); viewTabPanels.add(findViewById(R.id.mian_tabpanel_1)); viewTabPanels.add(findViewById(R.id.mian_tabpanel_2)); viewTabPanels.add(findViewById(R.id.mian_tabpanel_3)); viewTabPanels.add(findViewById(R.id.mian_tabpanel_4)); // viewTabPanels.add(findViewById(R.id.mian_tabpanel_5)); txtTTabs = new ArrayList<TextView>(); txtTTabs.add((TextView) findViewById(R.id.mian_tab_1)); txtTTabs.add((TextView) findViewById(R.id.mian_tab_2)); txtTTabs.add((TextView) findViewById(R.id.mian_tab_3)); txtTTabs.add((TextView) findViewById(R.id.mian_tab_4)); // txtTTabs.add((TextView) findViewById(R.id.mian_tab_5)); imgTabs = new ArrayList<ImageView>(); imgTabs.add((ImageView) findViewById(R.id.main_img_tab1)); imgTabs.add((ImageView) findViewById(R.id.main_img_tab2)); imgTabs.add((ImageView) findViewById(R.id.main_img_tab3)); imgTabs.add((ImageView) findViewById(R.id.main_img_tab4)); // imgTabs.add((ImageView) findViewById(R.id.main_img_tab5)); txtTips = new ArrayList<TextView>(); txtTips.add((TextView) findViewById(R.id.main_tip_1)); txtTips.add((TextView) findViewById(R.id.main_tip_2)); txtTips.add((TextView) findViewById(R.id.main_tip_3)); txtTips.add((TextView) findViewById(R.id.main_tip_4)); // txtTips.add((TextView) findViewById(R.id.main_tip_5)); FrameLayout.LayoutParams imgTabsParams = new FrameLayout.LayoutParams(DisplayUtils.getRealWidth(this, 80), DisplayUtils.getRealHeight(this, 80)); imgTabsParams.setMargins(DisplayUtils.dp2px(this, 4), DisplayUtils.dp2px(this, 4), DisplayUtils.dp2px(this, 4), DisplayUtils.dp2px(this, 4)); for (ImageView iv : imgTabs) { iv.setLayoutParams(imgTabsParams); } for (View tab : viewTabPanels) { tab.setOnClickListener(this); } } @Override public void initData() { roleContent = SPUtil.getObjectFromShare(RoleContent.class.getName()); fragments = new ArrayList<Fragment>(); fragments.add(new WorkOrderFragment()); fragments.add(new InspectionFragment()); // fragments.add(new EnergyFragment()); interactionFragment = new InteractionFragment(); fragments.add(interactionFragment); fragments.add(new MoreFragment()); Bundle bundle = getIntent().getExtras(); if (null != bundle) { type = bundle.getInt(Constants.INTENT_EXTRA_TYPE2MAIN, -1); } if (type == -1) { throw new IllegalArgumentException("the enter MainActivity's type is error!"); } receiver = new ContacterReceiver(); System.out.println("type = " + type); if (Constants.TYPE_GOMAIN_WELCOME == type) { // 从欢迎页进来,需要执行登录操作 new LoginTask().execute(); } else if (Constants.TYPE_GOMAIN_LOGIN == type) { // 从登录界面过来 启动相关服务获取数据 startService(); } } @Override public void bindViews() { Drawable drawableL = ContextCompat.getDrawable(this, R.drawable.ic_controlcenter); drawableL.setBounds(0, 0, drawableL.getMinimumWidth(), drawableL.getMinimumHeight()); // 必须设置图片大小,否则不显示 title.back.setCompoundDrawablePadding(8); title.back.setCompoundDrawables(drawableL, null, null, null); title.back.setText(getProject().getShortName()); Drawable drawableR = ContextCompat.getDrawable(this, R.drawable.ic_initiate); drawableR.setBounds(0, 0, drawableR.getMinimumWidth(), drawableR.getMinimumHeight()); // 必须设置图片大小,否则不显示 title.top_right_btn.setCompoundDrawablePadding(6); title.top_right_btn.setCompoundDrawables(drawableR, null, null, null); title.top_right_btn.setText(getString(R.string.label_initiate)); if (roleContent.SHOW_PROJECT_SELECT) { title.back.setVisibility(View.VISIBLE); } else { title.back.setVisibility(View.GONE); } if (roleContent.SHOW_INITIATE_WORK_ORDER) { title.top_right_btn.setVisibility(View.VISIBLE); } else { title.top_right_btn.setVisibility(View.GONE); } title.back.setOnClickListener(this); title.top_right_btn.setOnClickListener(this); mViewPager.setSlideable(true); mAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), fragments); mViewPager.setAdapter(mAdapter); /** * 设置当前页为第一页 */ setTabSelection(0); mViewPager.setCurrentItem(0); mViewPager.setOffscreenPageLimit(5); mViewPager.addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int pageId) { setTabSelection(pageId); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) {} @Override public void onPageScrollStateChanged(int arg0) {} }); } @Override protected void onResume() { Constants.Xmpp.isChatNotification = false; IntentFilter filter = new IntentFilter(); filter.addAction(Constants.ACTION_NEW_MESSAGE); filter.addAction(Constants.ACTION_RECONNECT_STATE); filter.addAction(Constants.ACTION_SYS_MSG); registerReceiver(receiver, filter); super.onResume(); } @Override protected void onPause() { Constants.Xmpp.isChatNotification = true; unregisterReceiver(receiver); SPUtil.saveObjectToShare(RefreshModel.class.getName(), null); super.onPause(); } @Override protected void onRestart() { title.back.setText(getProject().getShortName()); super.onRestart(); } @Override protected void onDestroy() { destoryService(); // 断开连接 AppContext.connectionManager.disconnect(); super.onDestroy(); } private void setTabSelection(int add) { clearSelection(); TextView txt = txtTTabs.get(add); txt.setTextColor(getResColor(R.color.main_text_blue)); if (add == 0) { imgTabs.get(0).setImageResource(R.drawable.ic_workorder_sel); title.setTitle(getString(R.string.label_wordorder)); if (roleContent.SHOW_PROJECT_SELECT) title.back.setVisibility(View.VISIBLE); if (roleContent.SHOW_INITIATE_WORK_ORDER) title.top_right_btn.setVisibility(View.VISIBLE); } else if (add == 1) { imgTabs.get(1).setImageResource(R.drawable.ic_inspection_sel); title.setTitle(getString(R.string.label_inspection)); if (roleContent.SHOW_PROJECT_SELECT) title.back.setVisibility(View.VISIBLE); title.top_right_btn.setVisibility(View.GONE); // } else if (add == 2) { // imgTabs.get(2).setImageResource(R.drawable.ic_energy_sel); // title.setTitle(getString(R.string.label_energy)); // if (roleContent.SHOW_PROJECT_SELECT) // title.back.setVisibility(View.VISIBLE); // title.top_right_btn.setVisibility(View.GONE); } else if (add == 2) { imgTabs.get(2).setImageResource(R.drawable.ic_interaction_sel); title.setTitle(getString(R.string.label_interaction)); title.back.setVisibility(View.GONE); title.top_right_btn.setVisibility(View.VISIBLE); } else if (add == 3) { imgTabs.get(3).setImageResource(R.drawable.ic_more_sel); title.setTitle(getString(R.string.label_more)); title.back.setVisibility(View.GONE); title.top_right_btn.setVisibility(View.GONE); } } private void clearSelection() { for (int i = 0; i < txtTTabs.size(); i++) { TextView txt = txtTTabs.get(i); txt.setTextColor(getResColor(R.color.main_color_text_gray)); } imgTabs.get(0).setImageResource(R.drawable.ic_workorder_nor); imgTabs.get(1).setImageResource(R.drawable.ic_inspection_nor); // imgTabs.get(2).setImageResource(R.drawable.ic_energy_nor); imgTabs.get(2).setImageResource(R.drawable.ic_interaction_nor); imgTabs.get(3).setImageResource(R.drawable.ic_more_nor); } /** * 点击事件监听 */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.mian_tabpanel_1: // 标签1 - 工单 setTabSelection(0); mViewPager.setCurrentItem(0, false); break; case R.id.mian_tabpanel_2: // 标签2 - 巡检 setTabSelection(1); mViewPager.setCurrentItem(1, false); break; case R.id.mian_tabpanel_3: // 标签3 - 互动 setTabSelection(2); mViewPager.setCurrentItem(2, false); break; case R.id.mian_tabpanel_4: // 标签4 - 更多 setTabSelection(3); mViewPager.setCurrentItem(3, false); break; // case R.id.mian_tabpanel_5: // 标签4 - 更多 // setTabSelection(4); // mViewPager.setCurrentItem(4, false); // break; case R.id.btn_top_back: // 项目选择 JumpToActivityForResult(ProjectSelectActivity.class, Constants.REQUEST_CODE_SELECT_PROJECT); break; case R.id.btn_top_right: // 发起 if (0 == mViewPager.getCurrentItem()) { // 发起工单 // JumpToActivity(AddWorkOrderActivity.class); Intent i = new Intent(this, AddWorkOrderActivity.class); startActivity(i); } else if (2 == mViewPager.getCurrentItem()) { // 发起互动 JumpToActivity(AddInteractionActivity.class); } break; } } /** * Back按钮监听,不销毁Activity,退到后台 */ @Override public void onBackPressed() { moveTaskToBack(true); } /** * 设置 tab 角标 */ public void setTabTip(int index, String tipString) { if (null == tipString || "0".equals(tipString)) { txtTips.get(index).setVisibility(View.GONE); } else { txtTips.get(index).setVisibility(View.VISIBLE); txtTips.get(index).setText(tipString); } } /** * 启动服务 */ private void startService() { System.out.println("startService"); Intent imService = new Intent(this, IMService.class); startService(imService); } /** * 销毁服务 */ private void destoryService() { System.out.println("destoryService"); Intent imService = new Intent(this, IMService.class); stopService(imService); } public void handReConnect(boolean isSuccess) { // mineFragment.onReConnect(isSuccess); } /** * 有新消息进来 * * @param user */ public void newMsgReceive(IMMessage message) { L.v(TAG, "newMsgReceive - " + message); interactionFragment.msgReceive(message); } /** * 收到系统类型消息 * * @param message */ public void systemMsgReceive(IMMessage message) {} /** * 回复一个presence信息给用户 * * @param type * @param to */ public void sendSubscribe(Presence.Type type, String to) { Presence presence = new Presence(type); presence.setTo(to); AppContext.connectionManager.getConnection().sendPacket(presence); } private class LoginTask extends AsyncTask<Void, Void, Integer> { @Override protected void onPreExecute() { super.onPreExecute(); showLoadingDialog(); } @Override protected Integer doInBackground(Void... arg0) { String userName = (String) AppContext.settingManager.readSetting(Constants.SP_KEY_USERNAME, ""); String password = (String) AppContext.settingManager.readSetting(Constants.SP_KEY_USERPSWD, ""); if (TextUtils.isEmpty(password) || TextUtils.isEmpty(password)) { return Constants.LOGIN_ERROR; } return XmppManager.getInstance().login(userName, password); } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); dismissLoadingDialog(); switch (result) { case Constants.LOGIN_SECCESS:// 登陆成功 // 开启服务 startService(); break; case Constants.LOGIN_ERROR_ACCOUNT_PASS:// 账号或密码错误 ToastUtil.showToast(R.string.toast_invalid_username_password); break; case Constants.LOGIN_ERROR:// 未知异常 ToastUtil.showToast(R.string.toast_unrecoverable_error); break; case Constants.SERVER_UNAVAILABLE:// 服务器连接失败 ToastUtil.showToast(R.string.toast_server_unavailable); break; } } } /** * 这又是什么鬼 * * @author gavin.xiong * */ private class ContacterReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { L.v(TAG, "ContacterReceiver.onReceive()"); String action = intent.getAction(); IMMessage message = (IMMessage) intent.getSerializableExtra(Constants.INTENT_EXTRA_IMMESSAGE_KEY); if (Constants.ACTION_NEW_MESSAGE.equals(action)) { newMsgReceive(message); } else if (Constants.ACTION_RECONNECT_STATE.equals(action)) { boolean isSuccess = intent.getBooleanExtra(Constants.INTENT_EXTRA_RECONNECT_STATE, true); handReConnect(isSuccess); } else if (Constants.ACTION_SYS_MSG.equals(action)) { systemMsgReceive(message); } } } }
ad7c086104b6ffe692c12286f5055fc8fb30aeac
[ "Java" ]
41
Java
ChenYouBo/Jialida
6ec63366481ff36f2e26befc70b6b2c103af76f4
73991a11f043ae494bb1621eb56757a2c532d641
refs/heads/master
<file_sep>#define SIZE 9 #define BOX_SIZE 3 #include <iostream> #include <fstream> #include <string> using namespace std; /** * @brief Represents a sudoku puzzle grid. Allows for certain actions such as * writing a number in a certain cell and checking if complete */ class Grid { private: char cells[SIZE][SIZE]; char original[SIZE][SIZE]; bool checkValid(int x, int y, char val); bool backtrack(char origCells[SIZE][SIZE], int x, int y); public: Grid(); ~Grid(); void loadBoard(string fileName); bool isComplete(); bool writeNum(int x, int y, char val); void undoNum(int x, int y); void print(); void solve(); };<file_sep>#include "game.hpp" Game::Game() { grid = new Grid(); } Game::~Game() { grid->~Grid(); } void Game::Run() { cout << "Enter the file name for the sudoku puzzle to load" << endl; string fileName; cin >> fileName; grid->loadBoard(fileName); grid->print(); while (true) { cout << "Enter d to do a move (followed by row, column and digit) and u to undo (followed by row and column)" << endl; string moveType; cin >> moveType; if (moveType == "d") { string row, col, val; cin >> row >> col >> val; int irow = atoi(row.c_str()); int icol = atoi(col.c_str()); int ival = atoi(val.c_str()); if (irow < 1 || irow > 9 || icol < 1 || icol > 9) { cout << "ERROR: Row and column numbers should be 1-9" << endl; } else if (ival < 1 || ival > 9) { cout << "ERROR: Cell values should be 1-9" << endl; } else { bool worked = grid->writeNum(irow - 1, icol - 1, *val.c_str()); if (worked == false) { cout << "ERROR: This move is not valid, try again" << endl; } } } else if (moveType == "u") { string row, col; cin >> row >> col; int irow = atoi(row.c_str()); int icol = atoi(col.c_str()); if (irow < 1 || irow > 9 || icol < 1 || icol > 9) { cout << "ERROR: Row and column numbers should be 1-9" << endl; } else { grid->undoNum(irow - 1, icol - 1); } } else if (moveType == "q") { cout << "Exiting!" << endl; return; } else { cout << "Enter a valid move type" << endl; } grid->print(); if (grid->isComplete()) { cout << "Good job! You solved it!" << endl; return; } } }<file_sep>#include "grid.hpp" /** * @brief Csonstructs a new grid of size 9 x 9. The * initial values are read from a file. * * @param * * @return */ Grid::Grid() { } Grid::~Grid() { } void Grid::loadBoard(string fileName) { ifstream fileIn; fileIn.open(fileName); int lineCt = 0; while(!fileIn.eof()) // To get you all the lines. { string x; getline(fileIn, x); // Saves the line in STRING. for (int i = 0; i < SIZE; i++) { cells[lineCt][i] = x.at(i); original[lineCt][i] = x.at(i); } lineCt += 1; } fileIn.close(); } bool Grid::isComplete() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { if (cells[i][j] == ' ') { return false; } } } return true; } // Should receive x and y values with 1 already subtracted bool Grid::writeNum(int x, int y, char val) { if (checkValid(x, y, val)) { cells[x][y] = val; return true; } else { return false; } } // Should receive already decremented void Grid::undoNum(int x, int y) { if (original[x][y] == ' '){ cells[x][y] = ' '; } else { cout << "ERROR: Attempted to undo given cell. " << endl; } } bool Grid::checkValid(int x, int y, char val) { for (int i = 0; i < SIZE; i++) { if (cells[x][i] == val && i != y) { return false; } if (cells[i][y] == val && x != i) { return false; } } int boxRowMin = x - x % 3; int boxColMin = y - y % 3; for (int i = boxRowMin; i < boxRowMin + 3; i ++) { for (int j = boxColMin; j < boxColMin + 3; j++) { if (cells[i][j] == val && !(i == x && j == y)) { return false; } } } return true; } void Grid::solve() { char cellsOrig[SIZE][SIZE]; for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { cellsOrig[i][j] = cells[i][j]; } } int x = 0, y = 0; while (cellsOrig[x][y] != ' ') { if (x == SIZE - 1) { x ++; y = 0; } else { y ++; } } bool worked = backtrack(cellsOrig, x, y); if(worked) { cout << "End of function" << endl; } else { cout << "ERROR - Solve did not succeed. Valid Input?"; } } bool Grid::backtrack(char cellsOrig[SIZE][SIZE], int x, int y) { if (x >= SIZE || y >= SIZE || isComplete()) return true; int nextX = x, nextY = y; do { if (nextY == SIZE - 1) { nextX ++; nextY = 0; } else { nextY ++; } } while (nextX < SIZE && cellsOrig[nextX][nextY] != ' '); for (int i = 1; i <= SIZE; i++) { if (checkValid(x, y, '0'+i)) { cells[x][y] = '0' + i; if (backtrack(cellsOrig, nextX, nextY)) { return true; } } } cells[x][y] = ' '; return false; } void Grid::print() { cout << "-------------------------" << endl; for (int i = 0; i < SIZE; i++) { cout << "| "; for (int j = 0; j < SIZE; j++) { cout << cells[i][j] << " "; if ((j + 1) % 3 == 0) { cout << "| "; } } cout << endl; if ((i + 1) % 3 == 0) { cout << "-------------------------" << endl; } } }<file_sep>#include "grid.hpp" class Game { private: Grid *grid; public: Game(); ~Game(); void Run(); };<file_sep># SudokuCS2Cpp CS 2 Assignment for implementing Sudoku U/I in C++ and Solution code <file_sep>#include "game.hpp" int main() { // Grid *grid = new Grid(); // string fileName; // cout << "File name of board you want to solve" << endl; // cin >> fileName; // grid->loadBoard(fileName); // grid->print(); // grid->solve(); // grid->print(); Game *game = new Game(); game->Run(); return 0; }
81366e95ad778abe000701e8cabab18d620074a7
[ "Markdown", "C++" ]
6
C++
maashok/SudokuCS2Cpp
205141ce9cab50080fe84ebc7e57bed0b2747bf5
7a4fa6c94f1bddf44d3dd352336f4f0d9f0a2128
refs/heads/master
<file_sep>Django~=3.1.2 pip~=20.0.2 pytz~=2020.1 wheel~=0.34.2 sqlparse~=0.4.1 asgiref~=3.2.10 certifi~=2019.11.28 chardet~=3.0.4 six~=1.14.0 webencodings~=0.5.1 idna~=2.8 urllib3~=1.25.8 pyparsing~=2.4.6 setuptools~=44.0.0 CacheControl~=0.12.6 requests~=2.22.0 msgpack~=0.6.2<file_sep>from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import CreateUserForm from .models import User def check_if_owner(request): return request.user.user.user_type == User.OWNER def check_if_seller(request): return request.user.user.user_type == User.SELLER def check_if_warehouseman(request): return request.user.user.user_type == User.WAREHOUSEMAN # owner menu def index(request): user = User.objects.get(name=request.user) if str(user.user_type) == "owner": pass elif str(user.user_type) == "seller": messages.error(request, 'access denied') return redirect('seller_index') elif str(user.user_type) == "warehouseman": messages.error(request, 'access denied') return redirect('warehouse_index') return render(request, "owner/index.html") # auth def register_page(request): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data['username'] user_type = form.cleaned_data['user_type'] user_type2 = form.cleaned_data['user_type2'] User.objects.create( user=user, name=user.username, user_type=user_type, user_type2=user_type2, ) messages.success(request, f'Created user {username}') return redirect('owner_index') else: print(form.errors) context = { 'form': form, } return render(request, "owner/register.html", context) def login_page(request): if request.user.is_authenticated: return render(request, 'warehouse/index.html') else: if request.method == "POST": username = request.POST.get('username') password = request.POST.get('<PASSWORD>') user = authenticate(request, username=username, password=<PASSWORD>, ) if user is not None: login(request, user) if str(User.objects.get(name=username).user_type) == "seller": return redirect('seller_index') elif str(User.objects.get(name=username).user_type) == "warehouseman": return redirect('warehouse_index') elif str(User.objects.get(name=username).user_type) == "owner": return redirect('owner_index') context = {} return render(request, "owner/login.html", context) def logout_page(request): logout(request) return redirect('login') <file_sep>{% extends 'warehouse/main.html' %} {% block title %} Edit product {% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="col-sm"> </div> <div class="col-sm"> <form method="POST"> {% csrf_token %} <div class="alert alert-primary" style="text-align: center" role="alert"> Product name </div> <div class="input-group mb-3"> {{ form.title }} </div> <div class="alert alert-primary" style="text-align: center" role="alert"> Category </div> <div class="input-group mb-3"> {{ form.category }} </div> <div class="alert alert-primary" style="text-align: center" role="alert"> Description </div> <div class="input-group mb-3"> {{ form.description }} </div> <div class="alert alert-primary" style="text-align: center" role="alert"> Price </div> <div class="input-group mb-3"> {{ form.price }} </div> <div class="alert alert-primary" style="text-align: center" role="alert"> Quantity on stock </div> <div class="input-group mb-3"> {{ form.quantity_on_stock }} </div> <button type="submit" class="btn btn-success btn-lg btn-block">Save changes</button> </form> </div> <div class="col-sm"> </div> </div> </div> {% endblock %}<file_sep>from django.db import models from django.contrib.auth.models import User as UserModel class User(models.Model): OWNER = 'owner' SELLER = 'seller' WAREHOUSEMAN = 'warehouseman' USER_TYPES = [ (OWNER, OWNER), (SELLER, SELLER), (WAREHOUSEMAN, WAREHOUSEMAN) ] user = models.OneToOneField(UserModel, on_delete=models.CASCADE) user_type = models.CharField(choices=USER_TYPES, max_length=20) name = models.CharField(max_length=50) def __str__(self): return self.name <file_sep># Generated by Django 3.1.4 on 2020-12-16 17:53 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('owner', '0002_user_user_type2'), ] operations = [ migrations.RemoveField( model_name='user', name='user_type', ), migrations.DeleteModel( name='UserType', ), ] <file_sep>from django.urls import path from . import views urlpatterns = [ path('', views.index, name='seller_index'), # order path('create-new-order/', views.create_order, name='new_order'), path('delete-order/<int:order_id>/', views.delete_order, name='delete_order'), path('order-details/<int:order_id>/', views.order_details, name='order_details'), path('change-open-status/<int:order_id>/', views.change_open_status, name='change_open_status'), path('change_paid_status/<int:order_id>/', views.change_paid_status, name='change_paid_status'), path('change_send_status/<int:order_id>/', views.change_send_status, name='change_send_status'), # product path('add-to-order/<int:product_id>/', views.add_to_order, name='add_to_order'), path('display-product/<int:product_id>/', views.display_product_info, name='order_product_info'), path('remove-from-order/<int:product_id>/<int:order_id>/', views.remove_from_order, name='remove_from_order'), path('increase-quantity/<int:product_id>/<int:order_id>/', views.increase_quantity, name='increase_quantity'), path('reduce-quantity/<int:product_id>/<int:order_id>/', views.reduce_quantity, name='reduce_quantity'), # category path('category-products/<int:category_id>/', views.category_products, name='order_category_products'), ] <file_sep>from django.shortcuts import render, redirect, get_object_or_404 from django.core.paginator import Paginator from django.core.exceptions import ObjectDoesNotExist from django.contrib import messages from django.contrib.auth.decorators import user_passes_test, login_required from owner.models import User from order.models import Order, OrderItem from .models import Item, Category from .forms import NewProductForm, SearchForProduct, NewCategoryForm, SearchForCategory def user_check(request): user = User.objects.get(name=request.user) return user.user_type == User.WAREHOUSEMAN or user.user_type == User.OWNER @login_required(login_url='login') def index(request): # user = User.objects.get(name=request.user) user = request.user.user if user.user_type == User.SELLER: messages.error(request, 'access denied') return redirect('seller_index') # low quantity products = Item.objects.filter(quantity_on_stock__lt=5) paginator = Paginator(products, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) # orders orders = Order.objects.filter(send_status=True) context = { 'low_quantity': page_obj, 'orders': orders, } return render(request, 'warehouse/index.html', context) # product @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def create_new_product(request): form = NewProductForm() if request.method == "POST": form = NewProductForm(request.POST) if form.is_valid(): if Item.objects.filter(title=form.cleaned_data['title']).exists(): messages.error(request, f'"{form.cleaned_data["title"]}" already on stock') else: new_product = Item.objects.create( title=form.cleaned_data['title'].title(), category=form.cleaned_data['category'], price=form.cleaned_data['price'], description=form.cleaned_data['description'], quantity_on_stock=form.cleaned_data['quantity_on_stock'] ) new_product.save() messages.success(request, f'"{form.cleaned_data["title"]}" created') return redirect('warehouse_index') context = { 'form': form, } return render(request, "warehouse/add_new_product.html", context) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def edit_product(request, product_id): product = get_object_or_404(Item, id=product_id) form = NewProductForm(request.POST or None, instance=product) if form.is_valid(): messages.success(request, f'Product "{product.title}" edited') form.save() return redirect('display_products') context = { 'form': form, 'product': product, } return render(request, "warehouse/edit_product.html", context) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def display_products(request): try: products = Item.objects.all() paginator = Paginator(products, 2) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'products': page_obj } return render(request, "warehouse/all_products.html", context) except ObjectDoesNotExist: messages.error(request, "You haven't any product in warehouse") return redirect('warehouse_index') @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def display_product_info(request, product_id): product = get_object_or_404(Item, id=product_id) context = { 'product': product } return render(request, "warehouse/product_info.html", context) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def search_product(request): search_form = SearchForProduct() expected_product = [] if request.method == "POST": search_form = SearchForProduct(request.POST) if search_form.is_valid(): # search by title and description if search_form.cleaned_data['title'] and search_form.cleaned_data['description']: title = search_form.cleaned_data['title'] description = search_form.cleaned_data['description'] products = Item.objects.all() for product in products: if (title.lower() in str(product).lower()) and ( description.lower() in str(product.description).lower()): expected_product.append(product) # search by title elif search_form.cleaned_data['title']: title = search_form.cleaned_data['title'] products = Item.objects.all() for product in products: if title.lower() in str(product).lower(): expected_product.append(product) # search by description elif search_form.cleaned_data['description']: description = search_form.cleaned_data['description'] products = Item.objects.all() for product in products: if description.lower() in str(product.description).lower(): expected_product.append(product) if len(expected_product) == 0: messages.error(request, 'Cant find any product') context = { 'search_form': search_form, 'expected_product': expected_product } return render(request, 'warehouse/search_for_product.html', context) # category @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def create_new_category(request): form = NewCategoryForm if request.method == "POST": form = NewCategoryForm(request.POST) if form.is_valid(): if Category.objects.filter(title=form.cleaned_data['title']).exists(): messages.error(request, f'Category "{form.cleaned_data["title"]}" already exists') else: new_category = Category.objects.create( title=form.cleaned_data['title'] ) new_category.save() messages.success(request, f'Category "{form.cleaned_data["title"]}" created') return redirect('/warehouse') context = { 'form': form } return render(request, "warehouse/add_new_category.html", context) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def display_categories(request): try: categories = Category.objects.all() context = { 'categories': categories } return render(request, "warehouse/all_categories.html", context) except ObjectDoesNotExist: messages.error(request, "You haven't any categories") return redirect('warehouse_index') @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def search_category(request): search_form = SearchForCategory() if request.method == "POST": search_form = SearchForCategory(request.POST) if search_form.is_valid(): title = search_form.cleaned_data['title'] try: category = Category.objects.get(title=title) return redirect('category_products', category_id=category.id) except ObjectDoesNotExist: messages.error(request, 'Cant find category') context = { 'search_form': search_form, } return render(request, 'warehouse/search_for_category.html', context) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def products_in_category(request, category_id): category = get_object_or_404(Category, id=category_id) products = Item.objects.filter(category=category) if len(products) > 0: context = { 'products': products } return render(request, "warehouse/category_products.html", context) else: messages.error(request, f'No products in category "{category}"') return redirect('warehouse_index') # order @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def display_order(request, order_id): order = get_object_or_404(Order, id=order_id) products = OrderItem.objects.filter(order_id=order.order_id) context = { 'order': order, 'products': products, } return render(request, 'warehouse/display_order.html', context) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def change_close_status(request, order_id): order = get_object_or_404(Order, id=order_id) order.send_status = False order.close_status = True order.save() messages.success(request, f'Order "{order.order_id}" status: Closed') return redirect('warehouse_index') <file_sep># Django-shop-manager ## Django app to manage a shop / warehouse ## Table of contents * [General info](#general-info) * [Technologies](#technologies) * [Setup](#setup) ## General info Web application created with Python and Django to manage a shop or warehouse.\ Application have three types of users: owner (admin), seller, warehouseman. Every user have special functions which he can use, for example: * You can login as: * owner -> Username: `admin` Password: `<PASSWORD>` * seller -> Username: `user1` Password: `<PASSWORD>` * warehouseman -> Username: `user2` Password: `<PASSWORD>` * owner: * Can create new user (owner/seller/warehouseman) * Have access to seller and warehouse panel * warehouseman: * Add new product or edit existing products * Create new categories or edit existing * Search for product (by title or description), category * Receives notifications when product quantity on stock is lower than 5 * Complete order * seller: * create new order * edit orders with status 'waiting' * search for orders * display available products in their categories * increase / reduce quantity of products in active order * change status to paid / unpaid * send order to warehouse to finalize ## Technologies Project is created with: * Python 3.8 * Django 3.1.2 * Bootstrap 4 ## Setup To run this project on Windows: * pip install virtualvenv (for keep order) * py -m venv myvenv * myvenv\scripts\activate * pip install -r requirements.txt * py manage.py runserver On Linux/Ubuntu: * sudo apt install python-pip * sudo apt install virtualenv (for keep order) * virtualenv myvenv * source myvenv/bin/activate * pip install -r requirements.txt * python manage.py runserver<file_sep>from django.urls import path from . import views urlpatterns = [ path('', views.index, name="warehouse_index"), # product path('create-new-product/', views.create_new_product, name='create_product'), path('edit-product/<int:product_id>/', views.edit_product, name='edit_product'), path('display-product/<int:product_id>/', views.display_product_info, name='product_info'), path('display-products/', views.display_products, name='display_products'), path('search-product/', views.search_product, name='search_product'), # category path('create-new-category/', views.create_new_category, name='create_category'), path('display-categories/', views.display_categories, name='display_categories'), path('category-products/<int:category_id>/', views.products_in_category, name='category_products'), path('search-category/', views.search_category, name='search_category'), # order path('display-order/<int:order_id>/', views.display_order, name='display_order'), path('change-close-status/<int:order_id>/', views.change_close_status, name='change_close_status'), ] <file_sep>import random from django.shortcuts import render, redirect, get_object_or_404 from django.core.paginator import Paginator from django.contrib import messages from django.contrib.auth.decorators import user_passes_test, login_required from django.core.exceptions import ObjectDoesNotExist from owner.models import User from warehouse.models import Item, Category from .models import OrderItem, Order from .forms import RawSearchOrder def user_check(request): user = User.objects.get(name=request.user) return str(user.user_type) == "seller" or str(user.user_type) == "owner" @login_required(login_url='login') def index(request): user = User.objects.get(name=request.user) if str(user.user_type) == "seller" or str(user.user_type) == "owner": pass elif str(user.user_type) == "warehouseman": messages.error(request, 'access denied') return redirect('warehouse_index') # open order open_order = Order.objects.filter(open_status=True) # waiting orders waiting_orders = Order.objects.filter(waiting_status=True) # categories categories = Category.objects.all() paginator = Paginator(categories, 4) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) # search search_form = RawSearchOrder() if request.method == "POST": search_form = RawSearchOrder(request.POST) if search_form.is_valid(): expected_order_id = search_form.cleaned_data['order_id'] try: expected_order = Order.objects.get(order_id=expected_order_id) return redirect('order_details', order_id=expected_order.id) except ObjectDoesNotExist: messages.error(request, f"Cant find order with id: {expected_order_id}") context = {'open_order': open_order, 'waiting_orders': waiting_orders, 'categories': page_obj, 'search_form': search_form } return render(request, "order/index.html", context) # order def create_unique_order_id(): """Function witch creating new unique order_id""" numbers = [] for i in range(48, 58): numbers.append(chr(i)) def create_id(): order_id = "order#" for i in range(5): x = random.choice(numbers) order_id += x return order_id while True: new_order_id = create_id() id_exists = Order.objects.filter(order_id=new_order_id) if not bool(id_exists): break return new_order_id @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def create_order(request): open_status_check = Order.objects.filter(open_status=True) if len(open_status_check) == 1: messages.error(request, f"You have one active order: {open_status_check[0]}") return redirect('seller_index') else: new_order_id = create_unique_order_id() Order.objects.create(order_id=new_order_id) messages.success(request, f"New order created! ID: {new_order_id}") return redirect('seller_index') @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def delete_order(request, order_id): order = Order.objects.get(id=order_id) products = OrderItem.objects.filter(order_id=order.order_id) if len(products) > 0: messages.error(request, 'Cannot delete order, because order still have products.') else: order.delete() messages.success(request, f'Order "{order.order_id}" deleted') return redirect('seller_index') @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def order_details(request, order_id): order = Order.objects.get(pk=order_id) order_items = OrderItem.objects.filter(order_id=order.order_id) waiting_orders = Order.objects.filter(waiting_status=True) # search search_form = RawSearchOrder() if request.method == "POST": search_form = RawSearchOrder(request.POST) if search_form.is_valid(): expected_order_id = search_form.cleaned_data['order_id'] try: expected_order = Order.objects.get(order_id=expected_order_id) return redirect('order_details', order_id=expected_order.id) except ObjectDoesNotExist: messages.error(request, f"Cant find order with id: {expected_order_id}") context = { 'order': order, 'order_items': order_items, 'waiting_orders': waiting_orders, 'search_form': search_form, } return render(request, "order/order_details.html", context) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def change_open_status(request, order_id): order = Order.objects.get(id=order_id) if order.open_status: order.open_status = False order.waiting_status = True order.save() messages.info(request, 'Changed order status to: waiting') elif not order.open_status: open_status_check = Order.objects.filter(open_status=True) if open_status_check.exists(): messages.error(request, 'You have to close active order to change this status!') else: order.waiting_status = False order.open_status = True order.save() messages.success(request, 'Changed order status to: open') return redirect('order_details', order_id=order_id) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def change_paid_status(request, order_id): order = Order.objects.get(id=order_id) products = OrderItem.objects.filter(order_id=order.order_id) if len(products) > 0: if order.open_status: if not order.paid: order.paid = True order.save() messages.success(request, f'Order "{order.order_id}" paid') elif order.paid: order.paid = False order.save() messages.success(request, f'Order "{order.order_id}" unpaid') else: messages.error(request, 'First you need to change the order status to "open"') else: messages.error(request, 'Cannot change paid status without items in order.') return redirect('order_details', order_id=order_id) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def change_send_status(request, order_id): order = Order.objects.get(id=order_id) if order.paid: order.open_status = False order.waiting_status = False order.send_status = True order.save() messages.success(request, 'Order has been send to warehouse') elif not order.paid: messages.error(request, 'Order have to be paid before send') return redirect('seller_index') # product @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def display_product_info(request, product_id): product = get_object_or_404(Item, id=product_id) context = { 'product': product } return render(request, 'order/product_info.html', context) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def add_to_order(request, product_id): product = Item.objects.get(pk=product_id) try: order = Order.objects.get(open_status=True) order_id = order.order_id if product.quantity_on_stock > 0: if OrderItem.objects.filter(item=product, order_id=order_id).exists(): new_order_item = OrderItem.objects.get(item=product, order_id=order_id) new_order_item.quantity += 1 new_order_item.save() product.quantity_on_stock -= 1 product.save() messages.success(request, "Product already in order, quantity increased by one.") else: item_order_id = f"{product.title}-{order_id}" new_order_item = OrderItem.objects.create(item=product, order_id=order_id, item_order_id=item_order_id) new_order_item.quantity += 1 new_order_item.save() product.quantity_on_stock -= 1 product.save() order.items.add(new_order_item) order.save() messages.success(request, f"{product.title} added to order") else: messages.error(request, f'No more "{product.title}" on stock') except ObjectDoesNotExist: messages.error(request, 'You have to have open order') return redirect('seller_index') @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def increase_quantity(request, product_id, order_id): order = Order.objects.get(id=order_id) product = OrderItem.objects.get(pk=product_id) item = Item.objects.get(title=product.item.title) if order.open_status: if item.quantity_on_stock > 0: product.quantity += 1 item.quantity_on_stock -= 1 product.save() item.save() else: messages.error(request, f'No more "{item}" on stock.') else: messages.error(request, 'First you need to change the order status to "open"') return redirect('order_details', order_id=order_id) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def reduce_quantity(request, product_id, order_id): order = Order.objects.get(id=order_id) product = OrderItem.objects.get(pk=product_id) item = Item.objects.get(title=product.item.title) if order.open_status: if product.quantity < 1: product.delete() messages.success(request, f'Removed from order "{item}"') else: product.quantity -= 1 item.quantity_on_stock += 1 product.save() item.save() else: messages.error(request, 'First you need to change the order status to "open"') return redirect('order_details', order_id=order_id) @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def remove_from_order(request, product_id, order_id): order = Order.objects.get(id=order_id) product = OrderItem.objects.get(pk=product_id) product_to_remove = OrderItem.objects.get(item_order_id=product) if order.open_status: item = Item.objects.get(title=product.item.title) item.quantity_on_stock += product_to_remove.quantity item.save() product_to_remove.delete() messages.success(request, f'Product "{item.title}" removed from order.') else: messages.error(request, 'First you need to change the order status to "open"') return redirect('order_details', order_id=order_id) # category @login_required(login_url='login') @user_passes_test(user_check, login_url='login') def category_products(request, category_id): products = Item.objects.filter(category=category_id) context = { 'products': products } return render(request, 'order/category_products.html', context) <file_sep>from django.urls import path from . import views urlpatterns = [ # owner menu path('menu', views.index, name='owner_index'), # auth path('register/', views.register_page, name='register'), ] <file_sep>from django import forms from .models import Order class SearchOrder(forms.ModelForm): class Meta: model = Order fields = ('order_id',) class RawSearchOrder(forms.Form): order_id = forms.CharField( label='', initial="order#", widget=forms.TextInput( attrs={"class": "form-control mr-sm-2", "placeholder": "Search order"}) ) <file_sep>from django.db import models class Category(models.Model): title = models.CharField(max_length=25) def __str__(self): return self.title class Meta: verbose_name_plural = "Categories" class Item(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, models.CASCADE) price = models.FloatField() description = models.TextField() quantity_on_stock = models.PositiveIntegerField(default=0) def __str__(self): return self.title <file_sep>from django import forms from .models import Item, Category class NewProductForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control", "style": "text-align:center", "placeholder": "Product name"})) category = forms.ModelChoiceField(Category.objects.all(), widget=forms.Select(attrs={"class": "form-control"})) price = forms.FloatField(widget=forms.NumberInput(attrs={"class": "form-control", "style": "text-align:center", "placeholder": "Price"})) description = forms.CharField(widget=forms.Textarea(attrs={"class": "form-control", "style": "text-align:center", "placeholder": "Description", "rows": 5})) quantity_on_stock = forms.IntegerField(widget=forms.NumberInput(attrs={"class": "form-control", "style": "text-align:center", "placeholder": "Quantity"})) class Meta: model = Item fields = ('title', 'category', 'price', 'description', 'quantity_on_stock', ) class SearchForProduct(forms.ModelForm): title = forms.CharField(required=False, widget=forms.TextInput(attrs={"class": "form-control", "style": "text-align:center", "placeholder": "search by title"})) description = forms.CharField(required=False, widget=forms.TextInput(attrs={"class": "form-control", "style": "text-align:center", "placeholder": "search by description"})) class Meta: model = Item fields = ('title', 'description', ) class NewCategoryForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control", "style": "text-align:center", "placeholder": "Category name"})) class Meta: model = Category fields = ('title', ) class SearchForCategory(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control", "style": "text-align:center", "placeholder": "search category"})) class Meta: model = Category fields = ('title', ) <file_sep># Generated by Django 3.1.4 on 2020-12-16 17:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('owner', '0003_auto_20201216_1853'), ] operations = [ migrations.RenameField( model_name='user', old_name='user_type2', new_name='user_type', ), ] <file_sep>from django.db import models from warehouse.models import Item class OrderItem(models.Model): item = models.ForeignKey(Item, models.CASCADE) quantity = models.PositiveIntegerField(default=0) order_id = models.CharField(max_length=11) item_order_id = models.CharField(max_length=100) # TODO foreign key to Order def __str__(self): return f"{self.item.title}-{self.order_id}" def get_item_name(self): return self.item.title def get_item_price(self): return self.item.price def get_total_item_price(self): item_total_price = (self.quantity * self.item.price) return item_total_price class Order(models.Model): order_id = models.CharField(max_length=11) # TODO we can remove it items = models.ManyToManyField(OrderItem) creation_date = models.DateTimeField(auto_now_add=True) open_status = models.BooleanField(default=True) waiting_status = models.BooleanField(default=False) send_status = models.BooleanField(default=False) close_status = models.BooleanField(default=False) paid = models.BooleanField(default=False) class Meta: ordering = ['creation_date'] def __str__(self): return self.order_id def get_total_price(self): order = Order.objects.get(order_id=self.order_id) items = order.items.all() total = 0 for item in items: total += item.get_total_item_price() return total <file_sep># Generated by Django 3.1.4 on 2020-12-16 17:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('owner', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='user_type2', field=models.CharField(choices=[('owner', 'owner'), ('seller', 'seller'), ('warehouseman', 'warehouseman')], default='owner', max_length=20), preserve_default=False, ), ] <file_sep># Generated by Django 3.1.3 on 2020-11-22 15:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('warehouse', '0001_initial'), ] operations = [ migrations.CreateModel( name='OrderItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('quantity', models.PositiveIntegerField(default=0)), ('order_id', models.CharField(max_length=11)), ('item_order_id', models.CharField(max_length=100)), ('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='warehouse.item')), ], ), migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('order_id', models.CharField(max_length=11)), ('creation_date', models.DateTimeField(auto_now_add=True)), ('open_status', models.BooleanField(default=True)), ('waiting_status', models.BooleanField(default=False)), ('send_status', models.BooleanField(default=False)), ('close_status', models.BooleanField(default=False)), ('paid', models.BooleanField(default=False)), ('items', models.ManyToManyField(to='order.OrderItem')), ], options={ 'ordering': ['creation_date'], }, ), ] <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>Menu</title> </head> <body> <div class="container"> <div class="row"> <div class="col-sm"> </div> <div class="col-sm" style="margin-top: 5%"> <h3 style="text-align:center">Django shop-manager</h3> {% for message in messages %} {% if 'success' in message.tags %} <div class="alert alert-success" style="text-align: center" role="alert"> {{ message }} </div> {% else %} <div class="alert alert-danger" style="text-align: center" role="alert"> {{ message }} </div> {% endif %} {% endfor %} <a href="{% url 'seller_index' %}" type="button" class="btn btn-outline-success btn-lg btn-block">Seller panel</a> <a href="{% url 'warehouse_index' %}" type="button" class="btn btn-outline-success btn-lg btn-block">Warehouse panel</a> <a href="{% url 'register' %}" type="button" class="btn btn-outline-success btn-lg btn-block">Create new employee</a> </div> <div class="col-sm"> </div> </div> </div> </body> </html>
4b27d461266c52e8c8855728b572afa9b6db4be3
[ "Markdown", "Python", "Text", "HTML" ]
19
Text
Netekss/Django-shop-manager
b35e6f37d7f9bd699ccb7a27af34e90f6d80860b
88bfb7e5507b9ca2077abc12c216f2f337966806
refs/heads/master
<file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from collections import namedtuple from decimal import Decimal from django.utils.encoding import python_2_unicode_compatible from itertools import groupby from .settings import PRICE_TYPE from .utils import quantize, currency @python_2_unicode_compatible class BasePrice(object): def __lt__(self, other): try: if PRICE_TYPE == 'gross': return self.gross < other.gross else: return self.net < other.net except: return NotImplemented def __le__(self, other): return self < other or self == other def __eq__(self, other): try: if PRICE_TYPE == 'gross': return self.gross == other.gross else: return self.net == other.net except: return False def __ne__(self, other): return not self == other def __radd__(self, other): return self + other def __rmul__(self, other): return self * other @property def tax(self): return self.gross - self.net def __str__(self): if PRICE_TYPE == 'gross': return currency(self.gross) else: return currency(self.net) class Price(BasePrice, namedtuple('Price', 'net gross rate')): def __new__(cls, price, rate=0): price = Decimal(price) rate = Decimal(rate) if rate: if PRICE_TYPE == 'gross': gross = quantize(price) net = quantize(gross / rate) else: net = quantize(price) gross = quantize(net * rate) else: gross = net = quantize(price) return super(Price, cls).__new__(cls, net, gross, rate) def __mul__(self, other): try: other = Decimal(other) if PRICE_TYPE == 'gross': return Price(self.gross * other, self.rate) else: return Price(self.net * other, self.rate) except TypeError: return NotImplemented def __add__(self, other): if isinstance(other, Price): return ComplexPrice((self, other)) elif isinstance(other, ComplexPrice): return ComplexPrice((self,) + other.prices) else: try: return self + Price(other, self.rate) except TypeError: return NotImplemented class ComplexPrice(BasePrice, namedtuple('ComplexPrice', 'net gross prices')): def __new__(cls, prices): prices = tuple(prices) net = Decimal(0) gross = Decimal(0) for price in prices: net += price.net gross += price.gross return super(ComplexPrice, cls).__new__(cls, net, gross, prices) def __add__(self, other): if isinstance(other, Price): return ComplexPrice(self.prices + (other,)) elif isinstance(other, ComplexPrice): return ComplexPrice(self.prices + other.prices) else: return NotImplemented @property def rates(self): return map( lambda (rate, prices): (rate, ComplexPrice(prices)), groupby(self.prices, lambda price: price.rate), ) <file_sep># -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = "cmsplugin_shop", version = '0.2', description = "Extensible E-Shop plugin for djangoCMS", author = "<NAME>", author_email = "<EMAIL>", url = "https://github.com/misli/cmsplugin-shop", packages = find_packages(), include_package_data = True, ) <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from django.conf import settings from django.utils.translation import ugettext_lazy as _ def S(name, default_value): return getattr(settings, 'CMSPLUGIN_SHOP_'+name, default_value) AUTH_USER_MODEL = settings.AUTH_USER_MODEL LOCALECONV = S('LOCALECONV', { 'currency_symbol': '$', 'int_curr_symbol': 'USD ', }) DECIMAL_PLACES = S('PRICE_DECIMAL_PLACES', 2) MAX_DIGITS = S('PRICE_MAX_DIGITS', 9) TAX_RATES = S('TAX_RATES', {0:_('no tax')}) DEFAULT_TAX_RATE = S('DEFAULT_TAX_RATE', TAX_RATES.keys()[0]) PRICE_TYPE = S('PRICE_TYPE', 'gross') PRODUCT_TEMPLATES = S('PRODUCT_TEMPLATES', (('default', _('default')),)) CATEGORY_TEMPLATES = S('CATEGORY_TEMPLATES', (('default', _('default')),)) CART_EXPIRY_DAYS = S('CART_EXPIRY_DAYS', 1) SESSION_KEY_CART = S('SESSION_KEY_CART', 'cmsplugin_shop_cart_id') SHOP_EMAIL = S('EMAIL', settings.SERVER_EMAIL) SEND_MAIL_KWARGS = S('SEND_MAIL_KWARGS', {}) INITIAL_ORDER_STATE = S('INITIAL_ORDER_STATE', 'new') PROFILE_ATTRIBUTE = getattr(settings, 'AUTH_USER_PROFILE_ATTRIBUTE', 'profile') <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from cms.plugin_base import CMSPluginBase from django.utils.translation import ugettext as _ from .models import ProductPlugin, CategoryPlugin class ProductPlugin(CMSPluginBase): model = ProductPlugin name = _('Product') text_enabled = True def render(self, context, instance, placeholder): context.update({ 'plugin': instance, 'product': instance.product, 'placeholder': placeholder, }) return context class CategoryPlugin(CMSPluginBase): model = CategoryPlugin name = _('Category') text_enabled = True def render(self, context, instance, placeholder): context.update({ 'plugin': instance, 'category': instance.category, 'placeholder': placeholder, }) return context <file_sep>{% load i18n %} {% if products.count %} <div class="list_products"> <h2>{% trans "Products" %}</h2> <ul> {% for product in products %} <li> <a href="{{ product.get_absolute_url }}">{{ product.name }}</a>, {{ product.unit_price }}Kč {{ product.summary | safe }} </li> {% endfor %} </ul> </div> {% endif %} <file_sep># -*- coding: utf-8 -*- from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement import tagging from cms.models import CMSPlugin from django.contrib.sites.models import Site from django.core.exceptions import ValidationError from django.core.mail import send_mail from django.core.urlresolvers import reverse from django.core.validators import RegexValidator from django.db import models from django.template import Context from django.template.loader import get_template from django.utils.encoding import python_2_unicode_compatible, smart_text from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from filer.fields.image import FilerImageField from mptt.fields import TreeForeignKey from mptt.models import MPTTModelBase from . import settings from .price import Price from .utils import get_rand_hash, get_html_field # allow different implementation of HTMLField HTMLField = get_html_field() class PriceField(models.DecimalField): def __init__(self, *args, **kwargs): kwargs.setdefault('decimal_places', settings.DECIMAL_PLACES) kwargs.setdefault('max_digits', settings.MAX_DIGITS) super(PriceField, self).__init__(*args, **kwargs) class TaxRateField(models.DecimalField): def __init__(self, *args, **kwargs): kwargs.setdefault('decimal_places', 4) kwargs.setdefault('max_digits', 9) kwargs.setdefault('choices', settings.TAX_RATES.items()) kwargs.setdefault('default', settings.DEFAULT_TAX_RATE) super(TaxRateField, self).__init__(*args, **kwargs) @MPTTModelBase.register @python_2_unicode_compatible class Node(models.Model): parent = TreeForeignKey('self', verbose_name=_('category'), blank=True, null=True, related_name='children', limit_choices_to={'product':None}) name = models.CharField(_('name'), max_length=250) slug = models.SlugField(_('slug'), max_length=250, db_index=True, unique=False) summary = HTMLField(_('summary'), blank=True, default='') description = HTMLField(_('description'), blank=True, default='') photo = FilerImageField(verbose_name='Fotka', null=True, blank=True, on_delete=models.SET_NULL) page_title = models.CharField(_('page title'), max_length=250, blank=True, null=True, help_text=_('overwrite the title (html title tag)')) menu_title = models.CharField(_('menu title'), max_length=250, blank=True, null=True, help_text=_('overwrite the title in the menu')) meta_desc = models.TextField(_('meta description'), blank=True, default='', help_text=_('the text displayed in search engines')) active = models.BooleanField(default=False, verbose_name=_('active')) class Meta: ordering = ('tree_id', 'lft') unique_together = [('parent', 'slug')] verbose_name = _('tree node') verbose_name_plural = _('tree nodes') def __str__(self): return self.name def get_absolute_url(self): path = '/'.join([n.slug for n in self.get_ancestors()]+[self.slug]) return reverse('Catalog:catalog', args=(path,)) def get_edit_url(self): return reverse('admin:{}_{}_change'.format(self._meta.app_label, self._meta.model_name), args=(self.id,)) def get_name(self): return self.name def get_page_title(self): return self.page_title or self.name def get_menu_title(self): return self.menu_title or self.name def save(self, *args, **kwargs): errors = self._perform_unique_checks([(Node, ('parent', 'slug'))]) if errors: raise ValidationError(errors) super(Node, self).save(*args, **kwargs) class Category(Node): class Meta: ordering = ('tree_id', 'lft') verbose_name = _('category') verbose_name_plural = _('categories') tagging.register(Category) class Product(Node): date_added = models.DateTimeField(_('date added'), auto_now_add=True) last_modified = models.DateTimeField(_('last modified'), auto_now=True) multiple = models.IntegerField(_('multiple'), default=1, null=False) unit = models.CharField(_('unit'), max_length=30, blank=True, null=True) price = PriceField(_('price')) tax_rate = TaxRateField(_('tax rate')) related = models.ManyToManyField('self', _('related products'), blank=True) voucher_exclude = models.BooleanField(_('excluded from vouchers'), default=False) class Meta: ordering = ('tree_id', 'lft') verbose_name = _('product') verbose_name_plural = _('products') @property def unit_price(self): return self.price / self.multiple def get_price(self): return Price(self.price, self.tax_rate) get_price.short_description = _('price') @cached_property def all_packages(self): return list(self.packages.all()) tagging.register(Product) @python_2_unicode_compatible class ProductPackage(models.Model): product = models.ForeignKey(Product, verbose_name=_('product'), related_name='packages') multiple = models.IntegerField(_('multiple')) name = models.CharField(_('name'), max_length=250, blank=True, null=True) price = PriceField(_('price'), blank=True, null=True) relative_discount = models.DecimalField(_('relative discount'), decimal_places=4, max_digits=8, blank=True, null=True) nominal_discount = PriceField(_('nominal discount'), blank=True, null=True) class Meta: ordering = ('multiple',) verbose_name = _('product package') verbose_name_plural = _('product packages') def get_price(self): if self.price: return Price(self.price, self.product.tax_rate) else: price = self.product.unit_price * self.multiple if self.relative_discount: price -= (price * self.relative_discount / 100) if self.nominal_discount: price -= self.nominal_discount return Price(price, self.product.tax_rate) get_price.short_description = _('price') def get_name(self): return self.name or '{} {}'.format( self.multiple, self.product.unit, ) get_name.short_description = _('name') def __str__(self): return '{}, {}'.format(self.get_name(), self.get_price()) @python_2_unicode_compatible class Cart(models.Model): last_updated = models.DateTimeField(_('last updated'), auto_now=True) class Meta: verbose_name = _('cart') verbose_name_plural = _('carts') def __str__(self): return ', '.join(map(smart_text, self.all_items)) def get_absolute_url(self): return reverse('Cart:cart') @cached_property def all_items(self): return list(self.items.order_by('product__name', 'package__multiple')) def get_price(self): if len(self.all_items): return sum(item.get_price() for item in self.all_items) else: return Price(0) get_price.short_description = _('price') @python_2_unicode_compatible class CartItem(models.Model): cart = models.ForeignKey(Cart, verbose_name=_('cart'), related_name='items') product = models.ForeignKey(Product, verbose_name=_('product'), related_name='+') package = models.ForeignKey(ProductPackage, verbose_name=_('product package'), related_name='+', blank=False, null=True) quantity = models.PositiveIntegerField(_('quantity'), default=1) price = PriceField(_('price')) tax_rate = TaxRateField(_('tax rate')) class Meta: unique_together = [('cart', 'product', 'package')] verbose_name = _('cart item') verbose_name_plural = _('cart items') def __str__(self): return '{}x {}{}'.format(self.quantity, self.product, self.package and ' {}'.format(self.package) or '') def get_unit_price(self): return Price(self.price, self.tax_rate) get_unit_price.short_description = _('unit price') def get_price(self): return Price(self.price * self.quantity, self.tax_rate) get_price.short_description = _('price') def save(self): if self.quantity: super(CartItem, self).save() elif self.id: super(CartItem, self).delete() @python_2_unicode_compatible class Method(models.Model): code = models.SlugField(_('code')) name = models.CharField(_('name'), max_length=150) description = HTMLField(_('description'), blank=True, default='') price = PriceField(_('price')) tax_rate = TaxRateField(_('tax rate')) ordering = models.PositiveIntegerField(_('ordering'), default=1) class Meta: abstract = True def __str__(self): return '{}, {}'.format(self.name, self.get_price()) def get_price(self): return Price(self.price, self.tax_rate) class DeliveryMethod(Method): class Meta: ordering = ('ordering', 'name') verbose_name = _('delivery method') verbose_name_plural = _('delivery methods') class PaymentMethod(Method): class Meta: ordering = ('ordering', 'name') verbose_name = _('payment method') verbose_name_plural = _('payment methods') @python_2_unicode_compatible class Voucher(models.Model): name = models.CharField(_('name'), max_length=250) slug = models.SlugField(_('slug'), max_length=250, db_index=True, unique=False) summary = HTMLField(_('summary'), blank=True, default='') photo = FilerImageField(verbose_name='Fotka', null=True, blank=True, on_delete=models.SET_NULL) valid_from = models.DateTimeField(_('valid_from')) valid_to = models.DateTimeField(_('valid_to')) relative_discount = models.DecimalField(_('relative discount'), decimal_places=4, max_digits=8, blank=True, null=True) nominal_discount = PriceField(_('nominal discount'), blank=True, null=True) categories = models.ManyToManyField(Category, _('categories'), blank=True) delivery_methods = models.ManyToManyField(DeliveryMethod, verbose_name=_('delivery methods'), blank=True) payment_methods = models.ManyToManyField(PaymentMethod, verbose_name=_('payment methods'), blank=True) one_time = models.BooleanField(_('one time'), default=False) min_price = PriceField(_('minimal price'), blank=True, null=True) class Meta: verbose_name = _('voucher') verbose_name_plural = _('vouchers') def __str__(self): return self.name @cached_property def all_categories(self): return list(self.categories.all()) @cached_property def all_delivery_methods(self): return list(self.delivery_methods.all()) @cached_property def all_payment_methods(self): return list(self.payment_methods.all()) @python_2_unicode_compatible class OrderState(models.Model): code = models.SlugField(_('code')) name = models.CharField(_('name'), max_length=150) description = HTMLField(_('description'), blank=True, default='') class Meta: verbose_name = _('order state') verbose_name_plural = _('order states') def __str__(self): return self.name @python_2_unicode_compatible class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) slug = models.SlugField(editable=False) date = models.DateTimeField(auto_now_add=True, editable=False) cart = models.OneToOneField(Cart, verbose_name=_('cart'), editable=False) state = models.ForeignKey(OrderState, verbose_name=_('state')) first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30) email = models.EmailField(_('email')) phone = models.CharField(_('phone'), max_length=150, validators=[ RegexValidator(r'^\+?[0-9 ]+$')]) address = models.TextField(_('address')) note = models.TextField(_('note'), blank=True) comment = models.TextField(_('internal comment'), blank=True) delivery_method = models.ForeignKey(DeliveryMethod, verbose_name=_('delivery method')) payment_method = models.ForeignKey(PaymentMethod, verbose_name=_('payment method')) voucher = models.ForeignKey(Voucher, verbose_name=_('voucher'), related_name='orders', blank=True, null=True) class Meta: ordering = ('-date',) verbose_name = _('order') verbose_name_plural = _('orders') def __str__(self): return '{} {} {}'.format(self.date, self.first_name, self.last_name) def get_confirm_url(self): return reverse('Order:confirm', kwargs={'slug':self.slug}) def get_edit_url(self): return reverse('admin:{}_{}_change'.format(self._meta.app_label, self._meta.model_name), args=(self.id,)) def get_absolute_url(self): return self.user \ and reverse('MyOrders:detail', kwargs={'pk':self.pk}) \ or reverse('Order:detail', kwargs={'slug':self.slug}) @cached_property def cart_price(self): return self.cart.get_price() @cached_property def delivery_method_price(self): return self.delivery_method.get_price() @cached_property def payment_method_price(self): return self.payment_method.get_price() @cached_property def voucher_price(self): # check voucher if not self.voucher: return Price(0) # check categories if self.voucher.all_categories: items = [ item for item in self.cart.all_items if ( not item.product.voucher_exclude and any(item.product.is_descendant_of(cat) for cat in self.voucher.all_categories) ) ] if not items: return Price(0) else: items = [ item for item in self.cart.all_items if not item.product.voucher_exclude ] # check minimal price if self.voucher.min_price: items_price = sum(item.get_price() for item in items) if items_price < Price(self.voucher.min_price): return Price(0) # check delivery method if self.voucher.all_delivery_methods and self.delivery_method not in delivery_methods: return Price(0) # check payment method if self.voucher.all_payment_methods and self.payment_method not in payment_methods: return Price(0) # return nominal discount if self.voucher.nominal_discount: return Price(-self.voucher.nominal_discount) # return relative discount return sum(item.get_price() * (self.voucher.relative_discount / -100) for item in items) @cached_property def price(self): return self.cart_price \ + self.delivery_method_price \ + self.payment_method_price \ + self.voucher_price price.short_description = _('price') def send_customer_mail(self): send_mail( _('Order accepted'), get_template('cmsplugin_shop/order_customer_mail.txt').render(Context({ 'site': Site.objects.get_current(), 'order': self, })), settings.SHOP_EMAIL, [self.email], **settings.SEND_MAIL_KWARGS ) def send_manager_mail(self): send_mail( _('New order received'), get_template('cmsplugin_shop/order_manager_mail.txt').render(Context({ 'site': Site.objects.get_current(), 'order': self, })), settings.SHOP_EMAIL, map(lambda m: u'"{}" <{}>'.format(m[0], m[1]), settings.settings.MANAGERS), **settings.SEND_MAIL_KWARGS ) def save(self, *args, **kwargs): if self.slug: super(Order, self).save(*args, **kwargs) else: tries = 10 while True: self.slug = get_rand_hash() try: super(Order, self).save(*args, **kwargs) break except: if tries: tries -= 1 else: raise @python_2_unicode_compatible class ProductPlugin(CMSPlugin): product = models.ForeignKey(Product, verbose_name=_('product')) template = models.CharField(_('template'), max_length=100, choices=settings.PRODUCT_TEMPLATES, default=settings.PRODUCT_TEMPLATES[0][0], help_text=_('the template used to render plugin')) def __str__(self): return self.product.name @cached_property def render_template(self): return 'cmsplugin_shop/product/%s.html' % self.template @python_2_unicode_compatible class CategoryPlugin(CMSPlugin): category = models.ForeignKey(Category, verbose_name=_('category')) template = models.CharField(_('template'), max_length=100, choices=settings.CATEGORY_TEMPLATES, default=settings.CATEGORY_TEMPLATES[0][0], help_text=_('the template used to render plugin')) def __str__(self): return self.category.name @cached_property def render_template(self): return 'cmsplugin_shop/category/%s.html' % self.template <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from django.test import TestCase # Create your tests here. <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import cmsplugin_shop.models import django.db.models.deletion import djangocms_text_ckeditor.fields import filer.fields.image class Migration(migrations.Migration): dependencies = [ ('filer', '0002_auto_20150606_2003'), ('cmsplugin_shop', '0001_initial'), ] operations = [ migrations.CreateModel( name='Voucher', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=250, verbose_name='name')), ('slug', models.SlugField(max_length=250, verbose_name='slug')), ('summary', djangocms_text_ckeditor.fields.HTMLField(default='', verbose_name='summary', blank=True)), ('valid_from', models.DateTimeField(verbose_name='valid_from')), ('valid_to', models.DateTimeField(verbose_name='valid_to')), ('relative_discount', models.DecimalField(null=True, verbose_name='relative discount', max_digits=8, decimal_places=4, blank=True)), ('nominal_discount', cmsplugin_shop.models.PriceField(null=True, verbose_name='nominal discount', max_digits=9, decimal_places=2, blank=True)), ('one_time', models.BooleanField(default=False, verbose_name='one time')), ('min_price', cmsplugin_shop.models.PriceField(null=True, verbose_name='minimal price', max_digits=9, decimal_places=2, blank=True)), ('categories', models.ManyToManyField(db_constraint='categories', to='cmsplugin_shop.Category', blank=True)), ('delivery_methods', models.ManyToManyField(to='cmsplugin_shop.DeliveryMethod', verbose_name='delivery methods', blank=True)), ('payment_methods', models.ManyToManyField(to='cmsplugin_shop.PaymentMethod', verbose_name='payment methods', blank=True)), ('photo', filer.fields.image.FilerImageField(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Fotka', blank=True, to='filer.Image', null=True)), ], options={ 'verbose_name': 'voucher', 'verbose_name_plural': 'vouchers', }, ), migrations.AddField( model_name='product', name='voucher_exclude', field=models.BooleanField(default=False, verbose_name='excluded from vouchers'), ), migrations.AlterField( model_name='order', name='email', field=models.EmailField(max_length=254, verbose_name='email'), ), migrations.AlterField( model_name='productpackage', name='relative_discount', field=models.DecimalField(null=True, verbose_name='relative discount', max_digits=8, decimal_places=4, blank=True), ), migrations.AddField( model_name='order', name='voucher', field=models.ForeignKey(related_name='orders', verbose_name='voucher', blank=True, to='cmsplugin_shop.Voucher', null=True), ), ] <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from django.conf import settings from django.conf.urls import patterns, url from .utils import get_view catalog = patterns('', url(r'^(?P<path>.*)$', get_view('catalog'), name='catalog')) cart = patterns('', url(r'^$', get_view('cart'), name='cart')) my_orders = patterns('', url(r'^$', get_view('my_orders'), name='list'), url(r'^(?P<pk>[^/]+)/$', get_view('my_order_detail'), name='detail'), url(r'^(?P<pk>[^.]+).pdf$', get_view('my_order_pdf'), name='pdf'), ) order = patterns('', url('^$', get_view('order_form'), name='form'), url(r'^(?P<slug>[^/]+)/$', get_view('order_detail'), name='detail'), url(r'^(?P<slug>[^.]+).pdf$', get_view('order_pdf'), name='pdf'), ) <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement import datetime from django.utils import timezone from django.utils.functional import cached_property from . import settings from .models import Cart def cart(self): try: c = Cart.objects.get(id=self.session[settings.SESSION_KEY_CART], order=None) except (KeyError, Cart.DoesNotExist): # delete expired carts Cart.objects.filter( last_updated__lt = timezone.now() - datetime.timedelta(settings.CART_EXPIRY_DAYS), order=None ).delete() # create new one c = Cart() self.session[settings.SESSION_KEY_CART] = c.id return c def save_cart(self): self.cart.save() self.session[settings.SESSION_KEY_CART] = self.cart.id class CartMiddleware(object): def process_request(self, request): type(request).cart = cached_property(cart) type(request).save_cart = save_cart <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from django.contrib import admin from . import models from .utils import get_admin admin.site.register(models.Node, get_admin('Node')) admin.site.register(models.Category, get_admin('Category')) admin.site.register(models.Product, get_admin('Product')) admin.site.register(models.Cart, get_admin('Cart')) admin.site.register(models.DeliveryMethod, get_admin('DeliveryMethod')) admin.site.register(models.PaymentMethod, get_admin('PaymentMethod')) admin.site.register(models.Voucher, get_admin('Voucher')) admin.site.register(models.OrderState, get_admin('OrderState')) admin.site.register(models.Order, get_admin('Order')) <file_sep># -*- coding: utf-8 -*- from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from datetime import date from django import forms from django.forms.models import inlineformset_factory from django.utils.safestring import mark_safe from django.utils.timezone import now from django.utils.translation import ugettext_lazy as _ from tagging.forms import TagField from tagging.utils import edit_string_for_tags from . import models class TaggingFormMixin(forms.ModelForm): tags = TagField(required=False, help_text=_( 'Enter space separated list of single word tags ' \ 'or comma separated list of tags containing spaces. ' \ 'Use doublequotes to enter name containing comma.' )) def __init__(self, *args, **kwargs): super(TaggingFormMixin, self).__init__(*args, **kwargs) self.initial['tags'] = edit_string_for_tags(self.instance.tags.all()) def save(self, commit=True): super(TaggingFormMixin, self).save(commit) self.instance.tags = self.cleaned_data['tags'] return self.instance class CategoryForm(TaggingFormMixin): class Meta: model = models.Category exclude = () class ProductForm(TaggingFormMixin): class Meta: model = models.Product exclude = () class CartItemForm(forms.ModelForm): def __init__(self, product, *args, **kwargs): self.product = product super(CartItemForm, self).__init__(*args, **kwargs) if self.product.all_packages: self.fields['package'].widget.choices = tuple( (package.id, str(package)) for package in self.product.all_packages ) else: del(self.fields['package']) class Meta: model = models.CartItem exclude = ['cart', 'product', 'price', 'tax_rate'] CartForm = inlineformset_factory( parent_model= models.Cart, model = models.CartItem, fields = None, exclude = ['product', 'package', 'price', 'tax_rate'], extra = 0, ) class VoucherField(forms.ModelChoiceField): widget = forms.CharField.widget def __init__(self, *args, **kwargs): queryset = models.Voucher.objects.filter(valid_from__lte=now(), valid_to__gt=now()) super(VoucherField, self).__init__(queryset, *args, **kwargs) def clean(self, slug): try: voucher = self.queryset.get(slug=slug) except models.Voucher.DoesNotExist: return None if voucher.one_time and voucher.orders.count(): return None return voucher class OrderForm(forms.ModelForm): voucher = VoucherField(label=_('Voucher code')) agreement = forms.BooleanField(label=_('I agree with terms and conditions')) class Meta: model = models.Order exclude = ['user', 'state', 'comment', 'voucher'] def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['delivery_method'].empty_label = None self.fields['payment_method'].empty_label = None class OrderConfirmForm(forms.Form): pass <file_sep>{% extends 'cmsplugin_shop/node.html' %} {% load sekizai_tags i18n %} {% block specific_content %} <h1 class="product_name"> {{ product.name }} <small>{{ product.get_price }}{% if product.unit %} / {{ product.multiple }}{{ product.unit }}{% endif %}</small> </h1> <div class="product_description"> {{ product.description | safe }} </div> <form method="post" action="">{% csrf_token %} {{ form.as_p }} <input name="add" type="submit" value="{% trans 'Add to cart' %}" /> <input name="add-and-cart" type="submit" value="{% trans 'Add and show the cart' %}" /> </form> {% endblock %} <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from cms.plugin_pool import plugin_pool from .utils import get_plugin plugin_pool.register_plugin(get_plugin('Product')) plugin_pool.register_plugin(get_plugin('Category')) <file_sep>cmsplugin-shop ============== Extensible Django CMS plugin for E-shop <file_sep>{% load i18n %} <table class="table order-cart"> <tr> <th>{% trans 'Product' %}</th> <th>{% trans 'Unit price' %}</th> <th>{% trans 'Quantity' %}</th> <th>{% trans 'Price' %}</th> </tr> {% for item in cart.all_items %} <tr> <td> <a href="{{ item.product.get_absolute_url }}"> {{ item.product.name }} {% if item.package %}/ {{ item.package.name }}{% endif %} </a> </td> <td class="number">{{ item.get_unit_price }}</td> <td class="number">{{ item.quantity }}</td> <td class="number">{{ item.get_price }}</td> </tr> {% endfor %} <tr> <th colspan="3">{% trans 'Subtotal' %}</th> <th class="number">{{ cart.get_price }}</th> </tr> {% if order %} <tr> <td colspan="3">{{ order.delivery_method.name }}</td> <td class="number">{{ order.delivery_method_price }}</td> </tr> <tr> <td colspan="3">{{ order.payment_method.name }}</td> <td class="number">{{ order.payment_method_price }}</td> </tr> {% if order.voucher %} <tr> <td colspan="3">{{ order.voucher.name }}</td> <td class="number">{{ order.voucher_price }}</td> </tr> {% endif %} <tr> <th colspan="3">{% trans 'Total' %}</th> <th class="number">{{ order.price }}</th> </tr> {% endif %} </table> <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from django.conf import settings from django.contrib import admin from django.contrib.admin.util import get_model_from_relation from django.core.urlresolvers import reverse from django.utils.encoding import smart_text, force_text from django.utils.translation import ugettext_lazy as _ from django_mptt_admin.admin import DjangoMpttAdmin from mptt.models import TreeForeignKey from cms.utils import get_language_from_request from . import models from .utils import get_form, get_admin class CategoryTreeListFilter(admin.FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg_tid = '%s__tree_id' % (field_path) self.lookup_kwarg_lft = '%s__lft__gte' % (field_path) self.lookup_kwarg_rght = '%s__rght__lte' % (field_path) self.lookup_kwarg_isnull = '%s__isnull' % field_path self.lookup_val_tid = request.GET.get(self.lookup_kwarg_tid, None) self.lookup_val_lft = request.GET.get(self.lookup_kwarg_lft, None) self.lookup_val_rght = request.GET.get(self.lookup_kwarg_rght, None) self.lookup_val_isnull = request.GET.get(self.lookup_kwarg_isnull, None) self.lookup_choices = models.Category.objects.order_by('tree_id', 'lft') super(CategoryTreeListFilter, self).__init__( field, request, params, model, model_admin, field_path ) if hasattr(field, 'verbose_name'): self.lookup_title = field.verbose_name else: self.lookup_title = other_model._meta.verbose_name self.title = self.lookup_title def has_output(self): if hasattr(self.field, 'rel') and self.field.null: extra = 1 else: extra = 0 return len(self.lookup_choices) + extra > 1 def expected_parameters(self): return [self.lookup_kwarg_lft, self.lookup_kwarg_rght, self.lookup_kwarg_isnull] def choices(self, cl): from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE yield { 'selected': self.lookup_val_tid is None and self.lookup_val_lft is None and self.lookup_val_rght is None and not self.lookup_val_isnull, 'query_string': cl.get_query_string({}, [ self.lookup_kwarg_tid, self.lookup_kwarg_lft, self.lookup_kwarg_rght, self.lookup_kwarg_isnull, ]), 'display': _('All'), } for val in self.lookup_choices: yield { 'selected': self.lookup_val_lft == val.lft and self.lookup_val_rght == val.rght, 'query_string': cl.get_query_string({ self.lookup_kwarg_tid: val.tree_id, self.lookup_kwarg_lft: val.lft, self.lookup_kwarg_rght: val.rght, }, [self.lookup_kwarg_isnull]), 'display': '{}{}'.format(val.level*'- ', val), } if self.field.null: yield { 'selected': bool(self.lookup_val_isnull), 'query_string': cl.get_query_string({ self.lookup_kwarg_isnull: 'True', }, [ self.lookup_kwarg_tid, self.lookup_kwarg_lft, self.lookup_kwarg_rght, ]), 'display': EMPTY_CHANGELIST_VALUE, } class CategoryAdmin(admin.ModelAdmin): form = get_form('Category') ordering = ['tree_id', 'lft'] list_display = ['name', 'parent', 'active'] list_filter = [('parent', CategoryTreeListFilter)] search_fields = ['name', 'summary', 'description'] prepopulated_fields = {'slug': ('name',)} trigger_save_after_move = True def lookup_allowed(self, key, value): return key in ['parent__lft__gte', 'parent__rght__lte', 'parent__tree_id'] \ and value.isdigit() and True or super(ProductAdmin, self).lookup_allowed(key, value) class ProductPackageInlineAdmin(admin.TabularInline): model = models.ProductPackage extra = 0 class ProductAdmin(admin.ModelAdmin): form = get_form('Product') ordering = ['tree_id', 'lft'] list_display = ['name', 'parent', 'active', 'multiple', 'unit', 'price', 'tax_rate'] list_editable = ['active', 'price', 'tax_rate'] list_filter = ['active', ('parent', CategoryTreeListFilter)] search_fields = ['name', 'summary', 'description'] inlines = [ProductPackageInlineAdmin] filter_horizontal = ['related'] prepopulated_fields = {'slug': ('name',)} def lookup_allowed(self, key, value): return key in ['parent__lft__gte', 'parent__rght__lte', 'parent__tree_id'] \ and value.isdigit() and True or super(ProductAdmin, self).lookup_allowed(key, value) class NodeAdmin(DjangoMpttAdmin): def has_add_permission(self, request): # Nodes must always be added as Product or Category return False class OrderStateAdmin(admin.ModelAdmin): pass class CartItemInlineAdmin(admin.TabularInline): model = models.CartItem extra = 0 class CartAdmin(admin.ModelAdmin): ordering = ['-last_updated'] inlines = [CartItemInlineAdmin] readonly_fields = ['last_updated', 'get_price'] class VoucherAdmin(admin.ModelAdmin): filter_horizontal = ['categories', 'delivery_methods', 'payment_methods'] ordering = ['-valid_from'] prepopulated_fields = {'slug': ('name',)} class OrderAdmin(admin.ModelAdmin): actions = ('send_customer_mail',) readonly_fields = ['slug', 'cart_link'] list_filter = ['state'] list_display = ['id', 'date', 'first_name', 'last_name', 'email', 'phone', 'address', 'delivery_method', 'payment_method', 'state', 'price', 'cart_link'] list_editable = ['state'] search_fields = ['first_name', 'last_name', 'email', 'phone', 'address'] def cart_link(self, order): return '<a href="{}">{}</a>'.format( reverse('admin:cmsplugin_shop_cart_change', args=(order.cart_id,)), order.cart, ) cart_link.short_description = _('cart') cart_link.allow_tags = True def send_customer_mail(self, request, queryset): for order in queryset.all(): try: order.send_customer_mail() except Exception as e: self.message_user(request, _('Failed to send notification e-mail to {}').format(order.email) ) send_customer_mail.short_description = _('Resend notification e-mail to the customer') class DeliveryMethodAdmin(admin.ModelAdmin): pass class PaymentMethodAdmin(admin.ModelAdmin): pass <file_sep># -*- coding: utf-8 -*- from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from cms.menu_bases import CMSAttachMenu from django.db.models.signals import post_delete, post_save from django.utils.translation import ugettext_lazy as _ from menus.base import NavigationNode from menus.menu_pool import menu_pool from .models import Node, Category class CatalogMenu(CMSAttachMenu): name = _('Catalog') def get_nodes(self, request): """ This method is used to build the menu tree. """ if request.toolbar.use_draft: qs = Node.objects.order_by('tree_id', 'lft') else: qs = Node.objects.filter(active=True).order_by('tree_id', 'lft') return [ NavigationNode( node.get_menu_title(), node.get_absolute_url(), node.id, node.parent and node.parent.id or None, ) for node in qs ] menu_pool.register_menu(CatalogMenu) def invalidate_menu_cache(sender, **kwargs): menu_pool.clear() post_save.connect(invalidate_menu_cache, sender=Category) post_delete.connect(invalidate_menu_cache, sender=Category) <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement import locale import os import string from decimal import Decimal from django.db.models import Model from django.utils.encoding import smart_text from django.utils.translation import get_language from . import settings try: from django.utils.module_loading import import_string except ImportError: from django.utils.module_loading import import_by_path as import_string class EmptyMixin(Model): class Meta: abstract = True def get_admin(name): return import_string(getattr(settings.settings, 'CMSPLUGIN_SHOP_{}_ADMIN'.format(name.upper()), 'cmsplugin_shop.admins.{}Admin'.format(name), )) def get_form(name): return import_string(getattr(settings.settings, 'CMSPLUGIN_SHOP_{}_FORM'.format(name.upper()), 'cmsplugin_shop.forms.{}Form'.format(name), )) def get_html_field(): return import_string(getattr(settings.settings, 'CMSPLUGIN_SHOP_HTML_FIELD', 'djangocms_text_ckeditor.fields.HTMLField', )) def get_plugin(name): return import_string(getattr(settings.settings, 'CMSPLUGIN_SHOP_{}_PLUGIN'.format(name.upper()), 'cmsplugin_shop.plugins.{}Plugin'.format(name), )) def get_toolbar(name): return import_string(getattr(settings.settings, 'CMSPLUGIN_SHOP_{}_TOOLBAR'.format(name.upper()), 'cmsplugin_shop.cms_toolbars.{}Toolbar'.format(name), )) def get_view(name): view = import_string(getattr( settings.settings, 'CMSPLUGIN_SHOP_{}_VIEW'.format(name.upper()), 'cmsplugin_shop.views.{}'.format(name), )) return hasattr(view, 'as_view') and view.as_view() or view QUANTIZE = Decimal((0,(1,),-settings.DECIMAL_PLACES)) def quantize(price): return price.quantize(QUANTIZE) class LocaleConvCache(object): def __init__(self, languages): """ This function loads localeconv for all languages during module load. It is necessary, because using locale.setlocale later may be dangerous (It is not thread-safe in most of the implementations.) """ self._conv = {} original_locale_name = locale.setlocale(locale.LC_ALL) for code, name in languages: locale_name = locale.locale_alias[code].split('.')[0]+'.UTF-8' locale.setlocale(locale.LC_ALL, str(locale_name)) self._conv[code] = locale.localeconv() locale.setlocale(locale.LC_ALL, original_locale_name) def getconv(self, language=None): return self._conv[language or get_language()].copy() localeconv_cache = LocaleConvCache(settings.settings.LANGUAGES) # This function is inspired by python's standard locale.currency(). def currency(val, localeconv=None, international=False): """Formats val according to the currency settings for current language.""" val = Decimal(val) conv = localeconv_cache.getconv() conv.update(localeconv or settings.LOCALECONV) # split integer part and fraction parts = str(abs(val)).split('.') # grouping groups = [] s = parts[0] for interval in locale._grouping_intervals(conv['mon_grouping']): if not s: break groups.append(s[-interval:]) s = s[:-interval] if s: groups.append(s) groups.reverse() s = smart_text(conv['mon_thousands_sep']).join(groups) # display fraction for non integer values if len(parts) > 1: s += smart_text(conv['mon_decimal_point']) + parts[1] # '<' and '>' are markers if the sign must be inserted between symbol and value s = '<' + s + '>' smb = smart_text(conv[international and 'int_curr_symbol' or 'currency_symbol']) precedes = conv[val<0 and 'n_cs_precedes' or 'p_cs_precedes'] separated = conv[val<0 and 'n_sep_by_space' or 'p_sep_by_space'] if precedes: s = smb + (separated and ' ' or '') + s else: s = s + (separated and ' ' or '') + smb sign_pos = conv[val<0 and 'n_sign_posn' or 'p_sign_posn'] sign = conv[val<0 and 'negative_sign' or 'positive_sign'] if sign_pos == 0: s = '(' + s + ')' elif sign_pos == 1: s = sign + s elif sign_pos == 2: s = s + sign elif sign_pos == 3: s = s.replace('<', sign) elif sign_pos == 4: s = s.replace('>', sign) else: # the default if nothing specified; # this should be the most fitting sign position s = sign + s return s.replace('<', '').replace('>', '') def get_rand_hash(length=32, stringset=string.ascii_letters+string.digits): return ''.join([stringset[i%len(stringset)] for i in [ord(x) for x in os.urandom(length)]]) <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from cms.toolbar_pool import toolbar_pool from .utils import get_toolbar toolbar_pool.register(get_toolbar('Shop')) <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from django import template from ..utils import currency as _currency register = template.Library() @register.filter def currency(value): try: return _currency(value) except ValueError: return '' <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement import cStringIO from cms.views import details as cms_page from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django.forms import ModelForm from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from django.views.generic import ( CreateView, DetailView, FormView, ListView, TemplateView, UpdateView, View, ) from formtools.wizard.views import SessionWizardView from os.path import basename from xhtml2pdf import pisa from . import models, settings from .utils import get_view, get_form class PdfViewMixin(object): """ A base view for displaying a Pdf """ def get_attachment_filename(self): if hasattr(self, 'attachment_filename'): return self.attachment_filename filename = basename(self.request.path) return filename.endswith('.pdf') and filename or '{}.pdf'.format(filename) def get(self, request, *args, **kwargs): content = super(PdfViewMixin, self).get(request, *args, **kwargs).render().content result = cStringIO.StringIO() pdf = pisa.CreatePDF(cStringIO.StringIO(content), result, encoding='UTF-8') if pdf.err: raise Exception(pdf.err) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{}"'.format(self.get_attachment_filename()) response.write(result.getvalue()) result.close() return response class ProductView(FormView): form_class = get_form('CartItem') def get_context_data(self, **kwargs): self.kwargs.update(kwargs) return self.kwargs def get_form_kwargs(self): kwargs = super(ProductView, self).get_form_kwargs() kwargs['product'] = self.kwargs['product'] return kwargs def form_valid(self, form): self.request.save_cart() form.instance.cart = self.request.cart form.instance.product = self.kwargs['product'] try: item = form.instance.__class__.objects.get( cart = form.instance.cart, product = form.instance.product, package = form.instance.package, ) item.quantity += form.instance.quantity item.save() except form.instance.__class__.DoesNotExist: form.instance.tax_rate = form.instance.product.tax_rate form.instance.price = form.instance.package \ and form.instance.package.price \ or form.instance.product.price form.instance.save() messages.add_message(self.request, messages.INFO, mark_safe(_('Product has been added to <a href="{}">shopping cart</a>').format(reverse('Cart:cart'))) ) return super(ProductView, self).form_valid(form) def get_success_url(self): if 'add-and-cart' in self.request.POST: return reverse('Cart:cart') else: return self.kwargs['product'].get_absolute_url() # catalog views root = TemplateView.as_view(template_name='cmsplugin_shop/root.html') category = TemplateView.as_view(template_name='cmsplugin_shop/category.html') product = ProductView.as_view(template_name='cmsplugin_shop/product.html') class CatalogView(View): root_view = staticmethod(get_view('root')) category_view = staticmethod(get_view('category')) product_view = staticmethod(get_view('product')) category_model = models.Category product_model = models.Product def dispatch(self, request, path): slug_list = [slug for slug in path.split('/') if slug] # do not allow disabled nodes if user is not staff if request.toolbar.use_draft: active = {} else: active = {'active':True} # display root view, if the path is empty if not slug_list: return self.root_view(request, categories = self.category_model.objects.filter(parent=None, **active), products = self.product_model.objects.filter(parent=None, **active), ) # handle cms subpages if request.current_page.application_namespace != 'Catalog': return cms_page(request, path) # lookup node by path node = None for slug in slug_list: node = get_object_or_404(models.Node, parent=node, slug=slug, **active) # display product view try: product = node.product return self.product_view(request, node = product, product = product, ) except self.product_model.DoesNotExist: # or category view category = node.category return self.category_view(request, node = category, category = category, categories = self.category_model.objects.filter(parent=node, **active), products = self.product_model.objects.filter(parent=node, **active), ) catalog = CatalogView.as_view() class CartView(UpdateView): form_class = get_form('Cart') model = models.Cart template_name = 'cmsplugin_shop/cart.html' def get_object(self, queryset=None): return self.request.cart def form_valid(self, form): self.request.save_cart() return super(CartView, self).form_valid(form) def get_success_url(self): if 'update-and-order' in self.request.POST: return reverse('Order:form') else: return reverse('Cart:cart') cart = CartView.as_view() class OrderFormView(SessionWizardView): template_name = 'cmsplugin_shop/order_form.html' form_list = [ get_form('Order'), get_form('OrderConfirm') ] def get_form_initial(self, step): initial = {} if step == '0' and self.request.user.is_authenticated(): for attr in 'first_name', 'last_name', 'email': if hasattr(self.request.user, attr): initial[attr] = getattr(self.request.user, attr) if hasattr(self.request.user, settings.PROFILE_ATTRIBUTE): profile = getattr(self.request.user, settings.PROFILE_ATTRIBUTE) for attr in 'phone', 'address': if hasattr(profile, attr): initial[attr] = getattr(profile, attr) return initial def get_order(self): # create order using data from first form order = models.Order() for attr, value in self.get_cleaned_data_for_step('0').items(): setattr(order, attr, value) # find get initial order_state try: state = models.OrderState.objects.get(code=settings.INITIAL_ORDER_STATE) except models.OrderState.DoesNotExist: state = models.OrderState(code=settings.INITIAL_ORDER_STATE, name='New') state.save() # set order.state and cart self.request.save_cart() order.cart = self.request.cart order.state = state if self.request.user.is_authenticated(): order.user = self.request.user return order def get_context_data(self, form, **kwargs): context = super(OrderFormView, self).get_context_data(form=form, **kwargs) if self.steps.current == '1': context.update({'order': self.get_order()}) return context def done(self, form_list, **kwargs): # get order order = self.get_order() # save order order.save() # send notifications order.send_customer_mail() order.send_manager_mail() messages.add_message(self.request, messages.INFO, mark_safe(_( 'Your order has been accepted. The confirmation email has been sent to {}.' ).format(order.email))) # redirect to order detail return HttpResponseRedirect(order.get_absolute_url()) order_form = OrderFormView.as_view() class OrderDetailView(DetailView): model = models.Order def get_queryset(self): return super(OrderDetailView, self).get_queryset().filter(user = None) class MyOrderDetailView(DetailView): model = models.Order def get_queryset(self): return super(MyOrderDetailView, self).get_queryset().filter(user = self.request.user) class OrderPdfView(PdfViewMixin, OrderDetailView): template_name_suffix = '_pdf' class MyOrderPdfView(PdfViewMixin, MyOrderDetailView): template_name_suffix = '_pdf' order_detail = OrderDetailView.as_view() order_pdf = OrderPdfView.as_view() my_order_detail = login_required(MyOrderDetailView.as_view()) my_order_pdf = login_required(MyOrderPdfView.as_view()) class MyOrdersView(ListView): model = models.Order def get_queryset(self): user = self.request.user return self.model._default_manager.filter(user=user) def get_context_data(self): context = super(MyOrdersView, self).get_context_data() context['orders'] = context['object_list'] return context my_orders = login_required(MyOrdersView.as_view()) <file_sep>from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from cms.toolbar_base import CMSToolbar from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from .models import Category, Product class ShopToolbar(CMSToolbar): def populate(self): admin_menu = self.toolbar.get_or_create_menu('shop_menu', _('Shop')) admin_menu.add_modal_item(_('Add product'), url=reverse('admin:{}_{}_add'.format(Product._meta.app_label, Product._meta.model_name))) admin_menu.add_modal_item(_('Add category'), url=reverse('admin:{}_{}_add'.format(Category._meta.app_label, Category._meta.model_name))) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import cmsplugin_shop.models import mptt.fields import djangocms_text_ckeditor.fields import django.db.models.deletion from django.conf import settings import django.core.validators import filer.fields.image class Migration(migrations.Migration): dependencies = [ ('filer', '0001_initial'), ('cms', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Cart', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('last_updated', models.DateTimeField(auto_now=True, verbose_name='last updated')), ], options={ 'verbose_name': 'cart', 'verbose_name_plural': 'carts', }, bases=(models.Model,), ), migrations.CreateModel( name='CartItem', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('quantity', models.PositiveIntegerField(default=1, verbose_name='quantity')), ('price', cmsplugin_shop.models.PriceField(verbose_name='price', max_digits=9, decimal_places=2)), ('tax_rate', cmsplugin_shop.models.TaxRateField(default=0, verbose_name='tax rate', max_digits=9, decimal_places=4, choices=[(0, 'no tax')])), ('cart', models.ForeignKey(related_name='items', verbose_name='cart', to='cmsplugin_shop.Cart')), ], options={ 'verbose_name': 'cart item', 'verbose_name_plural': 'cart items', }, bases=(models.Model,), ), migrations.CreateModel( name='CategoryPlugin', fields=[ ('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin')), ('template', models.CharField(default='default', help_text='the template used to render plugin', max_length=100, verbose_name='template', choices=[('default', 'default')])), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), migrations.CreateModel( name='DeliveryMethod', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.SlugField(verbose_name='code')), ('name', models.CharField(max_length=150, verbose_name='name')), ('description', djangocms_text_ckeditor.fields.HTMLField(default='', verbose_name='description', blank=True)), ('price', cmsplugin_shop.models.PriceField(verbose_name='price', max_digits=9, decimal_places=2)), ('tax_rate', cmsplugin_shop.models.TaxRateField(default=0, verbose_name='tax rate', max_digits=9, decimal_places=4, choices=[(0, 'no tax')])), ('ordering', models.PositiveIntegerField(default=1, verbose_name='ordering')), ], options={ 'ordering': ('ordering', 'name'), 'verbose_name': 'delivery method', 'verbose_name_plural': 'delivery methods', }, bases=(models.Model,), ), migrations.CreateModel( name='Node', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=250, verbose_name='name')), ('slug', models.SlugField(max_length=250, verbose_name='slug')), ('summary', djangocms_text_ckeditor.fields.HTMLField(default='', verbose_name='summary', blank=True)), ('description', djangocms_text_ckeditor.fields.HTMLField(default='', verbose_name='description', blank=True)), ('page_title', models.CharField(help_text='overwrite the title (html title tag)', max_length=250, null=True, verbose_name='page title', blank=True)), ('menu_title', models.CharField(help_text='overwrite the title in the menu', max_length=250, null=True, verbose_name='menu title', blank=True)), ('meta_desc', models.TextField(default='', help_text='the text displayed in search engines', verbose_name='meta description', blank=True)), ('active', models.BooleanField(default=False, verbose_name='active')), ('lft', models.PositiveIntegerField(editable=False, db_index=True)), ('rght', models.PositiveIntegerField(editable=False, db_index=True)), ('tree_id', models.PositiveIntegerField(editable=False, db_index=True)), ('level', models.PositiveIntegerField(editable=False, db_index=True)), ], options={ 'ordering': ('tree_id', 'lft'), 'verbose_name': 'tree node', 'verbose_name_plural': 'tree nodes', }, bases=(models.Model,), ), migrations.CreateModel( name='Category', fields=[ ('node_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cmsplugin_shop.Node')), ], options={ 'ordering': ('tree_id', 'lft'), 'verbose_name': 'category', 'verbose_name_plural': 'categories', }, bases=('cmsplugin_shop.node',), ), migrations.CreateModel( name='Order', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('slug', models.SlugField(editable=False)), ('date', models.DateTimeField(auto_now_add=True)), ('first_name', models.CharField(max_length=30, verbose_name='first name')), ('last_name', models.CharField(max_length=30, verbose_name='last name')), ('email', models.EmailField(max_length=75, verbose_name='email')), ('phone', models.CharField(max_length=150, verbose_name='phone', validators=[django.core.validators.RegexValidator('^\\+?[0-9 ]+$')])), ('address', models.TextField(verbose_name='address')), ('note', models.TextField(verbose_name='note', blank=True)), ('comment', models.TextField(verbose_name='internal comment', blank=True)), ('cart', models.OneToOneField(editable=False, to='cmsplugin_shop.Cart', verbose_name='cart')), ('delivery_method', models.ForeignKey(verbose_name='delivery method', to='cmsplugin_shop.DeliveryMethod')), ], options={ 'ordering': ('-date',), 'verbose_name': 'order', 'verbose_name_plural': 'orders', }, bases=(models.Model,), ), migrations.CreateModel( name='OrderState', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.SlugField(verbose_name='code')), ('name', models.CharField(max_length=150, verbose_name='name')), ('description', djangocms_text_ckeditor.fields.HTMLField(default='', verbose_name='description', blank=True)), ], options={ 'verbose_name': 'order state', 'verbose_name_plural': 'order states', }, bases=(models.Model,), ), migrations.CreateModel( name='PaymentMethod', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.SlugField(verbose_name='code')), ('name', models.CharField(max_length=150, verbose_name='name')), ('description', djangocms_text_ckeditor.fields.HTMLField(default='', verbose_name='description', blank=True)), ('price', cmsplugin_shop.models.PriceField(verbose_name='price', max_digits=9, decimal_places=2)), ('tax_rate', cmsplugin_shop.models.TaxRateField(default=0, verbose_name='tax rate', max_digits=9, decimal_places=4, choices=[(0, 'no tax')])), ('ordering', models.PositiveIntegerField(default=1, verbose_name='ordering')), ], options={ 'ordering': ('ordering', 'name'), 'verbose_name': 'payment method', 'verbose_name_plural': 'payment methods', }, bases=(models.Model,), ), migrations.CreateModel( name='Product', fields=[ ('node_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cmsplugin_shop.Node')), ('date_added', models.DateTimeField(auto_now_add=True, verbose_name='date added')), ('last_modified', models.DateTimeField(auto_now=True, verbose_name='last modified')), ('multiple', models.IntegerField(default=1, verbose_name='multiple')), ('unit', models.CharField(max_length=30, null=True, verbose_name='unit', blank=True)), ('price', cmsplugin_shop.models.PriceField(verbose_name='price', max_digits=9, decimal_places=2)), ('tax_rate', cmsplugin_shop.models.TaxRateField(default=0, verbose_name='tax rate', max_digits=9, decimal_places=4, choices=[(0, 'no tax')])), ('related', models.ManyToManyField(related_name='related_rel_+', db_constraint='related products', to='cmsplugin_shop.Product', blank=True)), ], options={ 'ordering': ('tree_id', 'lft'), 'verbose_name': 'product', 'verbose_name_plural': 'products', }, bases=('cmsplugin_shop.node',), ), migrations.CreateModel( name='ProductPackage', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('multiple', models.IntegerField(verbose_name='multiple')), ('name', models.CharField(max_length=250, null=True, verbose_name='name', blank=True)), ('price', cmsplugin_shop.models.PriceField(null=True, verbose_name='price', max_digits=9, decimal_places=2, blank=True)), ('relative_discount', models.DecimalField(decimal_places=4, default=1, max_digits=8, blank=True, null=True, verbose_name='relative discount')), ('nominal_discount', cmsplugin_shop.models.PriceField(null=True, verbose_name='nominal discount', max_digits=9, decimal_places=2, blank=True)), ('product', models.ForeignKey(related_name='packages', verbose_name='product', to='cmsplugin_shop.Product')), ], options={ 'ordering': ('multiple',), 'verbose_name': 'product package', 'verbose_name_plural': 'product packages', }, bases=(models.Model,), ), migrations.CreateModel( name='ProductPlugin', fields=[ ('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin')), ('template', models.CharField(default='default', help_text='the template used to render plugin', max_length=100, verbose_name='template', choices=[('default', 'default')])), ('product', models.ForeignKey(verbose_name='product', to='cmsplugin_shop.Product')), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), migrations.AddField( model_name='order', name='payment_method', field=models.ForeignKey(verbose_name='payment method', to='cmsplugin_shop.PaymentMethod'), preserve_default=True, ), migrations.AddField( model_name='order', name='state', field=models.ForeignKey(verbose_name='state', to='cmsplugin_shop.OrderState'), preserve_default=True, ), migrations.AddField( model_name='order', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, blank=True, to=settings.AUTH_USER_MODEL, null=True), preserve_default=True, ), migrations.AddField( model_name='node', name='parent', field=mptt.fields.TreeForeignKey(related_name='children', verbose_name='category', blank=True, to='cmsplugin_shop.Node', null=True), preserve_default=True, ), migrations.AddField( model_name='node', name='photo', field=filer.fields.image.FilerImageField(on_delete=django.db.models.deletion.SET_NULL, verbose_name='Fotka', blank=True, to='filer.Image', null=True), preserve_default=True, ), migrations.AlterUniqueTogether( name='node', unique_together=set([('parent', 'slug')]), ), migrations.AddField( model_name='categoryplugin', name='category', field=models.ForeignKey(verbose_name='category', to='cmsplugin_shop.Category'), preserve_default=True, ), migrations.AddField( model_name='cartitem', name='package', field=models.ForeignKey(related_name='+', verbose_name='product package', to='cmsplugin_shop.ProductPackage', null=True), preserve_default=True, ), migrations.AddField( model_name='cartitem', name='product', field=models.ForeignKey(related_name='+', verbose_name='product', to='cmsplugin_shop.Product'), preserve_default=True, ), migrations.AlterUniqueTogether( name='cartitem', unique_together=set([('cart', 'product', 'package')]), ), ] <file_sep># -*- coding: utf-8 -*- from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement from django.utils.translation import ugettext_lazy as _ from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from .urls import catalog, cart, order, my_orders @apphook_pool.register class CatalogApp(CMSApp): name = _('Catalog') urls = [catalog] app_name = 'Catalog' @apphook_pool.register class CartApp(CMSApp): name = _('Cart') urls = [cart] app_name = 'Cart' @apphook_pool.register class OrderApp(CMSApp): name = _('Order') urls = [order] app_name = 'Order' @apphook_pool.register class MyOrdersApp(CMSApp): name = _('My orders') urls = [my_orders] app_name = 'MyOrders'
f814d984ccd2deee8e44ff077bceb9ebd9ad3bfd
[ "Markdown", "Python", "HTML" ]
25
Python
misli/cmsplugin-shop
6da14052f25aa04a4f9a6d42a7fd8b9fd90ea5e0
6aff196503dbaefdf4345abbfd3ab42e19e52c16
refs/heads/master
<repo_name>rakshithrm17/C-programs<file_sep>/matrix addition.c #include<stdio.h> #include<conio.h> void main() { int c,d,m,n,first[25][25],second[25]25],sum[25][25]; clrscr(); printf("\nenter the number of rows and coloumn:\n"); scanf("%d %d",&m,&n); printf("\nenter the elements of first matrix:\n"); for(c=0;c<m;c++) for(d=0;d<n;d++) scanf("%d",&second[c][d]); printf("\nenter the elements of second matrix:\n"); for(c=0;c<m;c++) for(d=0;d<n;d++) scanf("%d",&second[c][d]); printf("\n the sum of entered matrices is:\n"); for(c=0;c<m;c++) { for(d=0;d<n;d++) { sum[c][d]=first[c][d]+second[c][d]); } printf("\n"); } getch(); } <file_sep>/README.md # C-programs All the c pgm <file_sep>/roots of the quadratic equation using if else statement.c #include<stdio.h> #include<math.h> #include<conio.h> void main() { float x1,x2,a,b,c,disc; clrscr(); printf("enter the coordinates a b c\n"); scanf("%f%f%f",&a,&b,&c); disc=b*b-4*a*c; if(disc==0) { x1=x2=b/(2*a); printf("the roots are equal\n"); printf("the roots are x1=%.2lf\nx2=%.2lf\n",x1,x2); } if(disc>0) { x1=(-b+sqrt(disc))/(2*a); x2=(-b-sqrt(disc))/(2*a); printf("the roots are distinct\n"); printf("the roots are x1=%.2lf\nx2=%.2fl\n",x1,x2); } if(disc>0) { x1=b/(2*a); x2=sqrt(fabs(disc))/(2*a); printf("the roots are complex\n"); printf("the roots are x1=%.2lf+i%.2lf\n",x1,x2"); printf("the roots are x2=%.2lf-i%.2lfn",x1,x2); } getch(); } <file_sep>/biggest.c #include<stdio.h> #include<conio.h> void main() { int a,b,c; printf("enter the number of elements\n"); scanf("%d%d%d",&a,&b,&c); if(a>b) { if(a>c) printf("\na is maximum"); else printf("\nc is maximum"); } else { if(b>c) printf("\nb is maximum"); else printf("\nc is maximum"); } getch(); } <file_sep>/numbers using insertion.c #include<stdio.h> #include<conio.h> void main() { int i,j,n,temp,a[30]; clrscr(); printf("enter thr numbers of elements:"); scanf("%d",&n); printf("\nenter the elements \n"); for i=0;i<n;i++ { scanf("%d",&a[i]); } for(i=0;i<=n-1;i++) { temp=a[i]; j=i-1; } a[j+1]=temp; } printf("\n sorted list is as follows\n"); for(i=0;i<n;i++) { printf("%d\n",a[i]); } getch(); }
351bee806f457a48869a22c51c0b1d56c5fe60b3
[ "Markdown", "C" ]
5
C
rakshithrm17/C-programs
7ea539409b6ec28e95350f589db87e182afd7dd5
d4ec73b93a2f9815e8e94d9a5e93a191f99887ad
refs/heads/master
<file_sep>package pl.com.sebastianbodzak.library.api; import pl.com.sebastianbodzak.library.domain.EmailMessage; /** * Created by Dell on 2016-10-13. */ public interface EmailFacade { void sendEmail(EmailMessage content, String email); } <file_sep>package library.infrastucture; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; import pl.com.sebastianbodzak.library.domain.EmployeeRepository; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Created by Dell on 2016-10-12. */ @RunWith(SpringRunner.class) @ContextConfiguration("/application.xml") @TestPropertySource({"/jdbc-test.properties", "/hibernate-test.properties"}) @WebAppConfiguration @Sql("/fixtures/employees.sql") public class JpaEmployeeRepositoryTest { private String occupiedLogin = "login"; private String freeLogin = "freeLogin"; @Autowired private EmployeeRepository employeeRepository; @Sql("/fixtures/employees.sql") @Test @Transactional public void shouldConfirmThatLoginIsOccupied() { boolean result = employeeRepository.isLoginOccupied(occupiedLogin); assertTrue(result); } @Sql("/fixtures/employees.sql") @Test @Transactional public void shouldConfirmedThatLoginIsAvaliable() { boolean result = employeeRepository.isLoginOccupied(freeLogin); assertFalse(result); } } <file_sep>package pl.com.sebastianbodzak.library.api.requests; /** * Created by Dell on 2016-10-20. */ public class ChangeEmailMessageRequest { } <file_sep>package pl.com.sebastianbodzak.library.infrastucture; import org.springframework.stereotype.Repository; import pl.com.sebastianbodzak.library.domain.Book; import pl.com.sebastianbodzak.library.domain.BookRepository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * Created by Dell on 2016-10-24. */ @Repository public class JpaBookRepository implements BookRepository { @PersistenceContext private EntityManager entityManager; @Override public void save(Book book) { entityManager.persist(book); } } <file_sep>package pl.com.sebastianbodzak.library.domain; import javax.persistence.*; /** * Created by Dell on 2016-10-11. */ @Entity public class User { @EmbeddedId private Account accountNumber; @OneToOne private PersonalData data; @Enumerated(EnumType.STRING) private UserStatus userStatus; private User() {} public User(Account accountNumber, PersonalData data, UserStatus userStatus) { this.accountNumber = accountNumber; this.data = data; this.userStatus = userStatus; } public PersonalData getData() { return data; } public UserStatus getUserStatus() { return userStatus; } public Account getAccountNumber() { return accountNumber; } } <file_sep>package pl.com.sebastianbodzak.library.api.dtos; import pl.com.sebastianbodzak.library.api.InvalidRequestException; /** * Created by Dell on 2016-10-12. */ public class AddressDto { private String city; private String street; private String postalCode; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public void validate() { if (city == null || street == null || postalCode == null) throw new InvalidRequestException("Address required city, street and postal code"); } } <file_sep>package pl.com.sebastianbodzak.library.api; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pl.com.sebastianbodzak.library.domain.EmailMessage; import pl.com.sebastianbodzak.library.domain.EmailMessageRepository; /** * Created by Dell on 2016-10-13. */ @Service public class EmailSender { private EmailFacade emailFacade; private EmailMessageRepository emailMessageRepository; public EmailSender(EmailFacade emailFacade, EmailMessageRepository emailMessageRepository) { this.emailFacade = emailFacade; this.emailMessageRepository = emailMessageRepository; } @Transactional public void sendEmail(String email, String typeOfMessage) { EmailMessage message = emailMessageRepository.loadMessageById(typeOfMessage); emailFacade.sendEmail(message, email); } } <file_sep>package pl.com.sebastianbodzak.library.api.dtos; /** * Created by Dell on 2016-10-11. */ public class SignupResultDto { private boolean success; private String failureReason; public SignupResultDto() { this.success = true; } public SignupResultDto(String failureReason) { this.failureReason = failureReason; this.success = false; } public boolean isSuccess() { return success; } public String getFailureReason() { return failureReason; } } <file_sep>INSERT INTO EMPLOYEE VALUES (1, 'hashedPassword', '<PASSWORD>', 'login', null, null, null); INSERT INTO EMPLOYEE VALUES (2, 'hashedPassword', '<PASSWORD>', 'login2', null, null, null); INSERT INTO EMPLOYEE VALUES (3, 'hashedPassword', '<PASSWORD>', 'login3', null, null, null);<file_sep>package pl.com.sebastianbodzak.library.api.responses; /** * Created by Dell on 2016-10-12. */ public class CreateEmployeeResponse { public String id; public CreateEmployeeResponse(Long id) { this.id = id.toString(); } public String getId() { return id; } public void setId(String id) { this.id = id; } } <file_sep>package pl.com.sebastianbodzak.library.domain; import javax.persistence.Embeddable; /** * Created by Dell on 2016-10-11. */ @Embeddable public class Address { private String city; private String street; private String postalCode; private Address() {} public Address(String city, String street, String postalCode) { this.city = city; this.street = street; this.postalCode = postalCode; } public String getCity() { return city; } public String getStreet() { return street; } public String getPostalCode() { return postalCode; } } <file_sep>package library.api; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import pl.com.sebastianbodzak.library.api.EmailSender; import pl.com.sebastianbodzak.library.api.PasswordHasher; import pl.com.sebastianbodzak.library.api.SessionManager; import pl.com.sebastianbodzak.library.api.requests.SignupRequest; import pl.com.sebastianbodzak.library.domain.Employee; import pl.com.sebastianbodzak.library.domain.EmployeeRepository; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; /** * Created by Dell on 2016-10-12. */ @RunWith(MockitoJUnitRunner.class) public class SessionManagerTest { private SessionManager sessionManager; @Mock private EmployeeRepository employeeRepository; @Mock private PasswordHasher passwordHasher; @Mock private SignupRequest request; private Long anyId = 1L; private String password = "<PASSWORD>"; private String hashedPassword = "<PASSWORD>"; @Mock private EmailSender emailSender; @Mock private Employee employee; @Before public void setUp() { sessionManager = new SessionManager(employeeRepository, passwordHasher, emailSender); } @Test public void shouldSignupEmployee() { doNothing().when(request).validate(); when(employeeRepository.findByEmployeeId(anyId)).thenReturn(employee); when(passwordHasher.hashPassword(password)).thenReturn(hashedPassword); // sessionManager.signupByEmployee(request); } } <file_sep>package pl.com.sebastianbodzak.library.api; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pl.com.sebastianbodzak.library.api.requests.SignupRequest; import pl.com.sebastianbodzak.library.domain.EmailMessage; import pl.com.sebastianbodzak.library.domain.EmailMessageRepository; import pl.com.sebastianbodzak.library.domain.Employee; import pl.com.sebastianbodzak.library.domain.EmployeeRepository; import static pl.com.sebastianbodzak.library.domain.JobTitle.ADMIN; /** * Created by Dell on 2016-10-24. */ @Service public class StarterConfigurator { private EmployeeRepository employeeRepository; private EmailMessageRepository emailMessageRepository; private PasswordHasher passwordHasher; public StarterConfigurator(EmployeeRepository employeeRepository, EmailMessageRepository emailMessageRepository, PasswordHasher passwordHasher) { this.employeeRepository = employeeRepository; this.emailMessageRepository = emailMessageRepository; this.passwordHasher = passwordHasher; } @Transactional public void createAdmin() { Employee employee = new Employee(null, ADMIN, null); employee.register("admin", passwordHasher.hashPassword("<PASSWORD>")); employeeRepository.save(employee); } @Transactional public void createBasicEmailMessages() { EmailMessage message = new EmailMessage("CONFIRM_EMPLOYEE_REGISTRATION", "Register confirmation", "You are register correctly!"); emailMessageRepository.save(message); } } <file_sep>INSERT INTO EMAILMESSAGE VALUES ('FIRST_MESSAGE', 'title1', 'content1'); INSERT INTO EMAILMESSAGE VALUES ('SECOND_MESSAGE', 'title2', 'content2'); INSERT INTO EMAILMESSAGE VALUES ('THIRD_MESSAGE', 'title3', 'content3');<file_sep>jdbc.driverClassName=org.hsqldb.jdbcDriver jdbc.url=jdbc:hsqldb:mem:library jdbc.username=sa jdbc.password=<file_sep>package pl.com.sebastianbodzak.library.api; /** * Created by Dell on 2016-10-24. */ public class Utils { public static boolean validateString(String string) { return string == null || string.trim().isEmpty(); } } <file_sep>package pl.com.sebastianbodzak.library.api; import pl.com.sebastianbodzak.library.api.responses.ListOfMessagesResponse; /** * Created by Dell on 2016-10-20. */ public interface MessagesCatalog { ListOfMessagesResponse listAll(); } <file_sep>package pl.com.sebastianbodzak.library.domain; /** * Created by Dell on 2016-10-13. */ public interface EmailMessageRepository { void save(EmailMessage emailMessage); EmailMessage loadMessageById(String typeOfMessage); } <file_sep>package pl.com.sebastianbodzak.library.domain; /** * Created by Dell on 2016-10-11. */ public interface EmployeeRepository { void save(Employee employee); boolean isLoginOccupied(String login); Employee findByEmployeeId(Long employeeId); Employee findByLoginAndPassword(String login, String hashedPassword); } <file_sep>package pl.com.sebastianbodzak.library.infrastucture; import org.springframework.stereotype.Component; import pl.com.sebastianbodzak.library.api.responses.ListOfMessagesResponse; import pl.com.sebastianbodzak.library.api.dtos.EmailMessageDto; import pl.com.sebastianbodzak.library.api.MessagesCatalog; import pl.com.sebastianbodzak.library.domain.EmailMessage; import pl.com.sebastianbodzak.library.domain.EmailMessage_; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; /** * Created by Dell on 2016-10-20. */ @Component public class JpaMessagesCatalog implements MessagesCatalog { @PersistenceContext private EntityManager entityManager; @Override public ListOfMessagesResponse listAll() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<EmailMessageDto> query = builder.createQuery(EmailMessageDto.class); Root<EmailMessage> root = query.from(EmailMessage.class); query.getOrderList(); selectMessagesDto(builder, query, root); Query jpaQuery = entityManager.createQuery(query); return new ListOfMessagesResponse(jpaQuery.getResultList()); } private void selectMessagesDto(CriteriaBuilder builder, CriteriaQuery<EmailMessageDto> query, Root<EmailMessage> root) { query.select(builder.construct(EmailMessageDto.class, root.get(EmailMessage_.typeOfMessage), root.get(EmailMessage_.title), root.get(EmailMessage_.content) )); } } <file_sep>package pl.com.sebastianbodzak.library.domain; import org.hibernate.annotations.*; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import javax.persistence.CascadeType; import javax.persistence.Entity; import java.time.LocalDateTime; import java.util.Set; import static org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME; /** * Created by Dell on 2016-10-11. */ @Entity public class BooksOrder { @Id @GeneratedValue private Long id; @OneToOne private User user; @OneToMany(cascade = CascadeType.ALL) private Set<Book> books; @DateTimeFormat(iso = DATE_TIME) private LocalDateTime orderedAt; @Enumerated(EnumType.STRING) private OrderStatus orderStatus; @DateTimeFormat(iso = DATE_TIME) private LocalDateTime realizedAt; private BooksOrder() {} public BooksOrder(User user, Set<Book> books, LocalDateTime orderedAt, OrderStatus orderStatus, LocalDateTime realizedAt) { this.user = user; this.books = books; this.orderedAt = orderedAt; this.orderStatus = orderStatus; this.realizedAt = realizedAt; } public Long getId() { return id; } public User getUser() { return user; } public Set<Book> getBooks() { return books; } public LocalDateTime getOrderedAt() { return orderedAt; } public OrderStatus getOrderStatus() { return orderStatus; } public LocalDateTime getRealizedAt() { return realizedAt; } } <file_sep>package library.domain; import org.junit.Before; import org.junit.Test; import pl.com.sebastianbodzak.library.domain.Address; import pl.com.sebastianbodzak.library.domain.Employee; import pl.com.sebastianbodzak.library.domain.PersonalData; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static pl.com.sebastianbodzak.library.domain.JobTitle.LIBRARIAN; /** * Created by Dell on 2016-10-12. */ public class EmployeeTest { private Employee employee; private PersonalData personalData; private Address address; private String login = "login"; private String password = "<PASSWORD>"; @Before public void setUp() { address = new Address("City", "Street", "00-000"); personalData = new PersonalData("firstName", "lastName", "<EMAIL>", "123456789", address); employee = new Employee(personalData, LIBRARIAN, null); } @Test public void shouldRegisterEmployee() { employee.register(login, password); assertEquals(login, employee.getLogin()); assertTrue(employee.isRegistered()); } @Test(expected = IllegalStateException.class) public void shouldNotRegisterEmployee() { employee.register(login, password); employee.register(login, password); } @Test public void shouldReturnFalseBecauseEmployeeIsNotRegister() { boolean result = employee.isRegistered(); assertFalse(result); } } <file_sep>package pl.com.sebastianbodzak.library.domain; /** * Created by Dell on 2016-10-11. */ public enum UserStatus { STUDENT, SUSPENDED, STANDARD, ACADEMIC_WORKER } <file_sep>package pl.com.sebastianbodzak.library.ui; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import pl.com.sebastianbodzak.library.api.AuthRequiredException; import pl.com.sebastianbodzak.library.api.InvalidRequestException; /** * Created by Dell on 2016-10-12. */ @ControllerAdvice public class ErrorHandler { @ExceptionHandler(InvalidRequestException.class) public ResponseEntity<String> handleInvalidRequestException(InvalidRequestException exception) { HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.CONTENT_TYPE, "application/json"); return new ResponseEntity<String>( "{'error': '" + exception.getMessage() + "' }", headers, HttpStatus.UNPROCESSABLE_ENTITY ); } @ExceptionHandler(AuthRequiredException.class) public ResponseEntity<String> handlerAuthRequiredException() { HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.CONTENT_TYPE, "application/json"); return new ResponseEntity<String>( "{'error': 'authentication required'}", headers, HttpStatus.UNAUTHORIZED); } } <file_sep>package pl.com.sebastianbodzak.library.infrastucture; import org.springframework.stereotype.Repository; import pl.com.sebastianbodzak.library.domain.EmailMessage; import pl.com.sebastianbodzak.library.domain.EmailMessageRepository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * Created by Dell on 2016-10-13. */ @Repository public class JpaEmailMessageRepository implements EmailMessageRepository { @PersistenceContext private EntityManager entityManager; @Override public EmailMessage loadMessageById(String typeOfMessage) { return entityManager.find(EmailMessage.class, typeOfMessage); } } <file_sep>package pl.com.sebastianbodzak.library.infrastucture; import org.springframework.stereotype.Component; import pl.com.sebastianbodzak.library.api.AuthRequiredException; import pl.com.sebastianbodzak.library.api.RequiresAuth; import pl.com.sebastianbodzak.library.api.SessionManager; /** * Created by Dell on 2016-10-20. */ @Component public class AuthAspect { private SessionManager sessionManager; public AuthAspect(SessionManager sessionManager) { this.sessionManager = sessionManager; } public void checkAuth(RequiresAuth requiresAuth) { if (!sessionManager.isAuthenticated(requiresAuth.roles())) throw new AuthRequiredException(); } } <file_sep>package pl.com.sebastianbodzak.library.api.responses; import pl.com.sebastianbodzak.library.api.dtos.EmailMessageDto; import java.util.List; /** * Created by Dell on 2016-10-20. */ public class ListOfMessagesResponse { private List<EmailMessageDto> messages; public ListOfMessagesResponse(List<EmailMessageDto> messages) { this.messages = messages; } public List<EmailMessageDto> getMessages() { return messages; } public void setMessages(List<EmailMessageDto> messages) { this.messages = messages; } }
db8d3606813377d492ac603576e9abff743c15b2
[ "Java", "SQL", "INI" ]
27
Java
SebastianBodzak/library
58b76b5988f0c0a745fbc117c3deddec34e18b68
5964eaf16529c9d4c8fed860a2e2f3c6e6c8004d
refs/heads/master
<repo_name>julianohubel/SpaUserControl<file_sep>/SpaUserControl.Infrastructure/Repositories/UserRepository.cs using SpaUserControlDataContex.domain.Contracts.Reopositories; using SpaUserControlDataContex.domain.Model; using SpaUserControlDataContex.Infrastructure.Data; using System; using System.Linq; namespace SpaUserControlDataContex.Infrastructure.Repositories { public class UserRepository : IUserRepository { private SpaUserControlDataContext _context; public UserRepository(SpaUserControlDataContext context) { this._context = context; } public User Get(string email) { return _context.users.Where(x => x.Email.ToLower() == email.ToLower()).FirstOrDefault(); } public User Get(Guid id) { return _context.users.Where(x => x.Id == id).FirstOrDefault(); } public void Create(User user) { _context.users.Add(user); _context.SaveChanges(); } public void Update(User user) { _context.Entry<User>(user).State = System.Data.Entity.EntityState.Modified; _context.SaveChanges(); } public void Delete(User user) { _context.users.Remove(user); _context.SaveChanges(); } public void Dispose() { _context.Dispose(); } } } <file_sep>/SpaUserControl.Startup/DependencyResolver.cs using SpaUserControl.bussines.Services; using SpaUserControl.domain.Contracts.Services; using SpaUserControlDataContex.domain.Contracts.Reopositories; using SpaUserControlDataContex.Infrastructure.Data; using SpaUserControlDataContex.Infrastructure.Repositories; using Unity; using Unity.Lifetime; namespace SpaUserControl.Startup { public static class DependencyResolver { public static void Resolve(UnityContainer container) { container.RegisterType<SpaUserControlDataContext, SpaUserControlDataContext>(new HierarchicalLifetimeManager()); container.RegisterType<IUserRepository,UserRepository>(new HierarchicalLifetimeManager()); container.RegisterType<IUserService, UserServices>(new HierarchicalLifetimeManager()); } } } <file_sep>/SpaUserControl.bussines/Services/UserServices.cs using SpanUserControl.common.Resources; using SpanUserControl.common.Validation; using SpaUserControl.domain.Contracts.Services; using SpaUserControlDataContex.domain.Contracts.Reopositories; using SpaUserControlDataContex.domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpaUserControl.bussines.Services { public class UserServices : IUserService { private IUserRepository _repository; public UserServices(IUserRepository repository) { this._repository = repository; } public User Authenticate(string email, string password) { var user = GetByEmail(email); if (user.Password != PasswordAssertionConcern.Encrypt(password)) throw new Exception(Erros.InvalidPassword); return user; } public void ChangeInformation(string email, string name) { var user = GetByEmail(email); user.ChangeName(name); user.Validate(); _repository.Update(user); } public void ChangePassword(string email, string password, string newPassword, string confirmPassword) { var user = Authenticate(email, password); user.SetPassWord(newPassword, confirmPassword); user.Validate(); _repository.Update(user); } public string ResetPassword(string Email) { var user = GetByEmail(Email); string password = user.ResetPassword(); user.Validate(); return password; } public User GetByEmail(string email) { var user = _repository.Get(email); if (user == null) throw new Exception(Erros.UserNotFound); return user; } public void Register(string name, string email, string password, string confirmPassword) { var hasUser = _repository.Get(email); if (hasUser != null) throw new Exception(Erros.DuplicateEmail); var user = new User(name, email); user.SetPassWord(password, confirmPassword); user.Validate(); _repository.Create(user); } public void Dispose() { _repository.Dispose(); } } } <file_sep>/ConsoleApp1/Program.cs using SpaUserControl.domain.Contracts.Services; using SpaUserControl.Startup; using SpaUserControlDataContex.domain.Contracts.Reopositories; using SpaUserControlDataContex.domain.Model; using SpaUserControlDataContex.Infrastructure.Data; using SpaUserControlDataContex.Infrastructure.Repositories; using System; using System.Collections.Generic; using System.Data.Entity.Core.Metadata.Edm; using System.Linq; using System.Text; using System.Threading.Tasks; using Unity; namespace ConsoleApp1 { class Program { static void Main(string[] args) { var container = new UnityContainer(); DependencyResolver.Resolve(container); var service = container.Resolve<IUserService>(); try { service.Register("Juliano", "<EMAIL>", "123Mudar", "123Mudar"); SpaUserControlDataContext context = new SpaUserControlDataContext(); var user = context.users.Where(u => u.Email == "<EMAIL>").FirstOrDefault(); Console.WriteLine(user.Email); Console.ReadKey(); } catch(Exception ex) { Console.WriteLine(ex.Message); Console.ReadKey(); } } } } <file_sep>/SpaUserControl.Infrastructure/Data/Map/UserMap.cs using SpaUserControlDataContex.domain.Model; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.ModelConfiguration; namespace SpaUserControlDataContex.Infrastructure.Data.Map { class UserMap : EntityTypeConfiguration<User> { public UserMap() { ToTable("User"); Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(x => x.Name).HasMaxLength(60).IsRequired(); Property(x => x.Email).HasMaxLength(160) .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation( new IndexAttribute("IX_EMAIL", 1) { IsUnique = true })) .IsRequired(); Property(x => x.Password).HasMaxLength(32).IsFixedLength(); } } } <file_sep>/SpaUserControl.Infrastructure/Data/SpaUserControlDataContext.cs using SpaUserControlDataContex.domain.Model; using SpaUserControlDataContex.Infrastructure.Data.Map; using System.Data.Entity; namespace SpaUserControlDataContex.Infrastructure.Data { public class SpaUserControlDataContext : DbContext { public SpaUserControlDataContext():base("SpaUserControlDataContext") { Configuration.LazyLoadingEnabled = false; Configuration.ProxyCreationEnabled = false; } public DbSet<User> users { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new UserMap()); } } }
6a6d7c7781862954199ca8b0e0bdbda430b4ca2b
[ "C#" ]
6
C#
julianohubel/SpaUserControl
a255064a9b25cc05a2b7f12627265933825ce57a
8d2964d78bcb3939cca291269907ccc386ea0575
refs/heads/master
<file_sep>#include <windows.h> #include <WinEvt.h> #include <tchar.h> #include <time.h> #include <stdio.h> #include <strsafe.h> typedef unsigned long long QWORD; typedef unsigned long DWORD; typedef unsigned short WORD; typedef unsigned char BYTE; #define ERROR_ARGUMENTS -1 #define ERROR_BAD_INFILE -2 #define ERROR_BAD_OUTFILE -3 void ParseEvent( HANDLE hEvent, FILE* pFile ) { DWORD dwBufferSize = 0; DWORD dwBufferUsed = 0; DWORD dwPropertyCount = 0; LPWSTR pBuffer = NULL; // Figure out how big of a buffer we need. if( !EvtRender( NULL, hEvent, EvtRenderEventXml, dwBufferSize, pBuffer, &dwBufferUsed, &dwPropertyCount ) ) { if( ERROR_INSUFFICIENT_BUFFER == GetLastError() ) { // Create the buffer. dwBufferSize = dwBufferUsed; pBuffer = (LPWSTR)malloc( dwBufferSize ); if( pBuffer ) { // Render the actual event. EvtRender( NULL, hEvent, EvtRenderEventXml, dwBufferSize, pBuffer, &dwBufferUsed, &dwPropertyCount ); } else { _ftprintf( stderr, _T("Out of memory\n") ); goto done; } } if( ERROR_SUCCESS != GetLastError() ) { _ftprintf( stderr, _T("EvtRender failed with error code %d\n"), GetLastError() ); goto done; } } // Print the event to the file. _ftprintf( pFile, _T("%s\n"), pBuffer ); done: if( pBuffer ) free( pBuffer ); } int _tmain( int argc, TCHAR** argv ) { EVT_HANDLE hLog; TCHAR sInFileName[MAX_PATH]; TCHAR sOutFileName[MAX_PATH]; FILE* pOutFile; EVT_HANDLE hEvent; DWORD dwToss; BOOL bNext = TRUE; // Make sure we have the right number of arguments. if( argc < 2 ) { _ftprintf( stderr, _T("USAGE: evttocsv.exe infile [outfile]\n") ); return ERROR_ARGUMENTS; } // Get the input file name. StringCchCopy( sInFileName, MAX_PATH, argv[1] ); // If an output file is specified, use that, otherwise append ".csv" to the // input file's name. if( argc > 2 ) { StringCchCopy( sOutFileName, MAX_PATH, argv[2] ); } else { StringCchCopy( sOutFileName, MAX_PATH, sInFileName ); StringCchCat( sOutFileName, MAX_PATH, _T(".csv") ); } _tprintf( _T("In file: %s\n"), sInFileName ); _tprintf( _T("Out file: %s\n\n"), sOutFileName ); // Open the event log file specified on the command line. hLog = EvtQuery( NULL, sInFileName, NULL, EvtOpenFilePath | EvtQueryReverseDirection ); if( NULL == hLog ) { _ftprintf( stderr, _T("Unable to open input file, %s\n"), sInFileName ); return ERROR_BAD_INFILE; } // Open the output file for the conversion. _tfopen_s( &pOutFile, sOutFileName, _T("w") ); if( !pOutFile ) { EvtClose( hLog ); _ftprintf( stderr, _T("Unable to open output file, %s\n"), sOutFileName ); return ERROR_BAD_OUTFILE; } while( bNext ) { // Retrieve the next log entry. bNext = EvtNext( hLog, 1, &hEvent, 1000, 0, &dwToss ); if( !bNext ) { switch( GetLastError() ) { case ERROR_NO_MORE_ITEMS: _ftprintf( pOutFile, _T("\nEnd of event log reached!\n") ); bNext = FALSE; break; case ERROR_TIMEOUT: _ftprintf( stderr, _T("Timeout waiting for event entry.\n") ); continue; default: _ftprintf( stderr, _T("Unknown error code, %d\n"), GetLastError() ); bNext = FALSE; break; } } ParseEvent( hEvent, pOutFile ); // Close the log entry. EvtClose( hEvent ); } fclose( pOutFile ); EvtClose( hLog ); return 0; } <file_sep>using System; using System.Diagnostics.Eventing.Reader; using System.IO; using System.Text; namespace Event_to_Text { class Event_to_Text { private const int VERSION_MAJOR = 1; private const int VERSION_MINOR = 0; private const int ERROR_ARGUMENTS = -1; private const int ERROR_FILE_NOT_FOUND = -2; private const int ERROR_BAD_EVENT_FILE = -3; public static int Main(string[] argv) { EventLogQuery evtQuery; EventLogReader evtReader; if (argv.Length < 1) { Console.Error.WriteLine("Event2Text version " + VERSION_MAJOR + "." + VERSION_MINOR); Console.Error.WriteLine("USAGE: evt2txt.exe infile"); return ERROR_ARGUMENTS; } if (!File.Exists(argv[0])) { Console.Error.WriteLine("Input file not found: " + argv[0]); return ERROR_FILE_NOT_FOUND; } try { evtQuery = new EventLogQuery(argv[0], PathType.FilePath); evtReader = new EventLogReader(evtQuery); } catch (Exception e) { Console.Error.WriteLine("Input file specified is not a valid log file!"); Console.Error.WriteLine(e); return ERROR_BAD_EVENT_FILE; } for (EventRecord record = evtReader.ReadEvent(); null != record; record = evtReader.ReadEvent()) { Console.WriteLine(record.ToXml()); } return 0; } } } <file_sep>libpath = /LIBPATH:"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Lib" /LIBPATH:"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib" libpath64 = /LIBPATH:"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Lib\x64" /LIBPATH:"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\amd64" cl = "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cl.exe" cl64 = "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64\cl.exe" link = "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\link.exe" link64 = "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64\link.exe" clparam = /nologo /EHsc /c /D "_CONSOLE" /D "WIN32" /D "NDEBUG" /D "_UNICODE" /D "UNICODE" /Zc:wchar_t /Zc:forScope /Gd /GS /Gy /GL /W3 /O2 /Oi linkparam = /LTCG /RELEASE /SUBSYSTEM:CONSOLE /NOLOGO /MACHINE:X86 /DYNAMICBASE /NXCOMPAT /OPT:REF /OPT:ICF /ALLOWISOLATION /INCREMENTAL:NO $(libpath) linkparam64 = /LTCG /RELEASE /SUBSYSTEM:CONSOLE /NOLOGO /MACHINE:X64 /DYNAMICBASE /NXCOMPAT /OPT:REF /OPT:ICF /ALLOWISOLATION /INCREMENTAL:NO $(libpath64) csharp = csc.exe csparam = /nologo /target:exe objs = evttocsv.obj objsx = evtxtocsv.obj objs64 = evttocsv64.obj objs64x = evtxtocsv64.obj libs = kernel32.lib Wevtapi.lib target = evttocsv.exe targetx = evtxtocsv.exe target64 = evttocsv64.exe target64x = evtxtocsv64.exe cstarget = evt2txt.exe all: $(target) $(target64) $(targetx) $(target64x) $(cstarget) x64: $(target64) $(target64x) $(cstarget) clean: del $(objs) $(objs64) $(objsx) $(objs64x) $(target) $(target64) $(targetx) $(target64x) $(cstarget) evttocsv.obj: evttocsv.cpp $(cl) $(clparam) /Fo"$@" $** evttocsv64.obj: evttocsv.cpp $(cl64) $(clparam) /Fo"$@" $** evtxtocsv.obj: evtxtocsv.cpp $(cl) $(clparam) /Fo"$@" $** evtxtocsv64.obj: evtxtocsv.cpp $(cl64) $(clparam) /Fo"$@" $** $(target): $(objs) $(link) $(linkparam) /OUT:$(target) $(libs) $** $(target64): $(objs64) $(link64) $(linkparam64) /OUT:$(target64) $(libs) $** $(targetx): $(objsx) $(link) $(linkparam) /OUT:$(targetx) $(libs) $** $(target64x): $(objs64x) $(link64) $(linkparam64) /OUT:$(target64x) $(libs) $** $(cstarget): evt2txt.cs $(csharp) $(csparam) /platform:anycpu /OUT:$@ $** <file_sep>#include <tchar.h> #include <time.h> #include <iostream> #include <stdio.h> #include <string> using namespace std; typedef unsigned long long QWORD; typedef unsigned long DWORD; typedef unsigned short WORD; typedef unsigned char BYTE; int main( int argc, char** argv ) { string sInFileName; string sOutFileName; FILE* pInFile; FILE* pOutFile; string sCSV; // Make sure we have the right number of arguments. if( argc < 2 ) { cout << "USAGE: evttocsv.exe infile [outfile]\n"; return 0; } // Get the input file name. sInFileName = argv[1]; if( argc > 2 ) { sOutFileName = argv[2]; } else { sOutFileName = sInFileName + ".csv"; } cout << "In file: " << sInFileName << endl; cout << "Out file: " << sOutFileName << "\n\n"; pInFile = fopen( sInFileName.c_str(), "rb" ); if( !pInFile ) { cout << "Unable to open input file " << sInFileName << "!\n"; return 0; } pOutFile = fopen( sOutFileName.c_str(), "w" ); if( !pOutFile ) { fclose( pInFile ); cout << "Unable to open output file " << sOutFileName << "!\n"; return 0; } char sCrap[48]; if( !feof( pInFile ) ) fread( (char*)&sCrap, 1, 48, pInFile ); sCSV = "Date Created,Date Written,Event ID,Event Type,String Count,Category,Source,Computer,Description,SID,Data\n"; fwrite( sCSV.c_str(), 1, sCSV.length(), pOutFile ); while( !feof( pInFile ) ) { DWORD dwLength; DWORD dwReserved; DWORD dwNumber; DWORD dwDateCreated; DWORD dwDateWritten; DWORD wEventID; WORD wEventType; WORD wStringCount; WORD wCategory; WORD wReservedFlags; DWORD dwClosingNumber; DWORD dwStringOffset; DWORD dwSIDLength; DWORD dwSIDOffset; DWORD dwDataLength; DWORD dwDataOffset; string sSourceName = ""; string sComputerName = ""; string sSID = ""; string sData = ""; string sStrings = ""; string sDateCreated = ""; string sDateWritten = ""; TCHAR c; int i = 0, j = 0; char* csv = new char[512]; fread( (char*)&dwLength, 1, 4, pInFile ); if( dwLength < 92 ) { delete csv; break; } char* pData = new char[dwLength - 4]; fread( pData, 1, (dwLength - 4), pInFile ); dwReserved = *((DWORD*)&pData[0]); dwNumber = *((DWORD*)&pData[4]); dwDateCreated = *((DWORD*)&pData[8]); dwDateWritten = *((DWORD*)&pData[12]); wEventID = *((WORD*)&pData[16]); wEventType = *((WORD*)&pData[20]); wStringCount = *((WORD*)&pData[22]); wCategory = *((WORD*)&pData[24]); wReservedFlags = *((WORD*)&pData[26]); dwClosingNumber = *((DWORD*)&pData[28]); dwStringOffset = *((DWORD*)&pData[32]); dwSIDLength = *((DWORD*)&pData[36]); dwSIDOffset = *((DWORD*)&pData[40]); dwDataLength = *((DWORD*)&pData[44]); dwDataOffset = *((DWORD*)&pData[48]); i = 52; while( (c = *((TCHAR*)&pData[i])) != '\0' ) { sSourceName += (char)c; i += 2; } i += 2; while( (c = *((TCHAR*)&pData[i])) != '\0' ) { sComputerName += (char)c; i += 2; } if( dwSIDLength ) { i = dwSIDOffset - 4; for( j = 0; j < dwSIDLength; j++ ) { sSID += (char)*((char*)&pData[i]); i++; } } if( dwDataLength ) { i = dwDataOffset - 4; for( j = 0; j < dwDataLength; j++ ) { sData += (char)*((char*)&pData[i]); i++; } } if( wStringCount > 1 ) { i = dwStringOffset - 4; for( j = 0; j < wStringCount; j++ ) { while( (c = *((TCHAR*)&pData[i])) != '\0' ) { sStrings += (char)c; i += 2; } sStrings += " | "; i += 2; } } delete pData; time_t tDateCreated = (time_t)dwDateCreated; time_t tDateWritten = (time_t)dwDateWritten; sDateCreated = asctime( localtime( &tDateCreated) ); sDateCreated = sDateCreated.substr( 0, sDateCreated.length() - 1 ); sDateWritten = asctime( localtime( &tDateWritten) ); sDateWritten = sDateWritten.substr( 0, sDateWritten.length() - 1 ); sprintf( csv, "%s,%s,%d,%d,%d,%d,%s,%s,%s,,\n", sDateCreated.c_str(), sDateWritten.c_str(), wEventID, wEventType, wStringCount, wCategory, sSourceName.c_str(), sComputerName.c_str(), sStrings.c_str() ); fwrite( csv, 1, strlen(csv), pOutFile ); delete csv; } fclose( pOutFile ); fclose( pInFile ); return 0; }
611b1385ae3c807a87259770f4ffb1f3faa06c32
[ "C#", "Makefile", "C++" ]
4
C++
anxkha/EventLog-to-CSV
39a7dcef54087d1f59da762c33d67e0cc1004eea
ecc007bedd3beed2e9a5e36014569104daeea949
refs/heads/master
<repo_name>taynara539/php<file_sep>/index.php <?php echo "Olá mundo 5622!" echo "ola udemy" ?>
bba38507b5c0bafcc57ef98929973a73bb3cc7a9
[ "PHP" ]
1
PHP
taynara539/php
3ddcbf957b202310171428379312b6cd496ad354
9b7273680245d4bccf4115ef8ba3b22ea4ed8ae5
refs/heads/master
<file_sep>'use strict'; // Document ready $(document).on('ready', function(){ // Magnific popup gallery $('.gallery').each(function() { $(this).magnificPopup({ delegate: '.gallery-item', type: 'image', gallery:{ enabled:true }, zoom: { enabled: true, // By default it's false, so don't forget to enable it duration: 300, // duration of the effect, in milliseconds easing: 'ease-in-out', // CSS transition easing function // The "opener" function should return the element from which popup will be zoomed in // and to which popup will be scaled down // By defailt it looks for an image tag: opener: function(openerElement) { // openerElement is the element on which popup was initialized, in this case its <a> tag // you don't need to add "opener" option if this code matches your needs, it's defailt one. return openerElement.is('img') ? openerElement : openerElement.find('img'); } } }); }); // Magnific popup one image $('.image-popup').magnificPopup({ type: 'image', closeOnContentClick: true, mainClass: 'mfp-img-mobile', image: { verticalFit: true } }); // Magnific popup video $('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({ type: 'iframe', mainClass: 'mfp-fade', removalDelay: 160, preloader: false, fixedContentPos: false }); $('.open-popup-link').magnificPopup({ type: 'inline', midClick: true // Allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source in href. }); $("a[href*='#'].anchor").mPageScroll2id({ offset: '.header' }); $('.facts__carousel').slick({ slidesToShow: 1, slidesToScroll: 1, autoplay: true, autoplaySpeed: 2000, dots: true, arrows: false }); $('.btn--svg').each(function(){ var animation = anime({ targets: $(this).find('.path-animate').get(0), strokeDashoffset: 442, easing: 'linear', duration: 5000, loop: true, autoplay: false }); $(this).hover(function(){ animation.play(); }, function(){ animation.pause(); }); }); $("#form").validate(); $('.j-modal-test').on('click', function(){ setTimeout(function(){ $.magnificPopup.open({ showCloseBtn: false, items: { src: '#modal' }, type: 'inline' }) }, 3000) }); $('.j-modal-close').on('click', function(){ $.magnificPopup.close(); }); headerScroll(); readMoreContent(); formLetter(); donatePayment(); }); $(window).on('load', function() { $(".loader").delay(100).fadeOut("slow", animatedLanding()); }); function animatedLanding(){ var tl = gsap.timeline(); var width = $(window).width(); if (width >= 1600 ) { tl .from('.roll__wrapper-img', {duration: 2, autoAlpha: 0}, 'first') .from('.header__btn', {duration: 1, y: -50, autoAlpha: 0}, 'first') .from('.roll__btn', {duration: 1, y: 100, autoAlpha: 0}, 'first') .from('.roll__block', {duration: 1, top: '-100%', autoAlpha: 0}, 'first') .from('.roll__block', {duration: 1.5, width: 163, left: '50%'}, '-=1') .fromTo('.roll__content-wrapper', {clipPath: 'polygon(0 0, 0 0, 0 100%, 0% 100%)'}, {duration: 1.5, clipPath: 'polygon(0 0, 100% 0, 100% 100%, 0 100%)'}, 'first') ; } else if (width >= 1201 && width <= 1599) { tl .from('.roll__wrapper-img', {duration: 2, autoAlpha: 0}, 'first') .from('.header__btn', {duration: 1, y: -50, autoAlpha: 0}, 'first') .from('.roll__btn', {duration: 1, y: 100, autoAlpha: 0}, 'first') .from('.roll__block', {duration: 1, top: '-100%', autoAlpha: 0}, 'first') .from('.roll__block', {duration: 1.5, width: 128, left: '50%'}, '-=1') .fromTo('.roll__content-wrapper', {clipPath: 'polygon(0 0, 0 0, 0 100%, 0% 100%)'}, {duration: 1.5, clipPath: 'polygon(0 0, 100% 0, 100% 100%, 0 100%)'}, 'first') ; } else if (width < 1200) { tl.kill(); gsap.set('.header__btn', {clearProps:"all"}); gsap.set('.roll__content-wrapper', {clearProps:"all"}); gsap.set('.roll__btn', {clearProps:"all"}); gsap.set('.roll__block', {clearProps:"all"}); } } $(window).on('scroll', function() { headerScroll(); }); $(window).on('resize', function() { }); function headerScroll(){ var header = $('.header'); var width = $(window).width(); if ($(window).scrollTop() > header.height()) { header.addClass('is-scroll'); } else { header.removeClass('is-scroll'); } } function readMoreContent() { var block = $('.what__content'); var btn = $('.what__content-link'); btn.on('click', function(e){ e.preventDefault(); if (block.hasClass('is-active')) { block.removeClass('is-active') } else { block.addClass('is-active') } }); } function formLetter() { var form = $('.payment__add'), btnAddLetter = form.find('.payment__add-btn'), letter = $('.payment__add-block'), formWrapper = form.find('.payment__add-wrapper'), formArray = [0] ; $(document).on('click', '.payment__block-remove', function() { formArray.pop(); $(this).parent().remove(); }); btnAddLetter.on('click', function(){ var number = formArray.length - 1; formArray.push(number + 1); var block = `<div class="payment__add-block"> <button class="payment__block-remove" type="button">Удалить</button> <div class="payment__block-title">Буква <span>${formArray.length}</span> для</div> <div class="payment__block-wrapper"> <div class="div1"> <div class="form-group"> <input class="form-control" type="text" name="letter-name-${formArray.length}" placeholder="Ваше имя"> </div> </div> <div class="div2"> <div class="form-group"> <input class="form-control" type="text" name="letter-lastname-${formArray.length}" placeholder="Фамилия"> </div> </div> <div class="div3"> <div class="form-group"> <input class="form-control" type="text" name="letter-mother-${formArray.length}" placeholder="Имя матери"> </div> </div> </div> </div>` formWrapper.append(block); }); } function donatePayment() { var input = $('#donate-custom'); var row = $('#payment__donate'); var label = $('#no-donate input[type="checkbox"]') input.on('click', function(e){ row.find('input[type="radio"]').prop("checked", false); }); label.on('click', function(e){ var _this = $(this); if (_this.prop("checked")) { row.hide(); } else { row.show(); } }); input.on('input', function(){ var _this = $(this); if (_this.val().length > 0) { _this.addClass('has-donate'); } else { _this.removeClass('has-donate'); } }); $('#payment__donate input[type="radio"]').on('change', function(){ input.val('').removeClass('has-donate'); }); } jQuery.extend(jQuery.validator.messages, { required: "Обязательное поле", remote: "Please fix this field.", email: "Введите правильный e-mail.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date (ISO).", number: "Please enter a valid number.", digits: "Please enter only digits.", creditcard: "Please enter a valid credit card number.", equalTo: "Пароли не совпадают.", accept: "Please enter a value with a valid extension.", maxlength: jQuery.validator.format("Please enter no more than {0} characters."), minlength: jQuery.validator.format("Please enter at least {0} characters."), rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."), range: jQuery.validator.format("Please enter a value between {0} and {1}."), max: jQuery.validator.format("Please enter a value less than or equal to {0}."), min: jQuery.validator.format("Please enter a value greater than or equal to {0}.") });
6331125595d9503beda21fc4429663c4a3f4320a
[ "JavaScript" ]
1
JavaScript
haoss/source_letterts_fig_png_font_favicon
7ae8d0748fb9c77e4e285ee18586e19cf59cd42c
8a1fc84a017ff54b47b2457caf3ec18ec6617ae9
refs/heads/master
<repo_name>Prologh/waterloo<file_sep>/C sharp 003/MainWindow.xaml.cs using System; using System.Windows; namespace Waterloo { /// <summary> /// Exception throwed in some custom situation. /// </summary> public class CustomException : Exception { public CustomException(){} public CustomException(string msg) { //TODO //DO SOMETHING WITH THE ERROR MESSEGE //I.E. DISPLAY IT SOMEHOW } } /// <summary> /// Class handling the main windows of application. /// </summary> public partial class MainWindow : Window { /// <summary> /// Constructor of main application. /// </summary> public MainWindow() { InitializeComponent(); } private void NewGame_Click(object sender, RoutedEventArgs e) { //TODO //NEW GAME INITATION } private void LoadGame_Click(object sender, RoutedEventArgs e) { //TODO //LOADING GAME OPENS "FILE CHOOSING" DIALOG BOX } private void SaveGame_Click(object sender, RoutedEventArgs e) { //TODO //SAVING GAME OPENS "SAVE AS" DIALOG BOX } private void ExitApp_Click(object sender, RoutedEventArgs e) { var message = "Czy na pewno zakończyć grę?"; var caption = "Zakończ"; var buttons = MessageBoxButton.YesNo; var icon = MessageBoxImage.Question; if (MessageBox.Show(message, caption, buttons, icon) == MessageBoxResult.Yes) { Application.Current.Shutdown(); } } private void LevelReset_Click(object sender, RoutedEventArgs e) { //TODO //RESETING THE BOARD } } }
dbc6865de76a9b7ea11d24b6c170d770d22b69c8
[ "C#" ]
1
C#
Prologh/waterloo
c8b00a15f4bcd8a54fa5d226e063da596ce132e7
19d5b3db8577ad810900b18975c5137615deb7dc
refs/heads/master
<file_sep><!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Click outside to close menu - source: stackoverflow --> <script> jQuery('body').bind('click', function(e) { if(jQuery(e.target).closest('.navbar').length == 0) { // click happened outside of .navbar, so hide var opened = jQuery('.navbar-collapse').hasClass('collapse in'); if ( opened === true ) { jQuery('.navbar-collapse').collapse('hide'); } } }); </script> <file_sep><!DOCTYPE html> <html lang="en"> <?php include 'includes/head.php'; ?> <body> <?php include 'includes/nav.php'; ?> <!-- Header for the page --> <header class="jumbotron hero-spacer"> <h1>Register</h1> <p>Register for Freedom Hack 2016 using the form below!</p> </header> <!-- Page Content --> <div class="container"> <!-- Change the width and height values to suit you best --> <div class="typeform-widget" data-url="https://abhiram4.typeform.com/to/uZAAum" data-text="Freedom Hack 2.0" style="width:100%;height:500px;"></div> <script>(function(){var qs,js,q,s,d=document,gi=d.getElementById,ce=d.createElement,gt=d.getElementsByTagName,id='typef_orm',b='https://s3-eu-west-1.amazonaws.com/share.typeform.com/';if(!gi.call(d,id)){js=ce.call(d,'script');js.id=id;js.src=b+'widget.js';q=gt.call(d,'script')[0];q.parentNode.insertBefore(js,q)}})()</script> <div style="font-family: Sans-Serif;font-size: 12px;color: #999;opacity: 0.5; padding-top: 5px;">Powered by <a href="http://www.typeform.com/?utm_campaign=uZAAum&amp;utm_source=typeform.com-1567566-Basic&amp;utm_medium=typeform&amp;utm_content=typeform-embedded&amp;utm_term=EN" style="color: #999" target="_blank">Typeform</a></div> </div> <!-- /.container --> <?php include 'includes/footer.php'; ?> <?php include 'includes/js.php'; ?> </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <?php include 'includes/head.php'; ?> <body> <?php include 'includes/nav.php'; ?> <!-- Jumbotron Header --> <header class="jumbotron hero-spacer"> <h1>Freedom Hack 2016</h1> <p>Welcome to Freedom Hack!</p> <p><a href="register" class="btn btn-primary btn-lg">Register</a> </p> </header> <!--<hr>--> <!-- Page Content --> <div class="container"> <!-- Information snippets --> <div class="row text-center"> <div class="col-md-3 col-sm-6 hero-feature"> <div class="thumbnail"> <div class="caption"> <h3>Register</h3> <p>Interested in signing up? Register for Freedom Hack now!</p> <p> <a href="register" class="btn btn-primary">Register</a> </p> </div> </div> </div> <div class="col-md-3 col-sm-6 hero-feature"> <div class="thumbnail"> <div class="caption"> <h3>Schedule</h3> <p>You can find the schedule for the hackathon here.</p> <p> <a href="schedule" class="btn btn-default">Schedule</a> </p> </div> </div> </div> <div class="col-md-3 col-sm-6 hero-feature"> <div class="thumbnail"> <div class="caption"> <h3>Where?</h3> <p>Freedom Hack will be held at the offices of Hacker Earth, which is located in Bangalore, Koramangala.</p> <p> <a href="https://www.google.co.in/maps/place/HackerEarth/@12.9336569,77.6145849,16.75z/data=!4m6!1m3!3m2!1s0x3bae144482c932d5:0xdc71453c34075c4c!2sHackerEarth!3m1!1s0x3bae144482c932d5:0xdc71453c34075c4c" class="btn btn-success" target="_blank">Locate on Google Maps</a> </p> </div> </div> </div> <div class="col-md-3 col-sm-6 hero-feature"> <div class="thumbnail"> <div class="caption"> <h3>When?</h3> <p>Freedom Hack will kick off on 9th January, 2016 and end about 24 hours later, on 10th January.</p> <p> </p> </div> </div> </div> </div> <!-- /.row --> </div> <!-- /.container --> <?php include 'includes/footer.php'; ?> <?php include 'includes/js.php'; ?> </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <?php include 'includes/head.php'; ?> <body> <?php include 'includes/nav.php'; ?> <!-- Header --> <header class="jumbotron hero-spacer"> <h1>Schedule</h1> <p>Register for Freedom Hack 2016 using the form below!</p> </header> <!-- Content --> <div class="container"> <center> <table class="table" style="width: 50%;"> <thead> <th> Date </th> <th> Time </th> <th> Event </th> </thead> <tbody> <td> 09/01/2016 </td> <td> 09:00 </td> <td> Reporting time </td> </tbody> </table> Bleh, somebody give me the final schedule :P </center> </div> <!-- /.container --> <?php include 'includes/footer.php'; ?> <?php include 'includes/js.php'; ?> </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <?php include 'includes/head.php'; ?> <body> <?php include 'includes/nav.php'; ?> <!-- Header for the page --> <header class="jumbotron hero-spacer"> <h1>About</h1> <p>Who are we and why are we doing Freedom Hack?</p> </header> <!-- Page Content --> <div class="container"> <p>Freedom Hack is a 24 hour Hackathon which is being organised by Free Software Movement Karnataka(FSMK) in association with Hacker Earth. Freedom Hack is being organised in the memory of the late Aaron Swartz, an Internet activist who fought for the open and free Internet platform. You can read more about <NAME> <a href="who-was-aaron-swartz">here</a>.</p> <p>January is celebrated as the month of Data Privacy and so, we call all hackers to contribute to make the Internet more open.</p> <p>The theme of the event is <b>Fork The Internet</b> and all the solutions to the problem statements should be ways to achieve this.</p> <p>Freedom Hack is an initiative of Free Software Movement Karnataka (FSMK), a non profit organisation which strives to promote the use and development of open source software.</p> <p><a href="register">Register now!</a></p> </div> <!-- /.container --> <?php include 'includes/footer.php'; ?> <?php include 'includes/js.php'; ?> </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <?php include 'includes/head.php'; ?> <body> <?php include 'includes/nav.php'; ?> <!-- Header for the page --> <header class="jumbotron hero-spacer"> <h1>Rules &amp; Regulations</h1> <p>The code of conduct is important to ensure <i>everybody</i> has a nice time.</p> </header> <!-- Page Content --> <div class="container"> <p>All attendees, sponsors, partners, volunteers and staff at our hackathon are required to agree with the following code of conduct. Organisers will enforce this code throughout the event. We are expecting cooperation from all participants to help ensure a safe environment for everybody.</p> <p><h2>The Quick Version</h2></p> <p>Our hackathon is dedicated to providing a harassment-free experience for everyone, regardless of gender, gender identity and expression, age, sexual orientation, disability, physical appearance, race, ethnicity, nationality, religion, previous hackday attendance or computing experience (or lack of any of the aforementioned). We do not tolerate harassment of hackathon participants in any form. Sexual language and imagery is not appropriate at any hackathon venue, including hacks, talks, workshops, parties, social media and other online media. Hackathon participants violating these rules may be sacked or expelled from the hackathon without a refund (if applicable) at the discretion of the hackathon organisers.</p> <p><h2>The Less Quick Version</h2></p> <p>Harassment includes offensive verbal comments related to gender, gender identity and expression, age, sexual orientation, disability, physical appearance, race, ethnicity, nationality, religion, sexual images in public spaces, intimidation, stalking, following, photography or audio/video recording against reasonable consent, sustained disruption of talks or other events, inappropriate physical contact, and unwelcome sexual attention.</p> <p>Photography is encouraged, but other participants must be given a reasonable chance to opt out from being photographed. If they object to the taking of their photograph, comply with their request. It is inappropriate to take photographs in contexts where people have a reasonable expectation of privacy (in bathrooms or where participants are sleeping).</p> <p>Participants asked to stop any harassing behavior are expected to comply immediately.</p> <p>As this is a hackathon we like to explicity note that the hacks created at our hackathon are equally subject to the anti-harassment policy.</p> <p>If you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact a member of hackathon staff immediately.</p> <p>Hackathon staff will be happy to help participants contact any local security or local law enforcement, provide escorts, or otherwise assist those experiencing harassment to feel safe for the duration of the hackathon. We value your attendance.</p> <p>If a participant engages in harassing behaviour, the hackathon organisers may take any action they deem appropriate, including warning the offender or expulsion from the hackathon.</p> <p>We expect participants to follow these rules at the hackathon.</p> </div> <!-- /.container --> <?php include 'includes/footer.php'; ?> <?php include 'includes/js.php'; ?> </body> </html> <file_sep><!DOCTYPE html> <html lang="en"> <?php include 'includes/head.php'; ?> <body> <?php include 'includes/nav.php'; ?> <!-- Header for the page --> <header class="jumbotron hero-spacer"> <h1>Who Was <NAME>?</h1> </header> <!-- Content --> <div class="container"> <p> <NAME> was a computer programmer, open source proponent and internet activist. He was a key contributor to many projects from a very young age. The list of projects he worked on is impressive, with big names like the RSS web feed format, the Markdown publishing format which is a favourite of bloggers, the organisation Creative Commons and the web framework web.py. Aaron also contributed to the development of the popular website Reddit, after his site Infogami merged with Reddit. </p> <p> Aaron was involved in the campaign against SOPA (Stop Online Piracy Act), claiming this bill could potentially shut down entire websites and could stop Americans from communicating with each other. </p> <p> Aaron commited suicide on January 11th, 2013, when he was being charged for data theft. The procecution was described as "the product of a criminal-justice system rife with intimidation and prosecutorial overreach" by his family and many others. </p> <p> Aaron's life and his contributions to the world have been captured in the documentary The Internet's Own Boy, which has been embeded below. </p> <p> <iframe width="854" height="480" src="https://www.youtube.com/embed/vXr-2hwTk58" frameborder="0" allowfullscreen></iframe> </p> </div> <!-- /.container --> <?php include 'includes/footer.php'; ?> <?php include 'includes/js.php'; ?> </body> </html>
9a7a68c574744102757796b4445d6aa8237c737c
[ "PHP" ]
7
PHP
AyeshaIshrath/freedom-hack-site
019f92acc96a7c90995c24e48d1e3367e36f6508
c2ba94395214f15080de9fd51e091c5bfa3dbdad
refs/heads/master
<file_sep>class Shoe attr_accessor :color, :size, :material, :condition attr_reader :brand BRANDS= [].to_set def initialize(brand) @brand=brand if !(BRANDS.include?(@brands)) BRANDS << @brand end end # def brand=(brand) # @brand=brand # manyo= BRANDS.size.uniq # end # Shoe::BRANDS.clear # brands = ["Uggs", "Rainbow", "Nike", "Nike"] # brands.each do |brand| # Shoe.new(brand def cobble self.condition = "new" puts "Your shoe is as good as new!" end end <file_sep>class Book attr_accessor :author, :page_count attr_reader :title , :genre GENRES=[] def initialize(title) @title = title end def turn_page puts "Flipping the page...wow, you read fast!" end def genre=(genre) #explicity define the genre= method, #to integrate our class into the method @genre= genre GENRES<< genre end end
87f40ad33e63b4994a1f28653204434fb7b611c3
[ "Ruby" ]
2
Ruby
Mineliegoma/ruby-oo-class-variables-class-constants-nyc01-seng-ft-071320
d2f83817cac490cd24c615ab547fd16dcb5a5855
e9dc30b255608ce62dc2d0728597b18e57fffefa
refs/heads/master
<file_sep>// // TicTacToeGame.h // TicTacToe // // Created by <NAME> on 11/30/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #ifndef __TicTacToe__TicTacToeGame__ #define __TicTacToe__TicTacToeGame__ #include <iostream> using namespace std; class TicTacToeGame { private: char gameBoard[3][3]; public: TicTacToeGame(); void print(); void playerOneMove(int row, int col); void playerTwoMov(int row, int col); }; #endif /* defined(__TicTacToe__TicTacToeGame__) */ <file_sep>// // TicTacToeGame.cpp // TicTacToe // // Created by <NAME> on 11/30/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #include "TicTacToeGame.h" TicTacToeGame::TicTacToeGame() { for (int row=0; row < 3; row++) for (int col=0; col < 3; col++) gameBoard[row][col] = ' '; } void TicTacToeGame::print() { for (int row=1; row < 3; row++) { for (int col=1; col < 3; col++) { cout << gameBoard[col][row]; if (col == 1 || col == 2) // don't need a | after 3rd col cout << "|"; } // horizontal line if (row == 0 || row == 1 || row == 2) cout << endl << "-+-+-" << endl; } cout << endl << endl; } void TicTacToeGame::playerOneMove(int row, int col) { gameBoard[col][row] = 'x'; } void TicTacToeGame::playerTwoMove(int row, int col) { gameBoard[row][col] = 'o'; } <file_sep>// // main.cpp // TicTacToe // // Created by <NAME> on 11/30/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #include <iostream> #include "TicTacToeGame.h" int main() { TicTacToeGame mytttgame; print(); /* o| | -+-+- |x| -+-+- | | */ playerOneMove(1, 1); print(); playerTwoMove(0, 0); print(); playerOneMove(0, 2); print(); playerTwoMove(2, 0); return 0; }
acd4b893e663dded2c37ac06e0cc082b1f8c4d86
[ "C++" ]
3
C++
AnitaGarcia819/tic-tac-toe
b2b3a62d6bafe6b5e7e48464ba047978f5f68700
2b35917d723e8b701c3b067a5c95a4b9c2d4bc2d
refs/heads/master
<file_sep>cd ~ git clone --recursive https://github.com/FWGS/xash3d-fwgs cd xash3d-fwgs cd engine git clone https://github.com/FWGS/nanogl cd .. git clone https://github.com/ValveSoftware/halflife hlsdk/ cd ~/xash3d-fwgs/ref_gl/nanogl git clone https://github.com/FWGS/nanogl/ cd nanogl cd ~/xash3d-fwgs/ python3 ./waf configure -T release --disable-vgui --enable-gles1 --enable-gles2 --64bits --enable-poly-opt python3 ./waf build sudo rm -rf /usr/local/lib/xash3d/* sudo python3 ./waf install cd ~ git clone https://github.com/FWGS/hlsdk-xash3d cd hlsdk-xash3d python3 waf configure -T release --enable-goldsrc-support python3 waf mkdir ~/halflife cp ~/xash3d-fwgs/build/game_launch/xash3d ~/halflife/ cp ~/hlsdk-xash3d/build/dlls/hl_arm64.so ~/halflife/ cp ~/hlsdk-xash3d/build/cl_dll/client_arm64.so ~/halflife/ #delete crap rm -rf ~/hlsdk-xash3d rm -rf ~/xash3d-fwgs <file_sep># half-life on pinebook pro with few clicks [Thx](https://forum.pine64.org/showthread.php?tid=8394) ## After script ---------- Copy `valve` folder from original game to ~/halflife Go to the `valve` dir and open `liblist.gam` in a text editor. Change the line `gamedll_linux=<something>` to `gamedll_linux="hl_arm64.so"` ```bash cd ~/halflife cp hl_arm64.so valve/dlls/hl_arm64.so cp client_arm64.so valve/cl_dlls/client64.so ``` run game with ```bash LD_LIBRARY_PATH=/optvc/lib:/home/rock/halflife/:. ./xash3d -console ``` #### Bugs ---------- -cstrike multiplayer cant choose team, because we cannot build actualy dll https://github.com/FWGS/cs16-client #### fixed ---------- -`connection problem. too many lost packets` fix ingame console `cl_maxpacket 700` ## Installation other modes ---------- 1. `Blue Shift` Copy `bshift` folder from original game to `~/halflife` ```bash cd ~/halflife cp hl.so bshift/dlls/bshift.so LD_LIBRARY_PATH=/optvc/lib:/home/rock/halflife/:. ./xash3d -console -game bshift ``` 2. `Counter Strike` Copy `cstrike` folder from original game to `~/halflife` ```bash cd ~/halflife cp hl.so cstrike/dlls/cs.so LD_LIBRARY_PATH=/optvc/lib:/home/rock/halflife/:. ./xash3d -console -game cstrike ``` 3. `Opposing Force` Copy `gearbox` folder from original game to `~/halflife` ```bash cd ~/halflife cp hl.so gearbox/dlls/opfor.so LD_LIBRARY_PATH=/optvc/lib:/home/rock/halflife/:. ./xash3d -console -game gearbox ``` 4. `Team Fortress Classic` Copy `tfc` folder from original game to `~/halflife` ```bash cd ~/halflife cp hl.so tfc/dlls/tfc.so LD_LIBRARY_PATH=/optvc/lib:/home/rock/halflife/:. ./xash3d -console -game tfc ``` <file_sep>cd ~ git clone --recursive https://github.com/FWGS/xash3d cd xash3d cd engine git clone https://github.com/FWGS/nanogl cd .. git clone https://github.com/ValveSoftware/halflife mv halflife hlsdk mkdir build cd build cmake -DHL_SDK_PATH=../hlsdk/ -DXASH_VGUI=no -DXASH_NANOGL=yes -DXASH_GLES=yes .. make cd ~ mkdir halflife cp xash3d/build/engine/libxash.so halflife/ cp xash3d/build/mainui/libxashmenu.so halflife/ cp xash3d/build/game_launch/xash3d halflife/ git clone https://github.com/FWGS/hlsdk-xash3d cd hlsdk-xash3d git checkout e67d115d9d82cf2ccbcd5a1060d503fcbd3850f2 mkdir build cd build cmake ../ make cd ~ cp hlsdk-xash3d/build/cl_dll/client.so halflife/ cp hlsdk-xash3d/build/dlls/hl.so halflife/ #delete crap cd ~ rm -rf hlsdk-xash3d rm -rf xash3d
155493116a4e447512f25e2627d328686760d1e1
[ "Markdown", "Shell" ]
3
Shell
colemancda/half-life_pinebookpro
110eb95ae4fe4ec6e12928f8729136524759ae3f
9db7c87337b19c6b79a9280ae1ee4cb129921817
refs/heads/master
<file_sep>from flask import Flask, render_template from flask_bootstrap import Bootstrap import sys reload(sys) sys.setdefaultencoding('utf-8') app = Flask(__name__) Bootstrap(app) import netsim.mactrafic # db=netsim.mactrafic.builddb() # db={u'mac1':{u'mac':u'00:00:00:00:00:01', u'ip':'192.168.1.1', u'sbyI': u'1', u'sbyO':u'2'}, # u'mac2':{u'mac':u'00:00:00:00:00:02', u'ip':'192.168.1.2', u'sbyI': u'1', u'sbyO':u'2'} # } @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.route('/') def index(): return render_template('index.html') @app.route('/index2') def index2(): data=netsim.mactrafic.builddb() return render_template('index2.html',data=data) @app.route('/user/<name>') def user(name): return render_template('user.html', name=name) def run(): app.run (debug=True) if __name__=='__main__': netsim.mactrafic.populatedb() run()<file_sep>from IPython.lib.deepreload import reload as dreload __all__=['jsonObject','ip','subrange','domain'] class jsonObject(object) : _jsonKey=None def __init__(self,*arg,**attr): 'store attribute' self.__dict__.update(attr) @property def json(self): d={} d.update(vars(self)) del d[self._jsonKey] if not d : return str(self) d2={} for k in d: if hasattr(d[k],'json'): d[k]=d[k].json return {str(self):d} @classmethod def _object(clss,json): 'return an ojbect from a json file' """ could a a dict or a list of dict mix with string """ if type (json) is list: return [jsonObject._store(item) for item in json] elif type(json) is str : return jsonObject(json) elif type(json) is dict: d={} d.update(json) if len(json)==1: I,attr=d.popitem() return clss(I,**attr) class ip(jsonObject) : _jsonKey='adr' import re valid_ipv4=re.compile(r'(^|\s)((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(?=$|\s|/)') @staticmethod def extract(str): R=ip.valid_ipv4.findall(str) if len(R)==1: return R[0][1] def __init__(self,ipadr=0,**attr): 'keep adr in int or long format' self.__dict__.update(attr) if type(ipadr) is tuple: ipadr=ipadr[0] if type(ipadr) is str : ipadr=ip.extract(ipadr) self.adr=ip.int(ipadr)& 0xFFFFFFFF def __int__(self): 'return integer value of IPv4 address' return self.adr @staticmethod def int(ipval): 'return an integer from an adr-list, string or integer' if type(ipval) is int or type(ipval) is long : return ipval elif type(ipval) is str: iplst=ip.adr(ipval) elif type(ipval) is list : iplst=ipval return sum([a<<s for a,s in zip(iplst,(24,16,8,0))]) @staticmethod def str(ipval): 'return a *str* from an adr-list, string or integer' if type(ipval) is tuple: adr=ipval[0] if type(ipval) is str: return ipval elif type(ipval) is int or type(ipval) is long: adr=ip.adr(ipval) elif type(ipval) is list: adr=ipval return '.'.join([str(byte) for byte in adr]) @staticmethod def adr(ipval): 'return an address list from an adr-list, string or integer' if type(ipval) is list: return ipval elif type(ipval) is str: return [int(byte) for byte in ipval.split('.')] elif type(ipval) is int or type(ipval) is long : ipint=ipval adr=[] for shift in (24,16,8,0): b=ipint/(1<<shift) ipint=ipint- b * (1<<shift) adr.append(b) return adr def __cmp__(self,other): if int(self) > int (other) : return 1 elif int(self) < int (other) : return -1 return 0 @property def range(self): return (self.adr,32) @property def ipstr(self): return self.__str__() @property def cisco(self): return 'host ' +ip.str(self.adr) @property def top (self): 'this is to be compatible for subrange.__contains__' return self.adr def __repr__(self): return 'IP: %s' % ip.str(self.adr) def __str__(self): return ip.str(self.adr) class subrange(jsonObject) : _jsonKey='range' def __init__(self,substr='0/32',**attr): self.__dict__.update(attr) if type(substr) is str : self.range=subrange.bin(substr) elif type(substr) is tuple : msk= substr[1] net0=substr[0]&0xFFFFFFFF msk0=-1<< int(32-int(msk)) self.range=(net0 & msk0,int(msk)) # self.range -> tuple ( network-ip(int), masklen(int)) @staticmethod def bin(substr): # range[0]=network (int) # range[1]=masklen adr,msk = substr.split('/') net0=ip.int(adr)& 0xFFFFFFFF msk0=-1<< int(32-int(msk)) return (net0 & msk0,int(msk)) def __contains__(self,item): 'check if self is within other subrange(or list) or IP' if type(item) is list: return all(i in self for i in item) if isinstance(item,ip): ipval=top=item.adr else: ipval,top=item.ipval,item.top if ipval >= self.ipval and \ top <= self.top: return True return False def __len__(self): # work only for subrange < /4 (4) return pow(2,32-self.range[1]) def __int__(self): return self.range[0] def __div__(self,part): 'return a list of range divided in ceiling (binary) part' if part : d=0 while ((2**d)-part)<0: d+=1 blksize=pow(2,32-self.range[1])>>d return [subrange((self.ipval+M*blksize,self.mask+d)) \ for M in range(2**d)] def __radd__(self,subr1): 'same as add below use for a1+a2+a3+a4' return self.__add__(subr1) def __add__(self,subr2): 'return a list of added subrange (inclusive or separate)' if type(subr2) is list: subr2.append(self) return subrange.summarize(subr2) if subr2 == self or subr2 in self : return [self] if self in subr2 : return [subr2] r=[self,subr2] if self>subr2: r=[subr2,self] if self.mask == subr2.mask and \ r[1].ipval & -1<<(32-self.mask+1) == r[0].ipval : return [subrange((r[0].ipval,self.mask-1))] return r @staticmethod def addition(sr,srlist): 'addition one or many subrange from a list of subrange' if type(sr) is list: srlist.extend(sr) return subrange.summarize(srlist) elif type(sr) is subrange: return sr+srlist def __sub__(self,other): 'return a list of range(s) corresponding substracted subrange' if other not in self: return [self] if other == self: return [] ranges=[] splitranges=self/2 if other in splitranges[0]: splitranges.reverse() ranges.append(splitranges[0]) next= splitranges[1] - other if next is not None : ranges.extend(next) return sorted(ranges) @staticmethod def substract(A,B): 'substract one or many subrange from one or list of subrange' t1=isinstance(A,subrange) t2=isinstance(B,subrange) if t1 and t2 : return (A-B) if not t1 and t2 : # case [A1,A2,A3]-B (srlist-subrange) if len(A)<2: return A[0]-B SR=A[:] Si=[ s for s in A if B in s] if not Si: return SR SR.remove(Si[0]) if SR: SR+=Si[0]-B elif t1 and not t2: # case A-[B1,B2,B3] (subrange-srlist) if len(B)<2: return A-B[0] Sj=[s for s in B if s in A] if not Sj: return A SR=A-Sj[0] for s in Sj[1:]: SR=subrange.substract(SR,s) else: SR=[] for s in A: SR+=subrange.substract(s,B) return sorted(SR) def __cmp__(self,item): if self.range==item.range: return 0 if self.ipval > item.top : return 1 if item.ipval > self.top : return -1 if self.ipval == item.ipval: if self.mask > item.mask : return 1 return -1 return 1 def __mul__(self,time): 'return a list of subranges starting at base, time x' return [subrange((self.ipval+M*len(self),self.mask)) for M in range(time)] @staticmethod def summarize(srlst): 'provide a summarize list of ranges - summarization' if len (srlst)<2: return srlst srlst.sort() l=len(srlst) delta=1 while delta and l>1 : for i in range(-l,-1)[:-1]: j=i+2 srlst[i:j]=srlst[i]+srlst[i+1] srlst[-2:]=srlst[-2]+srlst[-1] delta=len(srlst)-l l+=delta return srlst @property def ipval(self): return self.range[0] @property def top (self): return int(self)+ pow(2,32-self.range[1]) -1 @property def mask (self): return self.range[1] @property def ip(self): return ip(self.range[0]) @property def ipstr(self): return str(ip(self)) @property def cisco(self): return str(self.ip)+' '+ str(subrange((-1,self.mask)).ip) def __str__(self): return '%s/%s' % (ip.str(int(self)),str(self.range[1])) def __repr__(self): return 'SR: %s' % str(self) import json def jsonWrite(dict,fname): 'write a pretty json @ fname' f=open (fname,'w') s = json.dumps(dict, sort_keys=True) f.write('\n'.join([l.rstrip() for l in s.splitlines()])) f.close() def jsonRead(fname): 'read & remove UTF formatting and return a dict' d={} f=open(fname,'r') jsonStr=f.readlines() d=json.loads(''.join(jsonStr)) return d return newobj class domain(object): """ implement an hierarchical IP domain structure,i.e. includes subdomains. This object hold the IP database of a <network>. call domain ('NAME') create relative domain if does not exist already call domain ('N1/N2/N3') create relative domains that not exist already. NAME : name of the domain (must be unique wihtin a level) path_relative=True (Default=True) each domain (path) is a singleton, i.e. created once and only. """ dir={} _path=None _attr_conv={ 'domain':(None,'path'), 'range':('subrange','json'), 'dir':(None,'json')} def __new__(cls, *args, **kwargs): names=[] if 'path' in kwargs: names=kwargs['path'].split('/') names.extend(args[0].split('/')) domain._path='/'.join(names) d=domain.find(domain._path) if d : return d return super(domain,cls).__new__(cls) def __init__(self,name,path=None,**kwargs): names=[] if path is not None: names=path.split('/') names.extend(name.split('/')) if domain.find('/'.join(names)) is not None: return self.__dict__.update(kwargs) self.name=names[-1] self._type=self.__class__.__name__ self.dir={} if len(names)>1 : path='/'.join(names[:-1]) D=domain.find(path) if not D : #'create a new domain' D=domain(path) D.dir[self.name]=self self.domain=D else: domain.dir[self.name]=self self.domain=None def __iter__(self): return iter(self.dir) def __del__(self): print '%s deleted.' % self def remove(self): 'delete current instance and subdomain' dir={} dir.update(self.dir) if dir: for d in dir: self.dir[d].remove() self.dir={} D=self.domain if D : del D.dir[self.name] else : del domain.dir[self.name] @staticmethod def find(path): 'return domain obj specified by path if it exactly exist' if path is None : return None elif path =='/' : return None currentdir=domain.dir for d in path.split('/'): if d not in currentdir: return None else: curdomain=currentdir[d] currentdir=curdomain.dir return curdomain def __repr__(self): return '*%s*'%self.path @property def path (self): 'return domain path' path=[self.name] D=self.domain while D is not None: path.append(D.name) D=D.domain return '/'.join(reversed(path)) @property def json(self): d={} d.update(vars(self)) f=self.__class__._attr_conv for attr in f : if attr in d: if isinstance(d[attr],list): d[attr].sort() d[attr]=[getattr(obj,f[attr][-1]) for obj in d[attr]] elif isinstance(d[attr],dict): d2={} for k,v in d[attr].iteritems(): d2[k]=getattr(v,f[attr][-1]) d[attr]=d2 elif d[attr] is None: d[attr]='' elif isinstance(d[attr],(ip,subrange,domain,network)) : d[attr]=getattr(d[attr],f[attr][-1]) return d def save(self): jsonWrite(self.json,self.path.replace('/','.')+'.ipdb') @staticmethod def load(name): try: fname=name.replace('/','.')+'.ipdb' d= jsonRead(fname) except: print 'file not found (%s)' % fname else: D=domain.find(name) if not D: print '[%s] newly loaded' % name return domain._store(d) else: print '[%s] newly replaced' % name D.remove() return domain._store(d) @staticmethod def _store(json): 'return the head domain object update with all sub-domain (or derivate)' #1 - first top-level object creation D=eval("%(_type)s('%(name)s',path='%(domain)s')"%json) #2 - sub-domain creation &ref dir=json['dir'] if dir : #this is a not a leaf then. for name in dir : dir[name]=domain._store(dir[name]) #3 - Parent domain reference D.domain=domain.find(json['domain']) #4 - stuff attributes General for attr in ('dir','domain') : del json[attr] D.__dict__.update(json) print D #4 - stuff **custom** attributes conversion f=D.__class__._attr_conv for k,attr in json.iteritems(): if k in f : if isinstance(attr,str): D.__dict__[k]=eval("%s('%s')" % (f[k][0],attr)) else: D.__dict__[k]=eval('%s(%s)' % (f[k][0],attr)) return D """type works this way: type(name of the class, tuple of the parent class (for inheritance, can be empty), dictionary containing attributes names and values)""" # class network (domain): # # this definition is use to convert to json # # attribute name : (object type, property to use to get json) # _attr_conv=domain._attr_conv # _attr_conv.update( # { 'ips':('ip._store','json') , # 'gateway':('ip','json'), # 'range':('subrange','json') # }) # def __repr__(self): # return '+%s+'%self.path #### MAIN ####> if __name__=='__main__': SUBRANGETST=0 DOMAINTST=0 SUBSTRACT=0 IP_IN_RANGE=0 if IP_IN_RANGE : a=ip('192.168.241.23') b=ip('192.168.241.15') c=ip('192.168.241.33') s=subrange('192.168.241.16/28') print a in s print b in s l=[a,b,c] print [i in s for i in l] print [a,b,c] in s if SUBSTRACT : A=subrange('192.168.1.40/29') B=subrange('192.168.0.40/29') C=subrange('192.168.5.40/29') D=subrange('192.168.0.160/29') K=subrange('192.168/22') L=subrange('192.168.4/22') Z=subrange('0/0') R0=K-A print R0 print 8*'-==-' R1=subrange.substract(R0,B) print R1 print 8*'-==-' R2=subrange.substract(K,[A,B,C]) print R2 print 8*'-==-' R3=subrange.substract([K,L],[A,B,C]) print R3 print 8*'-==-' print subrange.substract(subrange('192.168.4/23'),R3) if SUBRANGETST : a1=ip('10.1.1.23') a1.name='svr1' a2=ip('192.168.2.5') a3=ip('192.168.2.6') a4=ip([56,56,45,44]) r1=subrange('10.111.33.0/16') r2=subrange('10.111.45.0/24') r3=subrange('10.110.40.0/22') r4=subrange('10.110.40.0/24') HALW=subrange('10.187.1.0/25') print r1 print len(r2) print r1 in r2 print r2 in r1 print 'r3 > r4 = %s' % str(r3>r4) print 'r4 > r3 = %s' % str(r4>r3) L=[r1,r2,r3,r4] print L L.sort() print L a=subrange('10.1.0.0/16') b=subrange('10.1.80.0/20') print a-b c=subrange('10.1.255.0/24') d=subrange('10.2.0.0/24') e=subrange('10.2.1.0/24') f=subrange('10.2.1.128/27') print d+c print e+d print e+f l8=subrange('192.168.0.0/20')/32 l8[3:4]=[] subrange.summarize(l8) print print l8 l8.append (subrange ('192.168.1.128/25')) print subrange.summarize(l8) print 'r1+r2+r3+HALW', r1+r2+r3+HALW if DOMAINTST : domain('BROOKFIELD') domain('DGC') domain('DLAKE',path='DGC') domain('TOR',path='DGC') domain('AUTOM',path='DGC/DLAKE') hn=network('home') network('internet',path='home') domain('home/test') network('home/test/base') network('home/test/base2') hn.range=subrange('192.168.254.0/24') hn.ips=[ ip('192.168.254.254',name='MAIN-Asus'), ip('192.168.254.253',name='B102-Asus'), ip('192.168.254.253',name='duplicate'), ip('192.168.254.90',name='M90 Laptop') ] hn.gateway=ip('192.168.254.254') a1=ip('10.1.1.1') N=domain.find('home/test/base') jsonf=N.json jsonf['allotoe']='JG' jsonf['ips']=[ {'192.168.1.90': {'name': 'bidon1'}}, {'192.168.1.253': {'name': 'bidon2'}}, {'192.168.1.253': {'name': 'bidon3'}}, {'192.168.1.254': {'name': 'bidon4'}}] jsonf['range']='192.168.1.0/24' D=domain._store(jsonf) T=[{'192.168.1.20': {'nom': 'serveur no1'}},'192.168.1.19'] ip._store(T) <file_sep>from IPython.lib.deepreload import reload as dreload from ip import * class interface(jsonObject) : 'implémente interface logique' _jsonKey='intf' def __init__(self,ifstr='0/32',name=None,**attr): self.__dict__.update(attr) self.name=name if type(ifstr) is str : self.intf=interface._bin(ifstr) elif type(ifstr) is tuple : msk= ifstr[1] net0=ifstr[0]&0xFFFFFFFF # msk0=-1<< int(32-int(msk)) self.intf=(net0 ,int(msk)) self.network=network(ifstr) @property def ip(self): return ip(self.intf[0]) @staticmethod def _bin(ifstr): adr,msk = ifstr.split('/') net0=ip.int(adr)& 0xFFFFFFFF # msk0=-1<< int(32-int(msk)) return (net0 ,int(msk)) def __str__(self): return '%s/%s' % (ip.str(self.intf[0]),str(self.intf[1])) def __repr__(self): return 'IF: %s' % str(self) class network(subrange): 'implémente réseau logique' def __repr__(self): return 'NW: %s' % str(self) class router(object) : 'implémente router' db={} links=[] def __new__(clss,*args,**kwargs): pass def __init__(self,id): self.id=id class link : list={} def __init__(self,id=None,endpoints=(None,None)): self.endpoints=endpoints self.id=id link.list[id]=self def __repr__(self): return '<-> %s'%self.id if __name__=='__main__': s1='192.168.254.3/24' s2='192.168.254.3 255.255.255.0' <file_sep>from datetime import datetime import json class Cumul(object): 'implement traffic totalizer' """ implement byte counters """ db={} def __init__(self,name=None): self.since=datetime.now() self.DateUpdated=None self._bytesIn=0 self._bytesOut=0 if name: self.name=name if name not in Cumul.db: Cumul.db[name]={'InTot':0,'OutTot':0} @property def bytesIn(self): return self._bytesIn @bytesIn.setter def bytesIn(self,value): if self.name : C=Cumul.db[self.name] C['InTot']+= -self._bytesIn+value self._bytesIn=value @property def bytesOut(self): return self._bytesOut @bytesOut.setter def bytesOut(self,value): if self.name : C=Cumul.db[self.name] C['OutTot']+= -self._bytesOut+value self._bytesOut=value def update(self, **kwargs): bytesInDelta=0 bytesOutDelta=0 if 'bytesInDelta' in kwargs: bytesInDelta=kwargs['bytesInDelta'] self.bytesInDelta+=byteInDelta if 'bytesOutDelta' in kwargs: bytesOutDelta=kwargs['bytesOutDelta'] self.bytesOutDelta+=bytesOutDelta if bytesInDelta or bytesOutDelta : self.DateUpdated=datetime.now() def __repr__(self): return '+=(%(name)s) in:%(_bytesIn)i out:%(_bytesOut)i'% vars(self) class Device(object): db={} def __init__(self,adr,name=None): self.TS_created=datetime.now() self.TS_updated=None self.mac=adr self.name=name self.counters=[Cumul('month')] Device.db[adr]=self # def __cmp__(self): def __repr__(self): return 'Dev>%s'%self.mac def bytesize(bytes,precision=3): 'return a compact string (5bytes) that summurize size in bytes' E=0 while bytes>pow(1024,E+1): E+=1 M=bytes*1./pow(1024,E) if M>999: E+=1 M/=1024 if E : if M>9.9: m=round(M,0) return '%3i %s'% (m,'BKMGT'[E]) else: m=round(M,1) return '%2.1f %s'% (m,'BKMGT'[E]) else: return '%3i B'% bytes def newMAC(serial=0): # generator while True: serial+=1 h='%012x'%serial mac=':'.join([''.join(b) for b in zip(h[::2],h[1::2])]) yield(mac) # '00:00:00:00:00:01' def populatedb(): # create bunch of Device DGen=newMAC() from random import random randombytes=lambda e:int(pow(10,(2+e*random()))) import ip adrip=ip.ip('192.168.1.254') for d in range (30): D=Device(DGen.next()) D.counters[0].bytesIn=randombytes(9) D.counters[0].bytesOut=randombytes(8) D.ip=adrip adrip=ip.ip(adrip.adr-1) def builddb(): db={'devices':[]} devices=Device.db.values() devices.sort(key=lambda d: d.counters[0].bytesIn+d.counters[0].bytesOut,reverse=True) for d in devices: db['devices'].append( {'mac':d.mac, 'ip':d.ip, 'sbyI':bytesize(d.counters[0].bytesIn), 'sbyO':bytesize(d.counters[0].bytesOut), 'DS_tot':d.counters[0].since }) db['sum']={ 'InT':bytesize(Cumul.db['month']['InTot']), 'OutT':bytesize(Cumul.db['month']['OutTot']) } return db def show(db): print '----- MAC ------ -----IP------ -In-- -Out-' for d in db['devices']: print '%(mac)s %(ip)-13s %(sbyI)s %(sbyO)s'% d print 43*'-' print ' TOT: %5s %5s'%\ (bytesize(Cumul.db['month']['InTot']), bytesize(Cumul.db['month']['OutTot'])) if __name__=='__main__': populatedb() db=builddb() show(db)
d4fbb8f656a9f029d49c8d7e0178f4a57e3e92f2
[ "Python" ]
4
Python
quenneville/flasky
0c9f6341ea351bdea2add467a411550ec7d7c860
d1576b807698871163a4048cdc510058f22c7dea
refs/heads/master
<file_sep># Ejercicio de patrones ## Apartados ## [Apartado A](https://github.com/SrBlimp/PracPatrones2018/blob/master/src/ApartatA/Apartado%20A.txt) ## [Apartado B](https://github.com/SrBlimp/PracPatrones2018/tree/master/src/ApartatB) ## [Apartado C](https://github.com/SrBlimp/PracPatrones2018/tree/master/src/ApartatC) ## [Apartado D](https://github.com/SrBlimp/PracPatrones2018/commit/45811cd3b2b9bef7227fe67dcaafd799c76ff038) (Aplicado sobre el apartado B y C) ## Authors * **<NAME>** - [SrBlimp](https://github.com/SrBlimp) * **<NAME>** - [yqz1](https://github.com/yqz1) * **<NAME>** - [AloitR](https://github.com/AloitR) <file_sep>package ApartatB; import java.util.ArrayList; import java.util.List; public class MachineComposite extends MachineComponent { private List<MachineComponent> components = new ArrayList<>(); public void addComponent(MachineComponent mc) { components.add(mc); } @Override public boolean isBroken() { if (broken) { return true; } for (MachineComponent mc: components) { if (mc.isBroken()) { return true; } } return false; } } <file_sep>package ApartatC; import java.util.Observable; public abstract class MachineComponent extends Observable { protected boolean broken = false; public void setBroken() { broken = true; } public void repair() { broken = false; } public abstract boolean isBroken(); }<file_sep>package ApartatC; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; public class MachineComposite extends MachineComponent implements Observer { private List<MachineComponent> components = new ArrayList<>(); // BrokenComponents list to save if we have any components broken private List<MachineComponent> brokenComponents = new ArrayList<>(); private boolean brokentest = false; public void addComponent(MachineComponent mc) { components.add(mc); mc.addObserver(this); if(mc.isBroken()) { notifyChanges(); } } @Override public void setBroken() { if (!isBroken()) { super.setBroken(); notifyChanges(); } } @Override public void repair() { if (isBroken()) { for (MachineComponent mc: brokenComponents) { mc.repair(); } super.repair(); notifyChanges(); } } @Override public boolean isBroken() { // Update list of broken components updateSubComponentsBroken(); return broken || brokenComponents.size() > 0; } @Override public void update(Observable o, Object arg) { MachineComponent mc = (MachineComponent) o; if (mc.isBroken()) { setBrokenComponent(mc); } else { repairBrokenSubComponent(mc); } } /** * Update list of brokenComponents to be up to date of the * broken components */ private void updateSubComponentsBroken() { for (MachineComponent mc: components) { if (mc.isBroken()) { brokenComponents.add(mc); } } } /** * Set broken the component passed by parameter and check * if the component is not broken to notify the observers * @param mc */ private void setBrokenComponent(MachineComponent mc) { // Add the component to the broken components list brokenComponents.add(mc); // Check if the component is broken, if component is not broken notify // the observers if (isBroken()) { notifyChanges(); } } /** * Repair the subComponent passed by parameter and check * if the component is not broken to notify the observers * @param mc */ private void repairBrokenSubComponent(MachineComponent mc) { // Remove component from the list of brokenComponents brokenComponents.remove(mc); // Check if the component is broken, if component is not broken notify // the observers if (!isBroken()) { notifyChanges(); } } private void notifyChanges() { setChanged(); notifyObservers(); } }<file_sep>package ApartatC; public class Machine extends MachineComponent { @Override public boolean isBroken() { return broken; } @Override public void setBroken() { if (!isBroken()) { super.setBroken(); // We have to mark as changed the broken value setChanged(); // Notify all the components that are observing notifyObservers(); } } @Override public void repair() { if (isBroken()) { super.repair(); // We have to mark as changed the broken value setChanged(); // Notify all the components that are observing notifyObservers(); } } }
8fac09f655e401c35a44373409d504cd032cb6e3
[ "Markdown", "Java" ]
5
Markdown
SrBlimp/PracPatrones2018
da1a973e181a9a942466380d493d5540c1883986
4ffaa7b39828dcd718ea29cace2937e613605cb7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PotterShoppingCart.Tests { public class PotterShoppingCart { private const int BOOK_PRICE = 100; private static readonly Dictionary<int, double> SUITE_DISCOUNT = new Dictionary<int, double> { {1, 0}, {2, 0.05}, {3, 0.1}, {4, 0.2}, {5, 0.25} }; public static int CalculateTotalPrice(Dictionary<string, int> books) { var totalPrice = 0; while (books.Count > 0) { var suiteSize = books.Count; var suiteAmout = books.Min(x => x.Value); var discount = SUITE_DISCOUNT[suiteSize]; var oneSuitePrice = (int)(BOOK_PRICE * suiteSize * (1 - discount)); totalPrice += oneSuitePrice * suiteAmout; //算過的從 books 中移掉 books = books.ToDictionary(x => x.Key, x => x.Value - suiteAmout) .Where(x => x.Value > 0) .ToDictionary(x => x.Key, x => x.Value); } return totalPrice; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace PotterShoppingCart.Tests { [TestClass()] public class PotterShoppingCartTests { [TestMethod()] public void CalculateTotalPriceTest_第一集1本_預計回傳100() { //Arrange var books = new Dictionary<string, int>() { { "哈利波特_1", 1} }; var expected = 100; //Act var actual = PotterShoppingCart.CalculateTotalPrice(books); //Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void CalculateTotalPriceTest_第一集1本_第二集1本_預計回傳190() { //Arrange var books = new Dictionary<string, int>() { { "哈利波特_1", 1}, { "哈利波特_2", 1} }; var expected = 190; //Act var actual = PotterShoppingCart.CalculateTotalPrice(books); //Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void CalculateTotalPriceTest_第一集1本_第二集1本_第三集1本_預計回傳270() { //Arrange var books = new Dictionary<string, int>() { { "哈利波特_1", 1}, { "哈利波特_2", 1}, { "哈利波特_3", 1} }; var expected = 270; //Act var actual = PotterShoppingCart.CalculateTotalPrice(books); //Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void CalculateTotalPriceTest_第一集1本_第二集1本_第三集1本_第四集1本_預計回傳320() { //Arrange var books = new Dictionary<string, int>() { { "哈利波特_1", 1}, { "哈利波特_2", 1}, { "哈利波特_3", 1}, { "哈利波特_4", 1}, }; var expected = 320; //Act var actual = PotterShoppingCart.CalculateTotalPrice(books); //Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void CalculateTotalPriceTest_第一集1本_第二集1本_第三集1本_第四集1本_第五集1本_預計回傳375() { //Arrange var books = new Dictionary<string, int>() { { "哈利波特_1", 1}, { "哈利波特_2", 1}, { "哈利波特_3", 1}, { "哈利波特_4", 1}, { "哈利波特_5", 1}, }; var expected = 375; //Act var actual = PotterShoppingCart.CalculateTotalPrice(books); //Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void CalculateTotalPriceTest_第一集1本_第二集1本_第三集2本_預計回傳370() { //Arrange var books = new Dictionary<string, int>() { { "哈利波特_1", 1}, { "哈利波特_2", 1}, { "哈利波特_3", 2}, }; var expected = 370; //Act var actual = PotterShoppingCart.CalculateTotalPrice(books); //Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void CalculateTotalPriceTest_第一集1本_第二集2本_第三集2本_預計回傳460() { //Arrange var books = new Dictionary<string, int>() { { "哈利波特_1", 1}, { "哈利波特_2", 2}, { "哈利波特_3", 2}, }; var expected = 460; //Act var actual = PotterShoppingCart.CalculateTotalPrice(books); //Assert Assert.AreEqual(expected, actual); } } }
db6479f411a73ee770054fbe90676a32d7c9a527
[ "C#" ]
2
C#
mystic01/PotterShoppingCart2
82f66b90c2d80c6576229ca5a37e2ac36f27fab1
5dd42c175e774912e2b5b6ba19e978bfca7d007b
refs/heads/master
<repo_name>Gyu-won/OSP_06<file_sep>/py_lab2/my_pkg/set.py #!/usr/bin/python def input2_data(): list_1 = [] list_2 = [] s = input("1st list: ") s = s.lstrip('[') s = s.rstrip(']') list_1 = list(map(int, s.split(','))) s = input("2nd list: ") s = s.lstrip('[') s = s.rstrip(']') list_2 = list(map(int, s.split(','))) union(list_1, list_2) intersection(list_1, list_2) def union(a, b): set1 = set(a) set2 = set(b) value = list(set1 | set2) print('=> union ', end='') print(value) def intersection(a, b): set1 = set(a) set2 = set(b) value = list(set1 & set2) print('=> intersection ', end='') print(value) <file_sep>/py_lab2/myprog_pkg.py #!/usr/bin/python from my_pkg.conversion import input1_data from my_pkg.set import input2_data while True: num = int(input('Select menu: 1)conversion 2)union/intersection 3)exit ? ')) if num == 1: input1_data() if num == 2: input2_data() if num == 3: print('exit the program...') break <file_sep>/py_lab2/my_pkg/conversion.py #!/usr/bin/python def input1_data(): n = input('input binary number: ') oct(n) dec(n) hex(n) def oct(num): n = 0 for i in range(len(num)): n += ((int(((int(num)) % (10 ** (i+1))) / (10 ** i))) * (2 ** i)) value = "{0:o}".format(n) print('=> OCT> ' + value) def dec(num): value = 0 for i in range(len(num)): value += ((int(((int(num)) % (10 ** (i+1))) / (10 ** i))) * (2 ** i)) print('=> DEC> ' + (str(value))) def hex(num): n = 0 for i in range(len(num)): n += ((int(((int(num)) % (10 ** (i+1))) / (10 ** i))) * (2 ** i)) value = "{0:X}".format(n) print('=> HEX> ' + value) if __name__ == '__main__': print("메인함수 실행")
a0959dd9d809ea6e5120c71a0dd7c50b29249b9d
[ "Python" ]
3
Python
Gyu-won/OSP_06
54b8b0395c3a2af5e822630b9bdccfbf9bb0b253
71a34291dcb286a505e06a3e84e045155806b9c2
refs/heads/master
<repo_name>jkufro/LazySorry<file_sep>/LazySorry/ContentView.swift // // ContentView.swift // LazySorry // // Created by <NAME> on 7/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct ContentView: View { @ObservedObject var lazySorryVM: LazySorryViewModel @State var topCardRotation:Double = 90.0 @State var topCardOffset:CGSize = CGSize(width: 0, height: -300) init() { lazySorryVM = LazySorryViewModel() } var body: some View { VStack { Spacer() ZStack { ForEach(0 ..< lazySorryVM.drawnCards.count) { CardView(imageName: self.lazySorryVM.drawnCards[$0]) } // https://www.hackingwithswift.com/quick-start/swiftui/how-to-start-an-animation-immediately-after-a-view-appears CardView(imageName: self.lazySorryVM.topCard) .onTapGesture { self.topCardRotation = 90 self.topCardOffset = CGSize(width: 0, height: -300) self.lazySorryVM.drawCardTrigger() withAnimation { self.topCardRotation = 0 self.topCardOffset = CGSize.zero } } .rotation3DEffect(.degrees(topCardRotation), axis: (x: 1, y: 0.3, z: 0)) .offset(x: topCardOffset.width, y: topCardOffset.height) .animation(.easeInOut) .onAppear { _ = Animation.easeInOut(duration: 0.5) return withAnimation { self.topCardRotation = 0 self.topCardOffset = CGSize.zero } } } Spacer() HStack { Spacer() Text( String("\(lazySorryVM.deck.numPlayingCardsLeft()) cards left until shuffle") ) .font(.custom("PaytoneOne-Regular", size: 18)) Spacer() } Spacer() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep>/LazySorry/View Models/LazySorryViewModel.swift // // LazySorryViewModel.swift // LazySorry // // Created by <NAME> on 7/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation import SwiftUI import AVFoundation class LazySorryViewModel: ObservableObject { static let drawCooldown:Int = 750 // milliseconds that must pass between draws @Published var deck: Deck @Published var drawnCards:[String] // track a short history of cards drawn var topCard:String = "back_of_card" @Published var topCardDegrees:Double = 0.0 var lastDraw:Int = Int(Date().timeIntervalSince1970 * 1_000) var avPlayer:AVAudioPlayer? init() { self.deck = Deck() self.drawnCards = ["back_of_card", "back_of_card", "back_of_card", "back_of_card", "back_of_card", "back_of_card", "back_of_card"] } func drawCardTrigger() { guard (self.isDrawCooledDown()) else { let generator = UINotificationFeedbackGenerator() generator.notificationOccurred(.error) return } // make sure the deck is not empty if (self.deck.isPlayingDeckEmpty()) { self.deck.newPlayingDeck() self.playShuffleSound() } else { self.playDrawSound() } // draw a card self.topCardDegrees = 90.0 self.drawnCards.append(self.topCard) self.topCard = self.deck.drawCard() self.drawnCards.removeFirst() self.lastDraw = Int(Date().timeIntervalSince1970 * 1_000) self.topCardDegrees = 0.0 } private func isDrawCooledDown() -> Bool { return (Int(Date().timeIntervalSince1970 * 1_000) - self.lastDraw) >= LazySorryViewModel.drawCooldown } // https://www.hackingwithswift.com/example-code/media/how-to-play-sounds-using-avaudioplayer private func playShuffleSound() { var options:[String] = [ "shuffle_1" ] options.shuffle() let resourceName:String = options[0] let path = Bundle.main.path(forResource: resourceName, ofType: "mp3")! let url = URL(fileURLWithPath: path) do { self.avPlayer = try AVAudioPlayer(contentsOf: url) self.avPlayer?.play() } catch { // couldn't load file :( } } private func playDrawSound() { var options:[String] = [ "pickup_3", "pickup_4", "pickup_5", "pickup_6", ] options.shuffle() let resourceName:String = options[0] let path = Bundle.main.path(forResource: resourceName, ofType: "mp3")! let url = URL(fileURLWithPath: path) do { self.avPlayer = try AVAudioPlayer(contentsOf: url) self.avPlayer?.play() } catch { // couldn't load file :( } } } <file_sep>/LazySorry/Views/ExitingCardView.swift // // ExitingCardView.swift // LazySorry // // Created by <NAME> on 7/10/20. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct ExitingCardView: View { var body: some View { Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) } } struct ExitingCardView_Previews: PreviewProvider { static var previews: some View { ExitingCardView() } } <file_sep>/LazySorry/Views/CardView.swift // // CardView.swift // LazySorry // // Created by <NAME> on 7/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import SwiftUI struct CardView: View { let imageName: String @State var rotationDegrees:Double = 0.0 @State private var offset = CGSize.zero var body: some View { ZStack { if (imageName == "") { EmptyView() } else { Image(imageName) .resizable() .aspectRatio(contentMode: .fit) // https://www.hackingwithswift.com/books/ios-swiftui/moving-views-with-draggesture-and-offset .offset(x: offset.width, y: offset.height) .gesture( DragGesture() .onChanged { gesture in self.offset = gesture.translation } .onEnded { _ in self.offset = CGSize.zero } ) .padding() .shadow(radius: 10) .animation(.spring()) } } } } struct CardView_Previews: PreviewProvider { static var previews: some View { CardView(imageName: "1", rotationDegrees: 0.0) } } <file_sep>/LazySorry/Models/Deck.swift // // Deck.swift // LazySorry // // Created by <NAME> on 7/9/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation class Deck { // The modern deck contains 45 cards: there are five 1 cards as well as four // each of the other cards (Sorry!, 2, 3, 4, 5, 7, 8, 10, 11 and 12). // The 6s or 9s are omitted to avoid confusion with each other. static let baseTruthDeck:[String] = [ "1", "1", "1", "1", "1", "2", "2", "2", "2", "3", "3", "3", "3", "4", "4", "4", "4", "5", "5", "5", "5", "7", "7", "7", "7", "8", "8", "8", "8", "10", "10", "10", "10", "11", "11", "11", "11", "12", "12", "12", "12", "sorry", "sorry", "sorry", "sorry", ] private var playingDeck:[String] = [] func isPlayingDeckEmpty() -> Bool { return self.playingDeck.count == 0 } func newPlayingDeck() { self.playingDeck = Deck.baseTruthDeck self.playingDeck.shuffle() } func drawCard() -> String { if (self.isPlayingDeckEmpty()) { return "" } return self.playingDeck.remove(at: 0) } func numPlayingCardsLeft() -> Int { return self.playingDeck.count } }
bee730f9ef7c3557525ad3172e79c936c91f79a9
[ "Swift" ]
5
Swift
jkufro/LazySorry
e4b2ce8d538ceec1c6e418efe20be89e6b15e754
ad36ef653c7eb49541720113de0ad70b60ff0c1f
refs/heads/master
<file_sep>/*global $ */ $(function () { 'use strict'; $('html').niceScroll({ cursorcolor: "#CCC", cursorwidth: 5, scrollspeed: 40, mousescrollstep: 40, background: "#FFF", cursorborder: "none", autohidemode: false, zindex: 99999 }); }); $(function () { 'use strict'; $('.closeBtn').click(function () { $('.guideWindow').hide(); }); }); $(function () { 'use strict'; $('.guideBg').stop().animate({ 'opacity' : '0.9' }, 1000); }); var scene02Num = 1; var scene03Num = 1; var scene05Num = 1; var scene06_1Num = 1; var scene06_2Num = 1; var scene07Num = 1; /*----------- not repeated animation-----------*/ $(function () { 'use strict'; $(window).scroll(function () { var scrollTop = $(document).scrollTop(); /*-------------scene02 Animation-----------*/ if (scrollTop > 400 && scene02Num === 1) { /*-------BG-------*/ scene02Num = 0; $('.page02 .bgPtt01').stop().animate({ 'opacity': '1', 'margin-top': '0px' }, 700); $('.page02 .bgPtt02').stop().delay(200).animate({ 'opacity': '1', 'margin-top': '0px' }, 800); $('.page02 .bgPtt03').stop().delay(500).animate({ 'opacity': '1', 'margin-top': '0px' }, 900); /*------Title-------*/ $('.page02 .titleNum').stop().animate({ 'opacity': '1' }, 1000); $('.page02 .titleSmall').stop().delay(100).animate({ 'opacity': '1', 'margin-left': '844px' }, 700); $('.page02 .titleBig').stop().delay(200).animate({ 'opacity': '1', 'margin-left': '664px' }, 900); $('.page02 .line').stop().delay(100).animate({ 'height': '64px' }, 1000); $('.page02 .bodytext').stop().delay(500).animate({ 'opacity': '1', 'margin-top': '269px' }, 900); } /*--------scene03 Title Animation----------*/ if (scrollTop > 1400 && scene03Num === 1) { scene03Num = 0; $('.page03 .titleNum').stop().animate({ 'opacity': '1' }, 1000); $('.page03 .titleSmall').stop().delay(100).animate({ 'opacity': '1', 'margin-left': '460px' /*30*/ }, 700); $('.page03 .titleBig').stop().delay(200).animate({ 'opacity': '1', 'margin-left': '457px' /*30*/ }, 900); $('.page03 .bodytext').stop().delay(400).animate({ 'opacity': '1', 'margin-top': '343px' /*20*/ }, 1000); /*------rightCar------*/ $('.page03 .rightCarbg').stop().delay(500).animate({ 'opacity': '1', 'margin-top': '100px', 'margin-left': '910px' }, 1000); $('.page03 .rightCar').stop().delay(700).animate({ 'opacity': '1', 'margin-top': '258px', 'margin-left': '999px' }, 700); $('.page03 .rightCarS_1').stop().delay(1000).animate({ 'opacity': '1', 'margin-top': '365px', 'margin-left': '897px' }, 1000); $('.page03 .rightCarS_2').stop().delay(900).animate({ 'opacity': '1', 'margin-top': '390px', 'margin-left': '1072px' }, 1000); } /*--------scene05 Title Animation----------*/ if (scrollTop > 2680 && scene05Num === 1) { scene05Num = 0; $('.page05 .titleNum').stop().animate({ 'opacity': '1', 'margin-left': '894px' }, 1000); $('.page05 .titleSmall').stop().delay(100).animate({ 'opacity': '1', 'margin-left': '951px' }, 700); $('.page05 .titleBig').stop().delay(200).animate({ 'opacity': '1' }, 900); $('.page05 .bodytext').stop().delay(400).animate({ 'opacity': '1', 'margin-top': '344px' }, 1000); } /*--------scene06 Animation----------*/ if (scrollTop > 3950 && scene06_1Num === 1) { scene06_1Num = 0; /*---Left Car---*/ $('.page06 .leftCarM').stop().animate({ 'opacity': '1', 'top': '-175px' }, 1000); $('.page06 .leftCarS').stop().delay(500).animate({ 'opacity': '1', 'left': '67px' }, 700); $('.page06 .leftCar').stop().delay(400).animate({ 'opacity': '1', 'left': '99px' }, 1000); } if (scrollTop > 4320 && scene06_2Num === 1) { scene06_2Num = 0; /*---Title---*/ $('.page06 .titleNum').stop().animate({ 'opacity': '1', 'margin-left': '914px' }, 1000); $('.page06 .titleSmall').stop().delay(100).animate({ 'opacity': '1', 'margin-left': '969px' }, 700); $('.page06 .titleBig').stop().delay(200).animate({ 'opacity': '1' }, 900); $('.page06 .bodytext').stop().delay(400).animate({ 'opacity': '1', 'margin-top': '345px' }, 1000); } /*--------scene07 Title Animation----------*/ if (scrollTop > 5320 && scene07Num === 1) { scene07Num = 0; /*---title---*/ $('.page07 .titleNum').stop().animate({ 'opacity': '1' }, 1000); $('.page07 .titleSmall').stop().delay(100).animate({ 'opacity': '1', 'margin-left': '459px' }, 700); $('.page07 .titleBig').stop().delay(200).animate({ 'opacity': '1', 'margin-left': '461px' }, 900); $('.page07 .titleBigSub').stop().delay(300).animate({ 'opacity': '1', 'margin-left': '461px' }, 1000); $('.page07 .bodytext').stop().delay(400).animate({ 'opacity': '1', 'margin-top': '388px' }, 1000); /*---Price Banner---*/ $('.page07 .bannerT').stop().delay(1100).animate({ 'opacity': '1', 'margin-top': '380px', 'margin-left': '1025px' }, 400); $('.page07 .bannerM_1').stop().delay(800).animate({ 'opacity': '1', 'margin-top': '385px', 'margin-left': '1025px' }, 700); $('.page07 .bannerM_2').stop().delay(1000).animate({ 'opacity': '1', 'margin-top': '385px', 'margin-left': '1025px' }, 500); $('.page07 .bannerS').stop().delay(1300).animate({ 'opacity': '1', 'margin-top': '385px', 'margin-left': '1025px' }, 1000); /*---rightCar---*/ $('.page07 .rightCarM').stop().delay(500).animate({ 'opacity': '1', 'margin-top': '203px', 'margin-left': '1265px' }, 1000); $('.page07 .rightCar').stop().delay(700).animate({ 'opacity': '1', 'margin-top': '481px', 'margin-left': '1005px' }, 700); $('.page07 .rightCarS').stop().delay(900).animate({ 'opacity': '1', 'margin-top': '696px', 'margin-left': '377px' }, 1000); } }); }); /*--Repeated horizontal animation via Mouse Xposition--*/ $(function () { 'use strict'; $(document).mousemove(function (event) { $('.page01 .obj01').stop().animate({'margin-left': (event.pageX - 10) * 0.04}, 300); $('.page01 .obj02').stop().animate({'margin-left': (-(event.pageX - 10) * 0.06)}, 400); /*-- $('.page06 .leftCarM').stop().animate({'margin-left':(-(event.pageX-10)*0.012)}, 500); $('.page06 .leftCarS').stop().animate({'margin-left':(-(event.pageX-10)*0.012)}, 500); $('.page06 .leftCar').stop().animate({'margin-left':(-(event.pageX-10)*0.012)}, 500); --*/ }); }); /*--Repeated vertical Animation via Scroll position--*/ $(function () { 'use strict'; $(window).scroll(function () { var scrollTop = $(document).scrollTop(); $('.page04 .rbCar').stop().animate({'margin-left': (scrollTop - 3500) * 0.2}, 500); $('.page04 .rbTxt').stop().animate({'margin-left': (-(scrollTop - 2000) * 0.03)}, 1000); $('.page05 .obj01').stop().animate({'margin-top': (-(scrollTop - 3100) * 0.1)}); $('.page05 .obj02').stop().animate({'margin-top': ((scrollTop - 4000) * 0.05)}, 300, 'swing'); $('.page05 .obj01_s').stop().animate({'margin-top': (-(scrollTop - 3100) * 0.08)}); $('.page05 .obj02_s').stop().animate({'margin-top': ((scrollTop - 4000) * 0.03)}, 300, 'swing'); }); }); /*--Scroll easing effect--*/ $(function () { 'use strict'; $('a').click(function () { $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top }, 1000, 'easeInOutExpo'); return false; }); }); /*--GNB--*/ $(function () { /*--mouseOver image change--*/ 'use strict'; $('#menu01').hover( function () {$('#menu01').css('background', 'url(image/gnb/01main_over.png)'); }, function () {$('#menu01').css('background', 'url(image/gnb/01main.png)'); } ); $('#menu02').hover( function () { $('#menu02').css('background', 'url(image/gnb/02vr_over.png)'); }, function () { $('#menu02').css('background', 'url(image/gnb/02vr.png)'); } ); $('#menu03').hover( function () { $('#menu03').css('background', 'url(image/gnb/03exterior_over.png)'); }, function () { $('#menu03').css('background', 'url(image/gnb/03exterior.png)'); } ); $('#menu04').hover( function () {$('#menu04').css('background', 'url(image/gnb/04interior_over.png)'); }, function () {$('#menu04').css('background', 'url(image/gnb/04interior.png)'); } ); $('#menu05').hover( function () {$('#menu05').css('background', 'url(image/gnb/05space_over.png)'); }, function () {$('#menu05').css('background', 'url(image/gnb/05space.png)'); } ); $('#menu06').hover( function () {$('#menu06').css('background', 'url(image/gnb/06spec_over.png)'); }, function () {$('#menu06').css('background', 'url(image/gnb/06spec.png)'); } ); /*--Image change via page (location)--*/ $(window).scroll(function () { var scrollTop = $(document).scrollTop(); if (scrollTop >= 0 && scrollTop < 950) { $('#menu01').css('background', 'url(image/gnb/01main_over.png)'); } else { $('#menu01').css('background', 'url(image/gnb/01main.png)'); } if (scrollTop >= 950 && scrollTop < 1950) { $('#menu02').css('background', 'url(image/gnb/02vr_over.png)'); } else { $('#menu02').css('background', 'url(image/gnb/02vr.png)'); } if (scrollTop >= 1950 && scrollTop < 3230) { $('#menu03').css('background', 'url(image/gnb/03exterior_over.png)'); } else { $('#menu03').css('background', 'url(image/gnb/03exterior.png)'); } if (scrollTop >= 3230 && scrollTop < 4820) { $('#menu04').css('background', 'url(image/gnb/04interior_over.png)'); } else { $('#menu04').css('background', 'url(image/gnb/04interior.png)'); } if (scrollTop >= 4820 && scrollTop < 5820) { $('#menu05').css('background', 'url(image/gnb/05space_over.png)'); } else { $('#menu05').css('background', 'url(image/gnb/05space.png)'); } if (scrollTop >= 5820) { $('#menu06').css('background', 'url(image/gnb/06spec_over.png)'); } else { $('#menu06').css('background', 'url(image/gnb/06spec.png)'); } }); }); <file_sep>$(document).ready(function () { 'use strict'; $('html').niceScroll({ cursorcolor: "#CCC", cursorwidth: 5, scrollspeed: 40, mousescrollstep: 40, background: "#FFF", cursorborder: "none", autohidemode: false, zindex: 99999 }); }); /*--Scroll easing effect--*/ $(document).ready(function () { 'use strict'; $('a').click(function () { $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top }, 800, 'easeInOutExpo'); return false; }); }); $(document).ready(function () { 'use strict'; $('.nav_icon').click(function () { $(this).toggleClass('open'); }); });
3adaee62ea5edb32883690e7d77efdd3476d06a9
[ "JavaScript" ]
2
JavaScript
eugeneseo-ixd/eugeneseo-ixd.github.io
eee2b5c4f521719ba027f3db82d61996e28a0d7c
6d26661259e5325f5610d7f0a2c5eb5fd6028e9e
refs/heads/master
<repo_name>robobrobro/spaceship<file_sep>/spaceship.js var G_ASTEROID_MAX_TRIES = 3; // max number of times to attempt to spawn var G_ASTEROID_HEIGHT_MAX = 100; // in pixels var G_ASTEROID_HEIGHT_MIN = 5; // in pixels var G_ASTEROID_WIDTH_MAX = 100; // in pixels var G_ASTEROID_WIDTH_MIN = 5; // in pixels var G_ASTEROID_MAX = 100; // max number of asteroids at one time var G_ASTEROID_ROTATION_SPEED_MAX = 5; // in degrees per frame var G_ASTEROID_ROTATION_SPEED_MIN = 0.1; // in degrees per frame var G_ASTEROID_SPAWN_EDGE = { "BOTTOM": 0, "BOTTOMLEFT": 1, "BOTTOMRIGHT": 2, "LEFT": 3, "RIGHT": 4, "TOP": 5, "TOPLEFT": 6, "TOPRIGHT": 7 } var G_ASTEROID_SPAWN_EDGES = 8; var G_ASTEROID_SPAWN_RATE = 500; // in milliseconds var G_ASTEROID_SPEED_MAX = 1; // in pixels per frame var G_ASTEROID_SPEED_MIN = 0.1; // in pixels per frame var G_ASTEROID_VERTICES_MAX = 20; var G_ASTEROID_VERTICES_MIN = 7; var G_BULLET_FIRE_WAIT = 100; // in milliseconds var G_BULLET_LENGTH = 5; // in pixels var G_BULLET_LIFE_TIME = 3000; // in milliseconds var G_BULLET_MAX = 500; // max number of bullets at one time var G_BULLET_SPEED = 12; // in pixels per frame var G_BULLET_WIDTH = 2; // in pixels var G_CANVAS_ID = "canvas"; var G_CANVAS_WIDTH = 800; var G_CANVAS_HEIGHT = 600; var G_KEY_A = 65; var G_KEY_D = 68; var G_KEY_G = 71; var G_KEY_H = 72; var G_KEY_P = 80; var G_KEY_S = 83; var G_KEY_SPACE = 32; var G_KEY_W = 87; var G_HUD_FONT_HEIGHT = 20; var G_HUD_ITEM_X_OFFSET = 20; var G_MSEC_PER_FRAME = 33; var G_SCORE_DEATH_PENALTY = 1000; var G_SCORE_ASTEROID_HIT = 10; var G_SHIP_BACKWARD_SPEED = 1.2; // in pixels per frame var G_SHIP_FILL_STYLES = [ "#000000", "#110000", "#220000", "#330000", "#440000", "#550000", "#660000", "#770000", "#880000", "#990000", "#aa0000", "#bb0000", "#cc0000", "#dd0000", "#ee0000", "#ff0000" ]; var G_SHIP_FORWARD_SPEED = 4.5; // in pixels per frame var G_SHIP_HEIGHT = 14; var G_SHIP_ROTATION_SPEED = 12; // in degrees per frame var G_SHIP_SPAWN_TIME_MAX = 5000; // in milliseconds var G_SHIP_TEXT = ">"; var g_asteroids = Array(); var g_asteroid_spawn_time = new Date(); var g_bullets = Array(); var g_bullet_fire_time = new Date(); var g_canvas; var g_ctx; var g_draw_grid = false; var g_draw_hud = true; var g_game_over = false; var g_game_paused = false; var g_hud_x = 8; var g_hud_y = 5; var g_img_starfield; var g_ship_collision = false; var g_ship_fill_style = "white"; var g_ship_fill_style_idx = 0; var g_ship_fill_style_idx_addend = 1; var g_ship_firing = false; var g_ship_height = 0; var g_ship_just_spawned = false; var g_ship_lives = 3; var g_ship_reflecting = false; var g_ship_reflection_x = 0; var g_ship_reflection_y = 0; var g_ship_rotation = 0; var g_ship_scale = 1; var g_ship_score = 0; var g_ship_spawn_time = new Date(); var g_ship_width = 0; var g_ship_x = 0; var g_ship_y = 0; var g_starfield_x = 0; var g_starfield_y = 0; var g_keys = {G_KEY_S: false, G_KEY_A: false, G_KEY_G: false, G_KEY_H: false, G_KEY_D: false, G_KEY_P: false, G_KEY_SPACE: false, G_KEY_W: false}; var g_keys_first_press = {G_KEY_S: false, G_KEY_A: false, G_KEY_G: false, G_KEY_H: false, G_KEY_D: false, G_KEY_P: false, G_KEY_SPACE: false, G_KEY_W: false}; function draw() { g_ctx.save(); g_ctx.setTransform(1, 0, 0, 1, 0, 0); g_ctx.clearRect(0, 0, g_canvas.width, g_canvas.height); draw_starfield(); draw_grid(); draw_hud(); draw_ship(); draw_ship_reflection(); draw_bullets(); draw_asteroids(); draw_game_over(); draw_game_paused(); g_ctx.restore(); } function draw_asteroids() { g_ctx.save(); for (var idx = 0; idx < g_asteroids.length; ++idx) { g_ctx.save(); g_ctx.strokeStyle = "white"; g_ctx.setTransform(1, 0, 0, 1, 0, 0); g_ctx.transform(1, 0, 0, 1, g_asteroids[idx].x, g_asteroids[idx].y); g_ctx.rotate(g_asteroids[idx].rotation); g_ctx.beginPath(); g_ctx.moveTo(g_asteroids[idx].vertices[0].x, g_asteroids[idx].vertices[0].y); for (var vertex = 1; vertex < g_asteroids[idx].vertices.length; ++vertex) { g_ctx.lineTo(g_asteroids[idx].vertices[vertex].x, g_asteroids[idx].vertices[vertex].y); } g_ctx.lineTo(g_asteroids[idx].vertices[0].x, g_asteroids[idx].vertices[0].y); g_ctx.stroke(); g_ctx.closePath(); g_ctx.transform(1, 0, 0, 1, -g_asteroids[idx].x, -g_asteroids[idx].y); g_ctx.restore(); } g_ctx.restore(); } function draw_bullets() { g_ctx.save(); g_ctx.strokeStyle = "#F3F315"; g_ctx.lineWidth = G_BULLET_WIDTH; for (var idx = 0; idx < g_bullets.length; ++idx) { g_ctx.save(); g_ctx.setTransform(1, 0, 0, 1, 0, 0); g_ctx.transform(1, 0, 0, 1, g_bullets[idx].x, g_bullets[idx].y); g_ctx.rotate(g_bullets[idx].rotation); g_ctx.beginPath(); g_ctx.moveTo(0, 0); g_ctx.lineTo(-G_BULLET_LENGTH, 0); g_ctx.stroke(); g_ctx.transform(1, 0, 0, 1, -g_bullets[idx].x, -g_bullets[idx].y); g_ctx.restore(); } g_ctx.restore(); } function draw_game_over() { if (!g_game_over) return; g_ctx.save(); g_ctx.font = "bold 120px courier new"; g_ctx.textAlign = "center"; g_ctx.textBaseline = "middle"; g_ctx.lineWidth = 8; g_ctx.strokeStyle = "white"; g_ctx.strokeText("GAME OVER", g_canvas.width / 2, g_canvas.height / 2); g_ctx.fillStyle = "#bb1111"; g_ctx.fillText("GAME OVER", g_canvas.width / 2, g_canvas.height / 2); g_ctx.restore(); } function draw_game_paused() { if (!g_game_paused) return; g_ctx.save(); g_ctx.font = "bold 120px courier new"; g_ctx.textAlign = "center"; g_ctx.textBaseline = "middle"; g_ctx.lineWidth = 8; g_ctx.strokeStyle = "white"; g_ctx.strokeText("PAUSED", g_canvas.width / 2, g_canvas.height / 2); g_ctx.fillStyle = "black"; g_ctx.fillText("PAUSED", g_canvas.width / 2, g_canvas.height / 2); g_ctx.restore(); } function draw_grid() { if (!g_draw_grid) return; g_ctx.save(); g_ctx.beginPath(); g_ctx.strokeStyle = "#330000"; // draw verticals var vert_step = g_canvas.width / 20; for (var x = 0; x < g_canvas.width; x += vert_step) { g_ctx.moveTo(x, 0); g_ctx.lineTo(x, g_canvas.height); } // draw horizontals var hori_step = g_canvas.height / 15; for (var y = 0; y < g_canvas.height; y += hori_step) { g_ctx.moveTo(0, y); g_ctx.lineTo(g_canvas.width, y); } g_ctx.closePath(); g_ctx.stroke(); g_ctx.beginPath(); g_ctx.strokeStyle = "#770000"; g_ctx.moveTo(g_canvas.width / 2, 0); g_ctx.lineTo(g_canvas.width / 2, g_canvas.height); g_ctx.stroke(); g_ctx.moveTo(0, g_canvas.height / 2); g_ctx.lineTo(g_canvas.width, g_canvas.height / 2); g_ctx.closePath(); g_ctx.stroke(); g_ctx.restore(); } function draw_hud() { if (!g_draw_hud) return; g_ctx.save(); g_ctx.textAlign = "left"; g_ctx.textBaseline = "top"; g_ctx.fillStyle = "white"; g_ctx.font = "bold " + G_HUD_FONT_HEIGHT + "px courier new"; var text = "LIVES: " + g_ship_lives; var text_width = g_ctx.measureText(text).width; g_ctx.fillText(text, g_hud_x, g_hud_y); var x = g_hud_x + text_width + G_HUD_ITEM_X_OFFSET; text = "SCORE: " + g_ship_score; text_width = g_ctx.measureText(text).width; g_ctx.fillText(text, x, g_hud_y); // TODO Temporary - delete!! (for testing) text = "ASTEROIDS: " + g_asteroids.length; g_ctx.fillText(text, x + text_width + G_HUD_ITEM_X_OFFSET, g_hud_y); g_ctx.restore(); } function draw_starfield() { g_ctx.save(); g_ctx.drawImage(g_img_starfield, g_starfield_x, g_starfield_y); g_ctx.restore(); } function draw_ship() { g_ctx.save(); g_ctx.setTransform(1, 0, 0, 1, 0, 0); g_ctx.transform(1, 0, 0, 1, g_ship_x, g_ship_y); g_ctx.rotate(g_ship_rotation); g_ctx.scale(g_ship_scale, g_ship_scale); g_ctx.transform(1, 0, 0, 1, -g_ship_x, -g_ship_y); g_ctx.textAlign = "center"; g_ctx.textBaseline = "middle"; g_ctx.fillStyle = g_ship_fill_style; g_ctx.font = g_ship_font; g_ctx.fillText(G_SHIP_TEXT, g_ship_x, g_ship_y); g_ctx.restore(); } function draw_ship_reflection() { if (!g_ship_reflecting) return; g_ctx.save(); g_ctx.setTransform(1, 0, 0, 1, 0, 0); g_ctx.transform(1, 0, 0, 1, g_ship_reflection_x, g_ship_reflection_y); g_ctx.rotate(g_ship_rotation); g_ctx.scale(g_ship_scale, g_ship_scale); g_ctx.transform(1, 0, 0, 1, -g_ship_reflection_x, -g_ship_reflection_y); g_ctx.textAlign = "center"; g_ctx.textBaseline = "middle"; g_ctx.fillStyle = "white"; g_ctx.font = g_ship_font; g_ctx.fillText(G_SHIP_TEXT, g_ship_reflection_x, g_ship_reflection_y); g_ctx.restore(); } function keydown(e) { g_keys_first_press[e.keyCode] = !g_keys[e.keyCode]; g_keys[e.keyCode] = true; } function keyup(e) { g_keys_first_press[e.keyCode] = false; g_keys[e.keyCode] = false; } function load() { g_canvas = document.getElementById(G_CANVAS_ID); g_canvas.height = G_CANVAS_HEIGHT; g_canvas.width = G_CANVAS_WIDTH; g_ctx = g_canvas.getContext("2d"); g_img_starfield = new Image(); g_img_starfield.src = "starfield.png"; // TODO use repeating background (all four edges) but background size should be larger than canvas for parallax g_last_update_time = new Date(); g_ship_x = g_canvas.width / 2; g_ship_y = g_canvas.height / 2; g_ship_width = g_ctx.measureText(G_SHIP_TEXT).width; g_ship_height = G_SHIP_HEIGHT; g_ship_rotation = -90 * Math.PI / 180; g_ship_font = "bold " + g_ship_height + "px courier new"; window.addEventListener("keydown", keydown); window.addEventListener("keyup", keyup); window.setInterval(run, G_MSEC_PER_FRAME); } function run() { update(); draw(); } function update() { if (!g_game_over && !g_game_paused) { update_starfield(); update_grid(); update_hud(); update_ship(); update_bullets(); update_asteroids(); update_game_paused(); } else if (g_game_over) { update_game_over(); } else if (g_game_paused) { update_game_paused(); } } function update_asteroids() { // spawn new asteroid var delta = new Date() - g_asteroid_spawn_time; if (g_asteroids.length == 0 || delta >= G_ASTEROID_SPAWN_RATE && g_asteroids.length < G_ASTEROID_MAX) { var height = Math.random() * (G_ASTEROID_HEIGHT_MAX - G_ASTEROID_HEIGHT_MIN) + G_ASTEROID_HEIGHT_MIN; var width = Math.random() * (G_ASTEROID_WIDTH_MAX - G_ASTEROID_WIDTH_MIN) + G_ASTEROID_WIDTH_MIN; var radius = Math.sqrt(height * height + width * width); var rotation_speed = (Math.random() * (G_ASTEROID_ROTATION_SPEED_MAX - G_ASTEROID_ROTATION_SPEED_MAX) + G_ASTEROID_ROTATION_SPEED_MIN) * Math.PI / 180; if (Math.random() < 0.5) rotation_speed *= -1; var speed = Math.random() * (G_ASTEROID_SPEED_MAX - G_ASTEROID_SPEED_MIN) + G_ASTEROID_SPEED_MIN; var x = 0, y = 0; var spawn_edge = Math.round(Math.random() * G_ASTEROID_SPAWN_EDGES - 1); switch (spawn_edge) { case G_ASTEROID_SPAWN_EDGE.TOP: x = Math.random() * (g_canvas.width - radius * 2) + radius; y = -radius * 2; rotation = 90 * Math.PI / 180; break; case G_ASTEROID_SPAWN_EDGE.TOPRIGHT: x = g_canvas.width + radius; y = -radius * 2; rotation = 135 * Math.PI / 180; break; case G_ASTEROID_SPAWN_EDGE.RIGHT: x = g_canvas.width + radius * 2; y = Math.random() * (g_canvas.height - radius * 2) + radius; rotation = -180 * Math.PI / 180; break; case G_ASTEROID_SPAWN_EDGE.BOTTOMRIGHT: x = g_canvas.width + radius * 2; y = g_canvas.height + radius * 2; rotation = -135 * Math.PI / 180; break; case G_ASTEROID_SPAWN_EDGE.BOTTOM: x = Math.random() * (g_canvas.width - radius * 2) + radius; y = g_canvas.height + radius * 2; rotation = -90 * Math.PI / 180; break; case G_ASTEROID_SPAWN_EDGE.BOTTOMLEFT: x = -radius * 2; y = g_canvas.height + radius * 2; rotation = -45 * Math.PI / 180; break; case G_ASTEROID_SPAWN_EDGE.LEFT: x = -radius * 2; y = Math.random() * (g_canvas.height - radius * 2) + radius; rotation = 180 * Math.PI / 180; break; case G_ASTEROID_SPAWN_EDGE.TOPLEFT: default: x = -radius * 2; y = -radius * 2; rotation = 45 * Math.PI / 180; break; } var vertices = Array(); var num_vertices = Math.round(Math.random() * (G_ASTEROID_VERTICES_MAX - G_ASTEROID_VERTICES_MIN) + G_ASTEROID_VERTICES_MIN); // for now, regular asteroids (all vertices have same angle to center) var angle = 2 * Math.PI / num_vertices; // in radians (= 360 / num_vertices * Math.PI / 180) for (var vertex_idx = 0; vertex_idx < num_vertices; ++vertex_idx) { var vertex_x = radius * Math.cos(angle * vertex_idx); var vertex_y = radius * Math.sin(angle * vertex_idx); var vertex = {x: vertex_x, y: vertex_y} vertices.push(vertex); } var asteroid = {x: x, y: y, vertices: vertices, radius: radius, height: height, width: width, rotation: rotation, rotation_speed: rotation_speed, speed: speed, just_spawned: true} g_asteroids.push(asteroid); g_asteroid_spawn_time = new Date(); } var to_create = Array(); var to_delete = Array(); // move asteroids for (var idx = 0; idx < g_asteroids.length; ++idx) { //if (g_asteroids[idx].just_spawned) //{ g_asteroids[idx].x += g_asteroids[idx].speed * Math.cos(g_asteroids[idx].rotation); g_asteroids[idx].y += g_asteroids[idx].speed * Math.sin(g_asteroids[idx].rotation); //} //else //if (!g_asteroids[idx].just_spawned) if (!g_asteroids[idx].just_spawned) { g_asteroids[idx].rotation += g_asteroids[idx].rotation_speed; if (Math.random() < 0.0025) g_asteroids[idx].rotation_speed *= -1; } // TODO fix this check - it's not working! but why?? // aha!! vertices are relative to center of asteroid, not absolute position! var is_out_of_bounds = true; for (var v_idx = 0; is_out_of_bounds && v_idx < g_asteroids[idx].vertices.length; ++v_idx) { var x = g_asteroids[idx].x + g_asteroids[idx].vertices[v_idx].x; var y = g_asteroids[idx].y + g_asteroids[idx].vertices[v_idx].y; // if any vertex is in bounds, the asteroid is is bounds if (x >= 0 && x < g_canvas.width && y >= 0 && y <= g_canvas.height) { is_out_of_bounds = false; } } // if just spawned and now in bounds, just_spawned = false // else if not just spawned and out of bounds, delete asteroid if (g_asteroids[idx].just_spawned && !is_out_of_bounds) g_asteroids[idx].just_spawned = false; else if (!g_asteroids[idx].just_spawned && is_out_of_bounds) to_delete.push(idx); var collision = false; // TODO check asteroids colliding with each other // for (var a_idx = 0; a_idx < g_asteroids.length && !collision; ++a_idx) // { // if (a_idx != idx) // { // var dx = g_asteroids[idx].x - g_asteroids[a_idx].x; // var dy = g_asteroids[idx].y - g_asteroids[a_idx].y; // var distance = Math.sqrt(dx * dx + dy * dy); // if (distance <= g_asteroids[idx].radius + g_asteroids[a_idx].radius) // { // //collision = true; // //g_asteroids[idx].rotation += Math.PI; // } // } // } // check for collisions with ship // only check asteroids that are close enough to the ship to matter // TODO how to check if ship is inside asteroid? // for now, just check distance to asteroid radius (since regular polygons) var dx = g_ship_x - g_asteroids[idx].x; var dy = g_ship_y - g_asteroids[idx].y; var distance_to_ship = Math.sqrt(dx * dx + dy * dy); if (!g_ship_just_spawned && distance_to_ship <= g_asteroids[idx].radius)// + Math.max(g_ship_height, g_ship_width)) { collision = true; g_ship_collision = true; } // check for collision against bullets for (var b_idx = 0; b_idx < g_bullets.length && !collision; ++b_idx) { var dx = g_bullets[b_idx].x - g_asteroids[idx].x; var dy = g_bullets[b_idx].y - g_asteroids[idx].y; var distance_to_bullet = Math.sqrt(dx * dx + dy * dy); if (distance_to_bullet <= g_asteroids[idx].radius) // TODO will not account for bullet moving through asteroid { collision = true; g_bullets[b_idx].destroy = true; g_ship_score += G_SCORE_ASTEROID_HIT; } } if (collision) // ship or bullet { to_delete.push(idx); // break asteroid in two!! and add both to array (after this loop) var height = g_asteroids[idx].height / 2 var width = g_asteroids[idx].width / 2 var radius = Math.sqrt(height * height + width * width); var rotation_speed = g_asteroids[idx].rotation_speed; var rotation1 = g_asteroids[idx].rotation; // or random? var rotation2 = -g_asteroids[idx].rotation; // or random? var x1 = g_asteroids[idx].x + radius * Math.cos(rotation1); var y1 = g_asteroids[idx].y + radius * Math.sin(rotation1); var x2 = g_asteroids[idx].x + radius * Math.cos(rotation2); var y2 = g_asteroids[idx].y + radius * Math.sin(rotation2); var speed = g_asteroids[idx].speed; // or random? var just_spawned = true; var vertices = Array(); var num_vertices = g_asteroids[idx].vertices.length; // for now, regular asteroids (all vertices have same angle to center) var angle = 2 * Math.PI / num_vertices; // in radians (= 360 / num_vertices * Math.PI / 180) for (var vertex_idx = 0; vertex_idx < num_vertices; ++vertex_idx) { var vertex_x = radius * Math.cos(angle * vertex_idx); var vertex_y = radius * Math.sin(angle * vertex_idx); var vertex = {x: vertex_x, y: vertex_y} vertices.push(vertex); } if (height >= G_ASTEROID_HEIGHT_MIN && width >= G_ASTEROID_WIDTH_MIN) { var asteroid1 = {x: x1, y: y1, vertices: vertices, radius: radius, height: height, width: width, rotation: rotation1, rotation_speed: rotation_speed, speed: speed, just_spawned: g_asteroids[idx].just_spawned}; to_create.push(asteroid1); var asteroid2 = {x: x2, y: y2, vertices: vertices, radius: radius, height: height, width: width, rotation: rotation2, rotation_speed: rotation_speed, speed: speed, just_spawned: g_asteroids[idx].just_spawned}; to_create.push(asteroid2); } } } // delete asteroids that have collided or are out of bounds for (var idx = 0; idx < to_delete.length; ++idx) g_asteroids.splice(to_delete[idx], 1); // create new asteroids that have come into existence for (var idx = 0; idx < to_create.length; ++idx) g_asteroids.push(to_create[idx]); } function update_bullets() { g_ship_firing = g_keys[G_KEY_SPACE]; var delta = new Date() - g_bullet_fire_time; var just_fired = false; if (!g_ship_just_spawned && g_ship_firing && (!g_bullets.length || g_bullets.length < G_BULLET_MAX && delta >= G_BULLET_FIRE_WAIT)) { var x = 0, y = 0, rotation = 0; if (!g_ship_reflecting) { x = g_ship_x; y = g_ship_y; rotation = g_ship_rotation; } else { x = g_ship_reflection_x; y = g_ship_reflection_y; rotation = g_ship_rotation; } var bullet = {x: x, y: y, rotation: rotation, fire_time: new Date(), destroy: false} g_bullets.push(bullet); just_fired = true; g_bullet_fire_time = new Date(); } var collided_idx = Array(); var now = new Date(); var out_of_bounds = false; for (var idx = 0; idx < g_bullets.length; ++idx) { if (g_bullets[idx].destroy) { collided_idx.push(idx); continue; } // check collisions with ship var ship_x, ship_y; if (g_ship_reflecting) { ship_x = g_ship_reflection_x; ship_y = g_ship_reflection_y; } else { ship_x = g_ship_x; ship_y = g_ship_y; } if (!g_ship_collision && !just_fired && !g_ship_just_spawned && g_bullets[idx].x >= ship_x - g_ship_width / 2 && g_bullets[idx].x < ship_x + g_ship_width / 2 && g_bullets[idx].y >= ship_y - g_ship_height / 2 && g_bullets[idx].y < ship_y + g_ship_height / 2) { g_ship_collision = true; } // move bullet g_bullets[idx].x += G_BULLET_SPEED * Math.cos(g_bullets[idx].rotation); g_bullets[idx].y += G_BULLET_SPEED * Math.sin(g_bullets[idx].rotation); // check collision with boundaries if (g_bullets[idx].x < 0) { g_bullets[idx].x += g_canvas.width; out_of_bounds = true; } else if (g_bullets[idx].x > g_canvas.width) { g_bullets[idx].x -= g_canvas.width; out_of_bounds = true; } if (g_bullets[idx].y < 0) { g_bullets[idx].y += g_canvas.height; out_of_bounds = true; } else if (g_bullets[idx].y > g_canvas.height) { g_bullets[idx].y -= g_canvas.height; out_of_bounds = true; } // delete bullets that have collided if (out_of_bounds && now - g_bullets[idx].fire_time >= G_BULLET_LIFE_TIME || g_ship_collision) { collided_idx.push(idx); } } // delete bullets that have collided for (var idx = 0; idx < collided_idx.length; ++idx) g_bullets.splice(collided_idx[idx], 1); } function update_game_over() { } function update_game_paused() { if (g_keys_first_press[G_KEY_P]) { g_game_paused = !g_game_paused; g_keys_first_press[G_KEY_P] = false; } } function update_grid() { if (g_keys_first_press[G_KEY_G]) { g_draw_grid = !g_draw_grid; g_keys_first_press[G_KEY_G] = false; } } function update_hud() { if (g_keys_first_press[G_KEY_H]) { g_draw_hud = !g_draw_hud; g_keys_first_press[G_KEY_H] = false; } } function update_ship() { // check if just spawned var delta = new Date() - g_ship_spawn_time; if (g_ship_just_spawned && delta >= G_SHIP_SPAWN_TIME_MAX) { g_ship_just_spawned = false; g_ship_fill_style = "white"; g_ship_scale = 1; } else if (g_ship_just_spawned) { g_ship_fill_style = G_SHIP_FILL_STYLES[g_ship_fill_style_idx]; g_ship_fill_style_idx += g_ship_fill_style_idx_addend; if (g_ship_fill_style_idx >= G_SHIP_FILL_STYLES.length) { g_ship_fill_style_idx = G_SHIP_FILL_STYLES.length - 1; g_ship_fill_style_idx_addend = -1; } else if (g_ship_fill_style_idx < 0) { g_ship_fill_style_idx = 0; g_ship_fill_style_idx_addend = 1; } if (g_ship_scale > 1) g_ship_scale -= 0.2; else g_ship_scale = 1; } // move ship if (g_keys[G_KEY_A]) { g_ship_rotation -= G_SHIP_ROTATION_SPEED * Math.PI / 180; } if (g_keys[G_KEY_D]) { g_ship_rotation += G_SHIP_ROTATION_SPEED * Math.PI / 180; } if (g_keys[G_KEY_W]) { g_ship_x += G_SHIP_FORWARD_SPEED * Math.cos(g_ship_rotation); g_ship_y += G_SHIP_FORWARD_SPEED * Math.sin(g_ship_rotation); } if (g_keys[G_KEY_S]) { g_ship_x -= G_SHIP_BACKWARD_SPEED * Math.cos(g_ship_rotation); g_ship_y -= G_SHIP_BACKWARD_SPEED * Math.sin(g_ship_rotation); } // TODO space drift? - move ship in direction of movement to simulate inertia // update ship reflection if out of bounds var x_reflecting = false; if (g_ship_x - g_ship_width / 2 < 0) { x_reflecting = true; g_ship_reflecting = true; g_ship_reflection_x = g_ship_x + g_canvas.width; g_ship_reflection_y = g_ship_y; if (g_ship_x < -g_ship_width / 2) { g_ship_reflecting = false; g_ship_x = g_ship_reflection_x; g_ship_y = g_ship_reflection_y; } } else if (g_ship_x + g_ship_width / 2 >= g_canvas.width) { x_reflecting = true; g_ship_reflecting = true; g_ship_reflection_x = g_ship_x - g_canvas.width; g_ship_reflection_y = g_ship_y; if (g_ship_x > g_canvas.width + g_ship_width / 2) { g_ship_reflecting = false; g_ship_x = g_ship_reflection_x; g_ship_y = g_ship_reflection_y; } } if (g_ship_y - g_ship_height / 2 < 0) { g_ship_reflecting = true; if (!x_reflecting) g_ship_reflection_x = g_ship_x; // to cover corner reflection g_ship_reflection_y = g_ship_y + g_canvas.height; if (g_ship_y < -g_ship_height / 2) { g_ship_reflecting = false; g_ship_x = g_ship_reflection_x; g_ship_y = g_ship_reflection_y; } } else if (g_ship_y + g_ship_height / 2 >= g_canvas.height) { g_ship_reflecting = true; if (!x_reflecting) g_ship_reflection_x = g_ship_x; // to cover corner reflection g_ship_reflection_y = g_ship_y - g_canvas.height; if (g_ship_y > g_canvas.height + g_ship_height / 2) { g_ship_reflecting = false; g_ship_x = g_ship_reflection_x; g_ship_y = g_ship_reflection_y; } } // TODO check for collisions with objects if (g_ship_collision && !g_ship_just_spawned) { // respawn in center if dead if (--g_ship_lives <= 0) { g_ship_lives = 0; g_ship_score -= G_SCORE_DEATH_PENALTY; g_game_over = true; g_game_paused = false; } else { g_ship_reflecting = false; g_ship_x = g_canvas.width / 2; g_ship_y = g_canvas.height / 2; g_ship_rotation = -90 * Math.PI / 180; g_ship_fill_style_idx = 0; g_ship_fill_style_idx_addend = 1; g_ship_scale = 20; g_ship_score -= G_SCORE_DEATH_PENALTY; g_ship_just_spawned = true; g_ship_spawn_time = new Date(); } g_ship_collision = false; } } function update_starfield() { // TODO move background in parallax to ship } window.addEventListener("load", load);
52d5db84401f516886d2c48901db03108443329b
[ "JavaScript" ]
1
JavaScript
robobrobro/spaceship
46fdcbd0f85d5629ff093f3954fd3f43284e6f17
de18f0c922d6a5cbe35b2e670b535fbb5a8bfd41
refs/heads/master
<repo_name>csbobby/deep-learning_lstm<file_sep>/predicting.py ''' Author: bobby Date created: Nov 11,2015 Date last modified: Nov 11, 2016 Python Version: 2.7 ''' from keras.models import Sequential from keras.utils import np_utils from keras.layers.core import Dense, Activation, Dropout import pandas as pd import numpy as np def predicting(model,X_test,resultsfname): print("Generating test predictions...") preds = model.predict_classes(X_test, verbose=0) def write_preds(preds, fname): pd.DataFrame({"SampleID": list(range(1,len(preds)+1)), "Label": preds}).to_csv(fname, index=False, header=True) write_preds(preds, resultsfname) return preds <file_sep>/lstm_training.py ''' Author: bobby Date created: Feb 1,2016 Date last modified: May 10, 2016 Python Version: 2.7 ''' from keras.models import Sequential from keras.utils import np_utils from keras.layers.core import Dense, Activation, Dropout import pandas as pd import numpy as np def lstm_training(X_train,y_train,input_dim,nb_classes): #settings param={} param['nb_epoch']=100 param['batch_size']=64 param['validation_split']=0.1 print 'traning',param # Here's a Long Short Term Memory (LSTM) model = Sequential() model.add(LSTM(input_dim = 3561, output_dim = 3000,return_sequences = False)) model.add(Dense(input_dim = 3000, output_dim = 1)) model.add(Activation("softmax")) # we'll use MSE (mean squared error) for the loss, and RMSprop as the optimizer model.compile(loss='mse', optimizer='rmsprop') from keras.utils.dot_utils import Grapher grapher = Grapher() grapher.plot(model, 'model.png') #if the evalidation error decreased after one epoch, save the model checkpointer =ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True) # the callback function for logging loss class LossHistory(keras.callbacks.Callback): def on_train_begin(self, logs={}): self.losses = [] def on_batch_end(self, batch, logs={}): self.losses.append(logs.get('loss')) # define a callback object history = LossHistory() print history.losses print("start train process...") hist = model.fit(X_train, y_train,nb_epoch=param['nb_epoch'], batch_size=param['batch_size'], \ validation_split=param.get('validation_split'), show_accuracy=True, verbose=0 \ , callbacks=[checkpointer,history] ) loss = hist.history.get('loss') val_loss = hist.history.get('val_loss') return model,loss,val_loss <file_sep>/IterationGraph.py ''' Author: bobby Date created: Feb 1,2016 Date last modified: May 14, 2016 Python Version: 2.7 ''' import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import pandas as pd def IterationGraph(loss,val_loss,history_path,graph_out_path,features): history_f = open(history_path,'w') length_history = len(loss) for i in range(length_history): history_f.write(str(loss[i])) history_f.write('\t') history_f.write(str(val_loss[i])) history_f.write('\n') df = pd.read_table(history_path,names=['loss','val_loss']) loss_plot = df.plot(title='%s_training'%features) loss_fig = loss_plot.get_figure() loss_fig.savefig(graph_out_path) #loss_fig.savefig('USER_loss.png') <file_sep>/README.md # deep-learning_lstm Deep Learning: Long short-term memory (LSTM) <file_sep>/deep_main.py ''' Author: bobby Date created: Feb 1,2016 Date last modified: May 14, 2016 Python Version: 2.7 ''' import pandas as pd import numpy as np from mlp_training import mlp_training from testing import testing import sys sys.path.append('../') from ws_py import datapreparation as dp from IterationGraph import * if __name__ == "__main__": print 'start' did = 0 fid = 1 datasets=['3W','40W','68W','100W']; datasets=datasets[did]# MSRA:3W 68W VSO_CC:40W 100W features=['ALL','USER','DL','VISUAL']; features=features[fid] resulttitle='features' sname=features model_save_filename = None model_save_collection = {} ## step 1: load data print "step 1: load data..." datadir,X_train,y_train,X_test,y_test = dp.feature_loader(datasets,features) #results and evaluation fnames resultsfname = datadir+'results_'+resulttitle+'_'+datasets+'_'+features+'.txt' evaluationfname = datadir+'evaluation_'+resulttitle+'_'+datasets+'_'+features+'.txt' input_dim = X_train.shape[1] nb_classes = len(np.unique(y_train)) print 'training...' model,loss,val_loss = mlp_training(X_train,y_train,input_dim) history_path = './IterationGraph/%s_history.txt'%features graph_out_path = './IterationGraph/%s_loss.png'%features IterationGraph(loss,val_loss,history_path,graph_out_path,features) print 'testing...' spearmanr_corr,objective_score = testing(X_test,y_test,resultsfname,evaluationfname) #preds = predicting(model,X_test,resultsfname) <file_sep>/testing.py ''' Author: bobby Date created: Feb 1,2016 Date last modified: Apr 10, 2016 Python Version: 2.7 ''' from keras.models import Sequential from keras.utils import np_utils from keras.layers.core import Dense, Activation, Dropout import pandas as pd import scipy as sp def testing(X_test,y_test,resultsfname,evaluationfname): print("Evaluate the results...") preds = model.predict_classes(X_test, verbose=0) def write_preds(preds, fname): pd.DataFrame({"SampleID": list(range(1,len(preds)+1)), "Label": preds}).to_csv(fname, index=False, header=True) write_preds(preds, resultsfname) spearmanr_corr = sp.spearmanr(y_test, preds)[0, 1] print "Pearson Correlation",p_corr objective_score = model.evaluate(X_test, y_test, batch_size=32) print "objective_score",objective_score return spearmanr_corr,objective_score
044e95350486005a7af9a380606dba28feecdd9b
[ "Markdown", "Python" ]
6
Python
csbobby/deep-learning_lstm
122804d7dbcb28c3ecfd7fc4418465186e986c9a
3689709db1b3735733a908a95321cdef58e49637
refs/heads/master
<file_sep>import React, { Component } from "react"; import "./App.css"; class ControlledInput extends Component { state = { text: "" }; handleChange = e => { const name = e.target.name; const value = e.target.value.toUpperCase(); /* console.log(`The name of the input : ${name}`); console.log(`The name of the input : ${value}`); */ this.setState({ text: value }); }; handleSubmit = event => { event.preventDefault(); console.log(this.state.text); }; render() { return ( <form onSubmit={this.handleSubmit} style={{ margin: "3rem" }}> <input tpe="text" value={this.state.text} onChange={this.handleChange} name="firstname" /> <button type="submit">Submit Here</button> </form> ); } } class UncontrolledInput extends Component { handleSubmit = event => { event.preventDefault(); console.log(this.firstname.value); console.log(this.email.value); console.log(this.text.textContent); }; render() { return ( <form style={{ margin: "3rem" }}> <input type="text" name="firstname" ref={orange => (this.firstname = orange)} /> <input type="email" name="email" ref={input => (this.email = input)} /> <button type="submit" onClick={this.handleSubmit}> Submit Here </button> <p ref={input => (this.text = input)}>hello world</p> </form> ); } } class App extends Component { render() { return ( <div> <UncontrolledInput /> </div> ); } } export default App;
2ff77caf1e5b57a3f8a14074fde7d933da91916b
[ "JavaScript" ]
1
JavaScript
ManuelRafaelano/curse-tutorials
3564a9a60c2308399f4092c9a3c9d81d4bcfefe7
d07832e021a8d2191a08725baa1dd219ee54e96a
refs/heads/master
<repo_name>janglz/citymobil-test<file_sep>/src/state/initialState.js import { useState, useEffect } from 'react'; /** * @constructor * @returns {Object} состояние * * структура состояния, наверное, слишком раздутая, но у меня же еще не одно тестовое, уважаемый проверяющий :) */ function State() { const [sortedBy, setSortedBy] = useState('none') // 'alphabet', 'alphabet-reversed' const [filteredBy, setFilteredBy] = useState(''); const [selectedAuto, setSelectedAuto] = useState(null); const [allCars, setAllCars] = useState([]); const [isLoading, setIsLoading] = useState(true); const [filteredCars, setFilteredCars] = useState([]); useEffect(() => { const abortController = new AbortController(); const fetchData = async () => { console.log('fetched') const cars = []; const data = await fetch('https://city-mobil.ru/api/cars', { abortController }) .then(response => response.json()); data.cars.forEach(car => { cars.push({ mark: car.mark, model: car.model, year: { economYear: car.tariffs['Эконом']?.year || '-', comfortYear: car.tariffs['Комфорт']?.year || '-', comfortPlusYear: car.tariffs['Комфорт+']?.year || '-', minivanYear: car.tariffs['Минивен']?.year || '-', businessYear: car.tariffs['Бизнес']?.year || '-', } }) }); setAllCars(cars); setFilteredCars(cars) setIsLoading(false); }; if (!allCars.length) fetchData(); return () => { abortController.abort(); } }, [setAllCars, setIsLoading, allCars, setFilteredCars]); return { sortedBy, setSortedBy, filteredBy, setFilteredBy, selectedAuto, setSelectedAuto, allCars, setAllCars, isLoading, setIsLoading, filteredCars, setFilteredCars, } } export default State;<file_sep>/README.md # Тестовое задание для Ситимобил Создано по шаблону [Create React App]. Неоправданно использован context api - для тренировки. Буду благодарен любой обратной связи! ## Запуск: ### `npm start` <file_sep>/src/components/InfoBar.js import { useContext, useEffect } from 'react' import { Context } from '../state/context'; /** * * @returns jsx */ function InfoBar () { const { selectedAuto, setSelectedAuto } = useContext(Context); useEffect(()=>{ setSelectedAuto(selectedAuto) }, [selectedAuto, setSelectedAuto]) // В описании задания указано "по клику на строку" - это значит, что программа сама должна выбирать, // какой год отобразит инфо-панель? const selected = selectedAuto ? ( <div className="infobar" onClick={()=>setSelectedAuto(null)}> <p>{`Выбран автомобиль ${selectedAuto.mark} ${selectedAuto.model} ${Object.values(selectedAuto.year).find(el => el !== '-')} года выпуска`}</p> </div> ) : '' return selected } export default InfoBar<file_sep>/src/components/SearchBar.js import { useEffect, useContext, useState } from 'react' import { Context } from '../state/context'; function SearchBar () { const { filteredBy, setFilteredBy, allCars, setFilteredCars, setIsLoading, filteredCars } = useContext(Context); const [inputValue, setInputValue] = useState(); const HandleChange = (e) => { const val = e.target.value || '' setInputValue(val) } useEffect( () => { setIsLoading(true); setFilteredBy(inputValue) }, [inputValue, setFilteredBy, filteredBy, allCars, setFilteredCars, setIsLoading, filteredCars], ); return ( <div className="searchbar"> <input type="text" defaultValue={filteredBy} placeholder="Поиск" onInput={HandleChange} /> <button className="button"> Найти </button> </div> ) } export { SearchBar } <file_sep>/src/components/Loader.js import logo from '../logo.svg' export default function Loader() { return <div className="loader"><img src={logo} alt="loading..." /></div> }
236fa665172fcece2fe91f7406d925f1bb510dbd
[ "JavaScript", "Markdown" ]
5
JavaScript
janglz/citymobil-test
3285147fefdbed6f2ab442290037ac47b4bdc596
2e0efa677ea124897b9f04ce0ee8efd5d5d110da
refs/heads/master
<repo_name>mangalpandey/sample-app<file_sep>/node-app/app.js const express = require("express"); const cors = require("cors"); const bodyParser = require("body-parser"); const mongoose = require("mongoose"); const MONGODB_URI = "mongodb+srv://mangal:<EMAIL>/test?retryWrites=true&w=majority"; const customerRoute = require("./routes/customer"); const productRoute = require("./routes/product"); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use((req, res, next) => { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader( "Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE" ); res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); next(); }); app.use("/customer", customerRoute); app.use("/product", productRoute); app.use((error, req, res, next) => { console.log(error); const status = error.statusCode || 500; const message = error.message; res.status(status).json({ message: message }); }); console.log("Please wait, Connecting to mongoDB"); mongoose .connect(MONGODB_URI, { useUnifiedTopology: true, useNewUrlParser: true, }) .then((result) => { console.log("Connedted to mongoDB and server has started at port 3001"); app.listen(3001); }) .catch((err) => { console.log("MongoDB conection error => " + err); }); <file_sep>/node-app/routes/customer.js const express = require("express"); const customerController = require("../controller/customer"); const isAuth = require("../middleware/auth"); const router = express.Router(); // GET /customer/login router.post("/login", customerController.login); // POST /customer/signup router.post("/signup", customerController.signup); // POST /customer/me router.post("/me", isAuth, customerController.me); module.exports = router; <file_sep>/node-app/routes/product.js const express = require("express"); const productController = require("../controller/product"); const isAuth = require("../middleware/auth"); const auth = require("../middleware/auth"); const router = express.Router(); // GET /product/get/id router.get("/get/:id", isAuth, productController.get); // GET /product/getAll router.get("/getAll", isAuth, productController.getAll); // GET /product/purchase router.post("/purchase", isAuth, productController.purchase); module.exports = router; <file_sep>/react-app/src/reducers/reducer.js import { ACCESS_TOKEN, API_BASE_URL, EMAIL, ID } from "../constants/config"; const LOGIN_IN_PROCESS = "LOGIN_IN_PROCESS"; const LOGIN_SUCCESS = "LOGIN_SUCCESS"; const LOGIN_ERROR = "LOGIN_ERROR"; const SIGNUP_IN_PROCESS = "SIGNUP_IN_PROCESS"; const SIGNUP_SUCCESS = "SIGNUP_SUCCESS"; const SIGNUP_ERROR = "SIGNUP_ERROR"; const PRODUCT_PURCHASING = "PRODUCT_PURCHASING"; const PRODUCT_PURCHASED = "PRODUCT_PURCHASED "; const PRODUCT_DATA = "PRODUCT_DATA"; const CUSTOMER_DATA = "CUSTOMER_DATA"; const intialState = { isSignupProgress: false, isSignupSuccess: false, signupError: null, isLoginProgress: false, isLoginSuccess: false, loginError: null, customer: null, isProductPurchasing: false, isProductPurchased: false, productsData: null, }; function setLoginInProcess(isLoginProgress) { return { type: LOGIN_IN_PROCESS, isLoginProgress, }; } function setLoginSuccess(isLoginSuccess) { return { type: LOGIN_SUCCESS, isLoginSuccess, }; } function setLoginError(loginError) { return { type: LOGIN_ERROR, loginError, }; } function setSignupInProcess(isSignupProgress) { return { type: SIGNUP_IN_PROCESS, isSignupProgress, }; } function setSignupSuccess(isSignupSuccess) { return { type: SIGNUP_SUCCESS, isSignupSuccess, }; } function setSignupError(signupError) { return { type: SIGNUP_ERROR, signupError, }; } function setCustometData(customer) { return { type: CUSTOMER_DATA, customer, }; } function setProductData(productsData) { return { type: PRODUCT_DATA, productsData, }; } function setProductPurchasing(isProductPurchasing) { return { type: PRODUCT_PURCHASING, isProductPurchasing, }; } function setProductPurchased(isProductPurchased) { return { type: PRODUCT_PURCHASED, isProductPurchased, }; } export function udateStatus() { return (dispatch) => { dispatch(setSignupSuccess(false)); }; } export function signup(name, email, password) { return (dispatch) => { dispatch(setSignupInProcess(true)); dispatch(setSignupSuccess(false)); dispatch(setSignupError(null)); fetch(API_BASE_URL + "/customer/signup", { method: "POST", headers: { "Content-type": "application/json; charset=UTF-8", }, body: JSON.stringify({ name: name, email: email, password: <PASSWORD>, }), }) .then((res) => res.json()) .then((data) => { if (data && data.customer) { console.log("succes", data); dispatch(setSignupInProcess(false)); dispatch(setSignupSuccess(true)); dispatch(setSignupError(null)); } else if (data && !data.token) { console.log("error", data); dispatch(setSignupInProcess(false)); dispatch(setSignupSuccess(false)); dispatch(setSignupError("Signup error")); } }) .catch(function (err) { console.log("error", err); dispatch(setSignupInProcess(false)); dispatch(setSignupSuccess(false)); dispatch(setSignupError(err)); }); }; } export function login(email, password) { return (dispatch) => { dispatch(setLoginInProcess(true)); dispatch(setLoginSuccess(false)); dispatch(setLoginError(null)); fetch(API_BASE_URL + "/customer/login", { method: "POST", headers: { "Content-type": "application/json; charset=UTF-8", }, body: JSON.stringify({ email: email, password: <PASSWORD>, }), }) .then((res) => res.json()) .then((data) => { if (data && data.token) { console.log("succes", data); saveToLocalStorage(data); dispatch(setLoginInProcess(false)); dispatch(setLoginSuccess(true)); dispatch(setLoginError(null)); } else if (data && !data.token) { console.log("error", data); saveToLocalStorage({}); dispatch(setLoginInProcess(false)); dispatch(setLoginSuccess(false)); dispatch(setLoginError(data)); } }) .catch(function (err) { console.log("error", err); saveToLocalStorage({}); dispatch(setLoginInProcess(false)); dispatch(setLoginSuccess(false)); dispatch(setLoginError("Error")); }); }; } function saveToLocalStorage(data) { if (data && data.token) { localStorage.setItem(ACCESS_TOKEN, data.token); localStorage.setItem(EMAIL, data.email); localStorage.setItem(ID, data._id); } else { localStorage.setItem(ACCESS_TOKEN, ""); localStorage.setItem(EMAIL, ""); localStorage.setItem(ID, ""); } } export function purchaseProduct(name, price, shopName, status) { return (dispatch) => { dispatch(setProductPurchasing(true)); fetch(API_BASE_URL + "/product/purchase", { method: "POST", headers: { "Content-type": "application/json; charset=UTF-8", Authorization: "Bearer " + localStorage.getItem(ACCESS_TOKEN), }, body: JSON.stringify({ name: name, price: price, shopName: shopName, status: status, userId: localStorage.getItem(ID), }), }) .then((res) => res.json()) .then((data) => { console.log("product purchase", data); dispatch(setProductPurchased(true)); dispatch(setProductPurchasing(false)); }) .catch((err) => { dispatch(setProductPurchased(false)); dispatch(setProductPurchasing(false)); }); }; } export function customerData() { return (dispatch) => { fetch(API_BASE_URL + "/customer/me", { method: "POST", headers: { "Content-type": "application/json; charset=UTF-8", Authorization: "Bearer " + localStorage.getItem(ACCESS_TOKEN), }, body: JSON.stringify({ email: localStorage.getItem(EMAIL), }), }) .then((res) => res.json()) .then((data) => { if (data) { console.log("succes", data); dispatch(setCustometData(data)); } else if (data && !data.token) { console.log("error", data); } }) .catch(function (err) { console.log("error", err); }); }; } export function getAllProducts(searchText) { return (dispatch) => { fetch( API_BASE_URL + "/product/getAll?searchText=" + searchText + "&userId=" + localStorage.getItem(ID), { method: "GET", headers: { "Content-type": "application/json; charset=UTF-8", Authorization: "Bearer " + localStorage.getItem(ACCESS_TOKEN), }, } ) .then((res) => res.json()) .then((data) => { if (data) { console.log("ProductsData", data); dispatch(setProductData(data)); } else if (data && !data.token) { console.log("error", data); } }) .catch(function (err) { console.log("error", err); }); }; } export default function reducer(state = intialState, action) { switch (action.type) { case LOGIN_SUCCESS: return { ...state, isLoginSuccess: action.isLoginSuccess, }; case LOGIN_IN_PROCESS: return { ...state, isLoginProgress: action.isLoginProgress, }; case LOGIN_ERROR: return { ...state, loginError: action.loginError, }; case SIGNUP_SUCCESS: return { ...state, isSignupSuccess: action.isSignupSuccess, }; case SIGNUP_IN_PROCESS: return { ...state, isSignupProgress: action.isSignupProgress, }; case SIGNUP_ERROR: return { ...state, signupError: action.signupError, }; case CUSTOMER_DATA: return { ...state, customer: action.customer, }; case PRODUCT_PURCHASING: return { ...state, isProductPurchasing: action.isProductPurchasing, }; case PRODUCT_PURCHASED: return { ...state, isProductPurchased: action.isProductPurchased, }; case PRODUCT_DATA: return { ...state, productsData: action.productsData, }; default: return state; } } <file_sep>/node-app/controller/customer.js const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const Customer = require("../models/customer"); exports.signup = async function (req, res, next) { const email = req.body.email; const name = req.body.name; const password = req.body.password; var existCustomer = await Customer.findOne({ email: email }); if (existCustomer) { res.status(201).json({ message: "Customer with this email already exist!", }); } bcrypt .hash(password, 12) .then((hashedPw) => { const customer = new Customer({ email: email, password: <PASSWORD>, name: name, }); return customer.save(); }) .then((result) => { res.status(201).json({ message: "Customer created!", customer: result, }); }) .catch((err) => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); }; exports.login = (req, res, next) => { const email = req.body.email; const password = req.<PASSWORD>; let loadedUser; Customer.findOne({ email: email }) .then((customer) => { if (!customer) { const error = new Error( "A customer with this email could not be found." ); error.statusCode = 401; throw error; } loadedUser = customer; return bcrypt.compare(password, customer.password); }) .then((isEqual) => { if (!isEqual) { const error = new Error("Wrong password!"); error.statusCode = 401; throw error; } const token = jwt.sign( { email: loadedUser.email, _id: loadedUser._id.toString(), }, "my-product-customer-secret", { expiresIn: "1h" } ); res.status(200).json({ token: token, _id: loadedUser._id.toString(), email: loadedUser.email, }); }) .catch((err) => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); }; exports.me = (req, res, next) => { const email = req.body.email; Customer.findOne({ email: email }) .then((customer) => { if (!customer) { const error = new Error( "A customer with this email could not be found." ); error.statusCode = 401; throw error; } res.status(200).json({ _id: customer._id.toString(), email: customer.email, }); }) .catch((err) => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); }; <file_sep>/node-app/controller/product.js const Product = require("../models/product"); const Customer = require("../models/customer"); const Transaction = require("../models/Transaction"); exports.purchase = async function (req, res, next) { const name = req.body.name; const price = req.body.price; const shopName = req.body.shopName; const status = req.body.status; const userId = req.body.userId; var customer = await Customer.findById(userId); try { if (!customer) { res.status(403).json({ message: "Customer not available" }); } const product = new Product({ name: name, price: price, shopName: shopName, status: status, customer: customer._id, }); var addedProduct = await product.save(); if (!addedProduct) { res.status(403).json({ message: "Product has not added" }); } } catch (err) { if (!err.statusCode) { err.statusCode = 500; } next(err); } var transaction = new Transaction({ product: addedProduct._id, customer: customer._id, }); transaction .save() .then((result) => { res.status(201).json({ message: "Product purchased!", data: result, }); }) .catch((err) => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); }; exports.get = (req, res, next) => { const id = req.params.id; Product.findById(id) .then((product) => { if (!product) { const error = new Error("Could not find product."); error.statusCode = 404; throw error; } res.status(200).json({ message: "Product fetched.", product: product }); }) .catch((err) => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); }; exports.getAll = (req, res, next) => { const searchText = req.query.searchText; const customerId = req.query.userId; console.log("searchText", searchText); Product.find({ customer: customerId, name: { $regex: `(?i)(?<=|^)${searchText}(?=|$)` }, }) .then((products) => { res.status(200).json({ message: "Fetched product successfully.", products: products, }); }) .catch((err) => { if (!err.statusCode) { err.statusCode = 500; } next(err); }); }; <file_sep>/react-app/src/components/LoginForm/LoginForm.js import React, { useState, useEffect } from "react"; import "./LoginForm.css"; import { withRouter } from "react-router-dom"; import { connect } from "react-redux"; import { login } from "../../reducers/reducer"; import { ACCESS_TOKEN } from "../../constants/config"; function LoginForm(props) { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); useEffect(() => { if (localStorage.getItem(ACCESS_TOKEN)) { redirectToHome(); } else if (props.isLoginSuccess && !props.loginError) { console.log("Login is successfull"); redirectToHome(); } else if (!props.isLoginSuccess && props.loginError) { console.log("Login is unsuccessfull"); } }, [props.isLoginSuccess]); const handleSubmitClick = () => { if (!email) { return; } if (!password) { return; } props.login(email, password); }; const redirectToHome = () => { props.updateTitle("Home"); props.history.push("/home"); }; const redirectToRegister = () => { props.history.push("/register"); props.updateTitle("Register Customer"); }; return ( <div className="container d-flex align-items-center flex-column"> <div className="card col-12 col-lg-4 login-card mt-2 hv-center"> <form> <div className="form-group text-left"> <label htmlFor="exampleInputEmail1">Email address</label> <input type="email" className="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value={email} onChange={(e) => { setEmail(e.target.value); }} /> </div> <div className="form-group text-left"> <label htmlFor="exampleInputPassword1">Password</label> <input type="<PASSWORD>" className="form-control" id="password" placeholder="<PASSWORD>" value={password} onChange={(e) => { setPassword(e.target.value); }} /> </div> <div className="form-check"></div> <button type="button" className="btn btn-primary" onClick={handleSubmitClick} > Submit </button> </form> <div className="registerMessage"> <span>Dont have an account? </span> <span className="loginText" onClick={() => redirectToRegister()}> Register Customer </span> </div> </div> </div> ); } const mapStateToProps = (state) => { return { isLoginProgress: state.isLoginProgress, isLoginSuccess: state.isLoginSuccess, loginError: state.loginError, }; }; const mapDispatchToProps = (dispatch) => { return { login: (email, password) => dispatch(login(email, password)), }; }; export default withRouter( connect(mapStateToProps, mapDispatchToProps)(LoginForm) );
2622eef912b324c08e83348856ff1f968540b37e
[ "JavaScript" ]
7
JavaScript
mangalpandey/sample-app
f8aa30000afa9e6d87c9b00c65f49dba26a75337
01d92673ae9cc21c4d57eb7b03787cbd8e3c3781
refs/heads/master
<repo_name>minivan/random-scripts<file_sep>/debs/bootstrap_os.sh # installing the e-mail client # i like Yorba sudo add-apt-repository ppa:yorba/ppa apt-get update sudo apt-get install geary <file_sep>/os/network_start.sh #!/bin/sh iface=wlan0 ifconfig $iface down iwconfig $iface mode Managed ifconfig $iface up killall wpa_supplicant wpa_supplicant -B -Dwext -i $iface -c ./wireless-wpa.conf -dd dhclient $iface <file_sep>/os/xubuntu_clean.sh sudo apt-get install -y zsh git-core vim curl zlib1g-dev build-essential openjdk-6-jdk openjdk-6-jre tmux \ openssl libreadline6 libreadline6-dev git-core libssl-dev libyaml-dev \ libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev \ automake libtool bison subversion git nodejs xfce4-terminal # setup the terminal theme to solarized light mkdir .config/Terminal curl https://raw.github.com/sgerrand/xfce4-terminal-colors-solarized/master/light/terminalrc > .config/Terminal/terminalrc # download and install the inconsolata font (using the appropriate patched version for the vim powerline) mkdir -p ~/.fonts/monospace curl https://gist.github.com/raw/1595572/51bdd743cc1cc551c49457fe1503061b9404183f/Inconsolata-dz-Powerline.otf > .fonts/monospace/Inconsolata.otf # set it as the primary font for the xfce4-terminal echo "FontName=Inconsolata Medium 14" >> .config/Terminal/terminalrc # install oh-my-zsh wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh # ==========THEME=========== # create the .themes folder mkdir -p ~/.themes # get the window decorations curl http://xfce-look.org/CONTENT/content-files/87476-darksun-xfce4.tar.bz2 > ~/.themes/window_dec.tar.bz2 cd ~/.themes tar xjvf window.tar.bz2 # clean up rm window.tar.bz2 # now replace the default theme name from ~/.config/xfce4/xfconf/xfce-perchannel-xml to Darksun # personal stuff: # 1. clone my .dotfiles git clone --recursive git://github.com/minivan/.dotfiles.git # 2. create symlink for .vimrc ln -s ~/.dotfiles/.vimrc ~/.vimrc # 3. create symlink for .zshrc ln -s ~/.dotfiles/.zshrc ~/.zshrc #configure git git config --global user.name "<NAME>" git config --global user.email <EMAIL> git config --global core.editor "vim" #install rvm curl -L https://get.rvm.io | zsh #let's use the heroku toolbelt! wget -qO- https://toolbelt.heroku.com/install.sh | sh #change the shell to zsh chsh -s `which zsh` #reboot! sudo shutdown -r now <file_sep>/README.md My Random scripts ============== Some scripts I might use. I might not. Maybe somebody else will. 1. Clean Xubuntu setup --- A poem to my future self: When I find myself in times of trouble And the netbook is failing me Do a clean install and wget -qO- https://raw.github.com/minivan/random-scripts/master/os/xubuntu_clean.sh | sh It doesn't rhyme, my future self, but the old you was a lousy poet. The chorus was the last line repeated four times. `C Am G F C`
f41781f6ded10f1afaa5e6e1900bcd5346bc035f
[ "Markdown", "Shell" ]
4
Shell
minivan/random-scripts
0efb873a72d4933ac516f8308056df84ea4c2c45
4f7093efd33e98944901f9d00df590e1eb27277e
refs/heads/master
<repo_name>hone/lokomo<file_sep>/lib/lokomo/cli.rb require 'lokomo' require 'thor' require 'tmpdir' require 'fileutils' module Lokomo class CLI < Thor desc "compile REPO_DIR", "runs bin/compile from the buildpack" def compile(repo_dir) buildpack_dir = "." build_dir = Dir.mktmpdir("build-") puts "build dir: #{build_dir}" Dir.mktmpdir("cache-") do |cache_dir| puts "cache dir: #{cache_dir}" FileUtils.rmdir(build_dir) FileUtils.cp_r(repo_dir, build_dir) pipe("#{buildpack_dir}/bin/compile #{build_dir} #{cache_dir}") end end private # run a shell command and stream the output # @param [String] command to be run def pipe(command) output = "" IO.popen(command) do |io| until io.eof? buffer = io.gets output << buffer puts buffer end end output end end end <file_sep>/lib/lokomo.rb require "lokomo/version" module Lokomo # Your code goes here... end <file_sep>/bin/lokomo #!/usr/bin/env ruby require 'lokomo/cli' Lokomo::CLI.start(ARGV)
f02dcb0f508826b7de97c6b1139ec5f6e759c9bb
[ "Ruby" ]
3
Ruby
hone/lokomo
6439db34954d6a739d0519e7662659cef626bf86
e0265f6675b28091b0c40c7912b8f89b898ae851
refs/heads/master
<repo_name>sv2901/land_partioner<file_sep>/README.md This is my minor project which helps with the problem of multi-cropping. It uses simplex algorithm to determine the best set of division for land, it uses parameters like budget, area and cost to optimize profit. <file_sep>/main.c #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <assert.h> #include<conio.h> char GJ[][20]={"Rice/Paddy","Greengram","Maize","Wheat","Gram","Pulses"}; char UP[][20]={"Rice/Paddy","Greengram","Redgram/Arhar","Masur/Lentil","Wheat","Peas","Chick Pea","Blackgram/Urd","Gram",}; char WB[][20]={"Rice/Paddy","Greengram","Redgram/Arhar","Masur/Lentil","Wheat","Gram","Pulses","Blackgram/Urd"}; double Profit_GJ[]={50975,18976,20800,15390,18000,22000}; double Profit_UP[]={50975,18976,29261,21138,15390,4108,17000,19000,18000}; double Profit_WB[]={50975,18976,29261,21138,15390,18000,22000,19000}; double Cost_GJ[]={17000,13778,15200,19000,15136,9000}; double Cost_UP[]={17000,13778,14047,15824,19000,6100,111700,15136,15136}; double Cost_WB[]={17000,13778,14047,15824,19000,15136,9000,15136}; int up=10,gj=7,wb=9,NOC=0; int cho=0,check=0; float area=0; double budget=0; void ShowStates() { printf(" WELCOME TO THE LAND PARTITIONER \n\n\n KINDLY CHOOSE FROM THE FOLLOWING STATES\n\n "); xyz: printf("1)UTTAR PRADESH\n 2)WEST BENGAL\n 3)GUJRAT\n CHOICE:"); scanf("%d",&cho); switch(cho) { case 1: for(int i=0;i<=8;i++) { printf("%d)",i+1); printf("%s\n",UP[i]); } NOC=up; break; case 2: for(int i=0;i<=7;i++) { printf("%d)",i+1); printf("%s\n",WB[i]); }NOC=wb; break; case 3: for(int i=0;i<=5;i++) { printf("%d)",i+1); printf("%s\n",GJ[i]); }NOC=gj; break; default: printf("WRONG INPUT\n"); goto xyz; } printf("ENTER LAND AREA MEASUREMENT IN ACRE \n"); scanf("%f",&area); if(area<0.162) { UP[0][20]=NULL; WB[0][20]=NULL; GJ[0][20]=NULL; printf("RICE HAS BEEN OMITTED DUE TO INSUFFICIENT AREA\n\n"); } switch(cho) { case 1: for(int i=0;i<9;i++) { } } printf("Enter your budget in Rs. :"); scanf("%lf",&budget); printf("\n\n"); ShowOmitScreen(cho); return cho; } void ShowOmitScreen(int cho) { int o=0,*ptr,i=0,j=0; char ch; printf("ANY PARTICULAR CROPS TO OMIT?\n\n"); printf("\nPRESS 'Y' FOR YES & 'N' FOR NO:"); scanf("%s",&ch); if(ch=='y'||ch=='Y') { printf("ENTER THE NUMBER OF CROPS TO OMIT"); scanf("%d",&o);//3 abc: ptr = (int*) calloc(o, sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter crop serial no.: "); for(i = 0; i < o; ++i) { scanf("%d", ptr + i); } switch(cho) { case 1: for(i = 0; i < o; ++i) { if(*(ptr+i)<10 && *(ptr+i)>0) { UP[*(ptr+i)-2][20]=NULL; Profit_UP[*(ptr+i)-1]=0; Cost_UP[*(ptr+i)-1]=0; } else { printf("INVALID INPUT TRY AGAIN\n\n"); free(ptr); goto abc; } } for(int i=0;i<=8;i++) { printf("%d)",i+1); printf("%s\n",UP[i]); } NOC=up-o; break; case 2: for(i = 0; i < o; ++i) { if(*(ptr+i)<7 && *(ptr+i)>0) { WB[*(ptr+i)-2][20]=NULL; Profit_WB[*(ptr+i)-1]=0; Cost_WB[*(ptr+i)-1]=0; } else { printf("INVALID INPUT TRY AGAIN\n\n"); free(ptr); goto abc; } } for(int i=0;i<=5;i++) { printf("%d)",i+1); printf("%s\n",WB[i]); } NOC=wb-o; break; case 3: for(i = 0; i < o; ++i) { if(*(ptr+i)<9 && *(ptr+i)>0) { GJ[*(ptr+i)-1][20]=NULL; Profit_GJ[*(ptr+i)-1]=0; Cost_GJ[*(ptr+i)-1]=0; } else { printf("INVALID INPUT TRY AGAIN\n\n"); free(ptr); goto abc; } } for(int i=0;i<=7;i++) { printf("%d)",i+1); printf("%s\n",GJ[i]); } NOC=gj-o; break; } free(ptr); } } #define M 20 #define N 20 static const double epsilon = 1.0e-8; int equal(double a, double b) { return fabs(a-b) < epsilon; } typedef struct { int m, n; // m=rows, n=columns, mat[m x n] double mat[M][N]; } Tableau; void nl(int k){ int j; for(j=0;j<k;j++) putchar('-'); putchar('\n'); } Tableau tab; void TableauInput() { check++; int i=0,j=0,p=0,c=0; float MAPC=0; //Max area per crop if(NOC>3) MAPC=((area*25)/100); else if(NOC>=2) MAPC=((area*50)/100); else MAPC=area; tab.m=2+NOC; tab.n=NOC; tab.mat[0][0]=0; tab.mat[1][0]=area; tab.mat[2][0]=budget; for(i=3;i<tab.m;i++) tab.mat[i][0]=MAPC; for(i=0;i<tab.m;i++) { for(j=1;j<NOC;j++) { if(i==0) { switch(cho) { case 1: while(Profit_UP[p]==0) { p++; } tab.mat[i][j]=-Profit_UP[p]; p++; break; case 2: while(Profit_WB[p]==0) { p++; } tab.mat[i][j]=-Profit_WB[p]; p++; break; case 3: while(Profit_GJ[p]==0) { p++; } tab.mat[i][j]=-Profit_GJ[p]; p++; break; } } else if(i==1) { tab.mat[i][j]=1; } else if(i==2) { switch(cho) { case 1: while(Cost_UP[c]==0) { c++; } tab.mat[i][j]=Cost_UP[c]; c++; break; case 2: while(Cost_WB[c]==0) { c++; } tab.mat[i][j]=Cost_WB[c]; c++; break; case 3: while(Cost_GJ[c]==0) { c++; } tab.mat[i][j]=Cost_GJ[c]; c++; break; } } else { int k=1; for(i=3;i<tab.m;i++) { for(j=1;j<NOC;j++) { if(j==k) tab.mat[i][j]=1; else tab.mat[i][j]=0; } k++; } } } } } void read_tableau(Tableau *tab, const char * filename) { int err, i, j; FILE * fp; fp = fopen(filename, "r" ); if( !fp ) { printf("Cannot read %s\n", filename); exit(1); } memset(tab, 0, sizeof(*tab)); err = fscanf(fp, "%d %d", &tab->m, &tab->n); if (err == 0 || err == EOF) { printf("Cannot read m or n\n"); exit(1); } for(i=0;i<tab->m; i++) { for(j=0;j<tab->n; j++) { err = fscanf(fp, "%lf", &tab->mat[i][j]); if (err == 0 || err == EOF) { printf("Cannot read A[%d][%d]\n", i, j); exit(1); } } } printf("Read tableau [%d rows x %d columns] from file '%s'.\n", tab->m, tab->n, filename); fclose(fp); } void print_tableau(Tableau *tab, const char* mes) { static int counter=0; int i, j; printf("\n%d. Tableau %s:\n", ++counter, mes); nl(70); printf("%-6s%5s", "col:", "b[i]"); for(j=1;j<tab->n; j++) { printf(" x%d,", j); } printf("\n"); for(i=0;i<tab->m; i++) { if (i==0) printf("max:"); else printf("b%d: ", i); for(j=0;j<tab->n; j++) { if (equal((int)tab->mat[i][j], tab->mat[i][j])) printf(" %6d", (int)tab->mat[i][j]); else printf(" %6.2lf", tab->mat[i][j]); } printf("\n"); } nl(70); } void pivot_on(Tableau *tab, int row, int col) { int i, j; double pivot; pivot = tab->mat[row][col]; assert(pivot>0); for(j=0;j<tab->n;j++) tab->mat[row][j] /= pivot; assert( equal(tab->mat[row][col], 1. )); for(i=0; i<tab->m; i++) { // foreach remaining row i do double multiplier = tab->mat[i][col]; if(i==row) continue; for(j=0; j<tab->n; j++) { // r[i] = r[i] - z * r[row]; tab->mat[i][j] -= multiplier * tab->mat[row][j]; } } } // Find pivot_col = most negative column in mat[0][1..n] int find_pivot_column(Tableau *tab) { int j, pivot_col = 1; double lowest = tab->mat[0][pivot_col]; for(j=1; j<tab->n; j++) { if (tab->mat[0][j] < lowest) { lowest = tab->mat[0][j]; pivot_col = j; } } printf("Most negative column in row[0] is col %d = %g.\n", pivot_col, lowest); if( lowest >= 0 ) { return -1; // All positive columns in row[0], this is optimal. } return pivot_col; } // Find the pivot_row, with smallest positive ratio = col[0] / col[pivot] int find_pivot_row(Tableau *tab, int pivot_col) { int i, pivot_row = 0; double min_ratio = -1; printf("Ratios A[row_i,0]/A[row_i,%d] = [",pivot_col); for(i=1;i<tab->m;i++){ double ratio = tab->mat[i][0] / tab->mat[i][pivot_col]; printf("%3.2lf, ", ratio); if ( (ratio > 0 && ratio < min_ratio ) || min_ratio < 0 ) { min_ratio = ratio; pivot_row = i; } } printf("].\n"); if (min_ratio == -1) return -1; // Unbounded. printf("Found pivot A[%d,%d], min positive ratio=%g in row=%d.\n", pivot_row, pivot_col, min_ratio, pivot_row); return pivot_row; } void add_slack_variables(Tableau *tab) { int i, j; for(i=1; i<tab->m; i++) { for(j=1; j<tab->m; j++) tab->mat[i][j + tab->n -1] = (i==j); } tab->n += tab->m -1; } void check_b_positive(Tableau *tab) { int i; for(i=1; i<tab->m; i++) assert(tab->mat[i][0] >= 0); } // Given a column of identity matrix, find the row containing 1. // return -1, if the column as not from an identity matrix. int find_basis_variable(Tableau *tab, int col) { int i, xi=-1; for(i=1; i < tab->m; i++) { if (equal( tab->mat[i][col],1) ) { if (xi == -1) xi=i; // found first '1', save this row number. else return -1; // found second '1', not an identity matrix. } else if (!equal( tab->mat[i][col],0) ) { return -1; // not an identity matrix column. } } return xi; } void print_optimal_vector(Tableau *tab, char *message) { int j, xi; printf("%s at ", message); for(j=1;j<tab->n;j++) { // for each column. xi = find_basis_variable(tab, j); if (xi != -1) printf("x%d=%3.2lf, ", j, tab->mat[xi][0] ); else printf("x%d=0, ", j); } printf("\n"); } void simplex(Tableau *tab) { int loop=0; add_slack_variables(tab); check_b_positive(tab); print_tableau(tab,"Padded with slack variables"); while( ++loop ) { int pivot_col, pivot_row; pivot_col = find_pivot_column(tab); if( pivot_col < 0 ) { printf("Found optimal value=A[0,0]=%3.2lf (no negatives in row 0).\n", tab->mat[0][0]); print_optimal_vector(tab, "Optimal vector"); break; } printf("Entering variable x%d to be made basic, so pivot_col=%d.\n", pivot_col, pivot_col); pivot_row = find_pivot_row(tab, pivot_col); if (pivot_row < 0) { printf("unbounded (no pivot_row).\n"); break; } printf("Leaving variable x%d, so pivot_row=%d\n", pivot_row, pivot_row); pivot_on(tab, pivot_row, pivot_col); print_tableau(tab,"After pivoting"); print_optimal_vector(tab, "Basic feasible solution"); if(loop > 20) { printf("Too many iterations > %d.\n", loop); break; } } } void Print_EndResult(Tableau *tab) { nl(70); printf("\n"); int k=0; for(int i=1;i<NOC;i++) { printf("x%d:",i); if(strlen(UP[k])==0 ) k++; printf("%s\n",UP[k]); k++; } } int main(int argc, char *argv[]) { char ch; ShowStates(); TableauInput(); if (argc > 1) { // usage: cmd datafile read_tableau(&tab, argv[1]); } print_tableau(&tab,"Initial"); simplex(&tab); Print_EndResult(&tab); printf("Press 1 to EXIT"); while(1) { ch=getch(); if(ch=='1') return 0; } }
8dbdb17af833deb1558d010cfe5bf101d8730ec9
[ "Markdown", "C" ]
2
Markdown
sv2901/land_partioner
6ff7ff39fc1c1e8839b48ead3dc3d6ec750cd6aa
7208053ec706721ea9d4bea9e34147a39dd493ac
refs/heads/master
<repo_name>braddevans/mcbankmysql<file_sep>/src/main/java/uk/co/breadhub/mysqlecon/database/DatabaseImpl.java package uk.co.breadhub.mysqlecon.database; import uk.co.breadhub.mysqlecon.Main; import java.sql.*; import java.util.UUID; public class DatabaseImpl { private static final String host = Main.getInstance().getConfig().getString("Database.Hostname"); private static final String port = Main.getInstance().getConfig().getString("Database.Port"); private static final String database = Main.getInstance().getConfig().getString("Database.Database"); private static final String username = Main.getInstance().getConfig().getString("Database.Username"); private static final String password = Main.getInstance().getConfig().getString("Database.Password"); private static Connection con; /** * Connects to Database */ public void connect() { String UrlString = "jdbc:mysql://" + host + ":" + port + "/" + database + ""; try { Class.forName("com.mysql.jdbc.Driver"); try { con = DriverManager.getConnection(UrlString, username, password); } catch(Exception ex) { System.out.println("Failed to create the database connection. :"); ex.printStackTrace(); } } catch(ClassNotFoundException ex) { System.out.println("Driver not found."); } } /** * Disconnects from the Database */ public void disconnect(){ try { getConnection().close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * Gets Database Connection * @return */ public Connection getConnection() { try { if(con == null || con.isClosed()) { connect(); } } catch(Exception e) { e.printStackTrace(); } return con; } /** * Initialises the Database */ public void init() { String sql = "CREATE TABLE IF NOT EXISTS `" + database + "`.`Global_banktable` ( " + "`UUID` VARCHAR(64) NOT NULL , " + "`balance` int(42) NOT NULL , UNIQUE(`UUID`), " + "PRIMARY KEY (`UUID`)) " + "ENGINE = InnoDB;"; try { Statement stmt = getConnection().createStatement(); stmt.executeUpdate(sql); } catch(Exception e) { e.printStackTrace(); } } /** * Gets the User Balance * @param uniqueId * @return */ public int userBalance(UUID uniqueId) { int balance = 0; try { PreparedStatement ps = getConnection().prepareStatement("SELECT balance FROM Global_banktable WHERE UUID=?"); ps.setString(1, uniqueId.toString()); ResultSet rs = ps.executeQuery(); if(rs.next()) { balance = rs.getInt("balance"); } } catch(Exception e) { e.printStackTrace(); } return balance; } /** * Administrator Setting user Balance Function * @param uniqueId * @param amount */ public void adminSet(UUID uniqueId, int amount) { try { PreparedStatement ps = getConnection().prepareStatement("INSERT IGNORE INTO `Global_banktable` (`UUID`, `balance`) VALUES (?,?);"); ps.setString(1, uniqueId.toString()); ps.setInt(2, amount); ps.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } } /** * Deposit into Database as the command Sender * @param uniqueId * @param amount */ public void userDeposit(UUID uniqueId, int amount) { int ammount_ = userBalance(uniqueId) + amount; try { PreparedStatement ps = getConnection().prepareStatement("INSERT IGNORE INTO `Global_banktable` (`UUID`, `balance`) VALUES (?,?) on duplicate key update `balance` = ?;"); ps.setString(1, uniqueId.toString()); ps.setInt(2, ammount_); ps.setInt(3, ammount_); ps.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } } /** * Withdraw from Database as the command Sender into Current servers Econ plugin * @param uniqueId * @param amount */ public void userWithdraw(UUID uniqueId, int amount) { int ammount_ = userBalance(uniqueId) - amount; try { PreparedStatement ps = getConnection().prepareStatement("INSERT IGNORE INTO `Global_banktable` (`UUID`, `balance`) VALUES (?,?) on duplicate key update `balance` = ?;"); ps.setString(1, uniqueId.toString()); ps.setInt(2, ammount_); ps.setInt(3, ammount_); ps.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } } /** * Deposit into Database Through Admin Command * @param uniqueId * @param amount */ public void adminDeposit(UUID uniqueId, int amount) { int ammount_ = userBalance(uniqueId) + amount; try { PreparedStatement ps = getConnection().prepareStatement("INSERT IGNORE INTO `Global_banktable` (`UUID`, `balance`) VALUES (?,?) on duplicate key update `balance` = ?;"); ps.setString(1, uniqueId.toString()); ps.setInt(2, ammount_); ps.setInt(3, ammount_); ps.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } } /** * Remove from Database Through Admin Command * @param uniqueId * @param amount */ public void adminWithdraw(UUID uniqueId, int amount) { int ammount_ = userBalance(uniqueId) - amount; try { PreparedStatement ps = getConnection().prepareStatement("INSERT IGNORE INTO `Global_banktable` (`UUID`, `balance`) VALUES (?,?) on duplicate key update `balance` = ?;"); ps.setString(1, uniqueId.toString()); ps.setInt(2, ammount_); ps.setInt(3, ammount_); ps.executeUpdate(); } catch(Exception e) { e.printStackTrace(); } } } <file_sep>/src/main/java/uk/co/breadhub/mysqlecon/Main.java package uk.co.breadhub.mysqlecon; import com.earth2me.essentials.api.Economy; import org.bukkit.plugin.java.JavaPlugin; import uk.co.breadhub.mysqlecon.database.DatabaseImpl; import uk.co.breadhub.mysqlecon.listeners.CommandListener; import java.util.logging.Logger; public final class Main extends JavaPlugin { private static final Logger log = Logger.getLogger("Minecraft"); private static DatabaseImpl database; private static Economy economy = new Economy(); private static Main instance; @Override public void onEnable() { // Plugin startup logic instance = this; saveDefaultConfig(); //Register Commands getCommand("bank").setExecutor(new CommandListener()); if (!getConfig().getString("Database.Username").equals("testacc")) { // register Database database = new DatabaseImpl(); database.connect(); database.init(); } else { log.info("Plugin Disabled Cannot have account named testacc"); onDisable(); } } @Override public void onDisable() { if (!getConfig().getString("Database.Username").equals("testacc")) { database.disconnect(); } } public static Economy getEconomy() { return economy; } public static Main getInstance() { return instance; } public static DatabaseImpl getDatabase() { return database; } } <file_sep>/src/main/java/uk/co/breadhub/mysqlecon/listeners/CommandListener.java package uk.co.breadhub.mysqlecon.listeners; import com.earth2me.essentials.api.Economy; import com.earth2me.essentials.api.NoLoanPermittedException; import com.earth2me.essentials.api.UserDoesNotExistException; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import uk.co.breadhub.mysqlecon.Main; import uk.co.breadhub.mysqlecon.utils.StringUtils; import java.math.BigDecimal; public class CommandListener implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { try { switch (args.length) { case 0: { sendHelp(sender); break; } case 1: { if (args[0].toLowerCase().equals("balance")) { // get balance from database sender.sendMessage(StringUtils.replaceColors("&7[&6Bank&7] &3You Have&7: &2$" + Main.getDatabase().userBalance(Bukkit.getOfflinePlayer(sender.getName()).getUniqueId()))); } else { sendHelp(sender); } break; } case 2: { switch (args[0]) { case "balance": { if (sender.hasPermission("msbank.balance.others")) { // get selected user balance from database args[1] sender.sendMessage(StringUtils.replaceColors("&7[&6Bank&7] &3User&7: &2" + args[1] + " &3has&7: &2$" + Main.getDatabase().userBalance(Bukkit.getOfflinePlayer(args[1]).getUniqueId()))); } else { sender.sendMessage(StringUtils.replaceColors("&4You do not have permission to use this command")); } break; } case "deposit": { if (Integer.parseInt(args[1]) >= 0.0001) { if (Economy.getMoney(args[1]) >= Integer.parseInt(args[1])) { Main.getDatabase().userDeposit(Bukkit.getOfflinePlayer(sender.getName()).getUniqueId(), Integer.parseInt(args[1])); sender.sendMessage(StringUtils.replaceColors(String.format("&7[&6Bank&7] &3You have Deposited&7: &2$%s", Integer.parseInt(args[1])))); Economy.substract(sender.getName(), BigDecimal.valueOf(Integer.parseInt(args[1]))); break; } else { sender.sendMessage(StringUtils.replaceColors("&4that Would take you into the minuses")); break; } } else { sender.sendMessage(StringUtils.replaceColors("&4You cannot Deposit Minus numbers or 0")); } break; } case "withdraw": { if (Integer.parseInt(args[1]) >= 0.0001) { Main.getDatabase().userWithdraw(Bukkit.getOfflinePlayer(sender.getName()).getUniqueId(), Integer.parseInt(args[1])); sender.sendMessage(StringUtils.replaceColors(String.format("&7[&6Bank&7] &3You have withdrawn&7: &4 $%s", Integer.parseInt(args[1])))); Economy.add(sender.getName(), BigDecimal.valueOf(Integer.parseInt(args[1]))); } else { sender.sendMessage(StringUtils.replaceColors("&4You cannot Withdraw Minus numbers or 0")); } break; } default: sendHelp(sender); break; } break; } case 3: { if (sender.hasPermission("mcbank.admin")) { switch (args[0]) { case "deposit": { if (Integer.parseInt(args[2]) >= 0.0001) { Main.getDatabase().adminDeposit(Bukkit.getOfflinePlayer(args[1]).getUniqueId(), Integer.parseInt(args[2])); sender.sendMessage(StringUtils.replaceColors(String.format("&7[&6Bank&7] &3You have Deposited&7: &4$%s&2 into &3" + args[1] + "&2's bank", Integer.parseInt(args[2])))); Economy.substract(args[1], BigDecimal.valueOf(Integer.parseInt(args[2]))); } else { sender.sendMessage(StringUtils.replaceColors("&4You cannot Deposit Minus numbers or 0")); } break; } case "withdraw": { if (Integer.parseInt(args[2]) >= 0.0001) { sender.sendMessage(StringUtils.replaceColors(String.format("&7[&6Bank&7] &3You have Withdrawn&7: &4$%s&2 from &3" + args[1] + "&2's bank", Integer.parseInt(args[2])))); Main.getDatabase().adminWithdraw(Bukkit.getOfflinePlayer(args[1]).getUniqueId(), Integer.parseInt(args[2])); Economy.add(args[1], BigDecimal.valueOf(Integer.parseInt(args[2]))); } else { sender.sendMessage(StringUtils.replaceColors("&4You cannot Withdraw Minus numbers or 0")); } break; } case "set": { if (Integer.parseInt(args[2]) >= 0.0001) { sender.sendMessage(StringUtils.replaceColors(String.format("&7[&6Bank&7] &3You have Set&7: &4$%s&2 into &3" + args[1] + "&2's bank", Integer.parseInt(args[2])))); Main.getDatabase().adminSet(Bukkit.getOfflinePlayer(args[1]).getUniqueId(), Integer.parseInt(args[2])); Economy.setMoney(args[1], BigDecimal.valueOf(Integer.parseInt(args[2]))); } else { sender.sendMessage(StringUtils.replaceColors("&4You cannot Set Minus numbers or 0")); } break; } default: sendHelp(sender); break; } break; } else { sendHelp(sender); break; } } default: sendHelp(sender); break; } } catch (UserDoesNotExistException | NoLoanPermittedException e) { e.printStackTrace(); } return false; } private void sendHelp(CommandSender sender) { sender.sendMessage(StringUtils.replaceColors("&6=&5=&6=&5=&6=&5=&6=&7[&9Bank Help&7]=&6=&5=&6=&5=&6=&5=&6=")); sender.sendMessage(" "); sender.sendMessage(" "); sender.sendMessage(StringUtils.replaceColors(" &5User Commands&7:")); sender.sendMessage(StringUtils.replaceColors(" &7/bank balance")); sender.sendMessage(StringUtils.replaceColors(" &7/bank withdraw &8<ammount>")); sender.sendMessage(StringUtils.replaceColors(" &7/bank deposit &8<ammount>")); sender.sendMessage(" "); if (sender.hasPermission("msbank.admin")) { sender.sendMessage(StringUtils.replaceColors(" &4Admin / Staff Commands&7:")); sender.sendMessage(StringUtils.replaceColors(" &7/bank balance &6<User>")); sender.sendMessage(StringUtils.replaceColors(" &7/bank withdraw &6<user> &8<ammount>")); sender.sendMessage(StringUtils.replaceColors(" &7/bank deposit &6<user> &8<ammount>")); sender.sendMessage(StringUtils.replaceColors(" &7/bank set &6<user> &8<ammount>")); sender.sendMessage(" "); } } } <file_sep>/settings.gradle rootProject.name = 'mysqlecon'
8fbaa716be3e3489f6292fa04da2846019b67b29
[ "Java", "Gradle" ]
4
Java
braddevans/mcbankmysql
82a148308708efeba6f0652aa5e854ca1bb5f1ad
c2f7d1ccf2b7af2e50b2790e30ae7a742c59e4b6
refs/heads/main
<file_sep>#include "pch-cpp.hpp" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable4[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable5[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable6[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable7[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable8[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable9[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable11[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable13[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable14[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable15[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable16[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable18[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable19[13]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable20[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable21[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable22[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable25[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable26[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable27[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable28[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable29[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable30[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable31[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable32[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable33[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable34[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable35[19]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable36[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable37[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable38[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable39[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable40[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable41[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable42[13]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable43[22]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable46[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable47[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable48[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable49[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable50[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable51[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable53[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable55[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable56[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable64[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable65[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable66[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable67[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable68[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable72[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable73[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable74[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable75[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable76[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable77[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable78[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable79[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable80[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable81[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable82[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable83[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable98[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable100[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable105[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable106[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable107[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable108[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable109[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable111[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable113[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable114[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable115[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable117[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable118[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable119[145]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable120[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable121[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable122[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable125[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable126[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable127[45]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable128[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable129[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable130[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable131[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable132[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable133[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable137[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable138[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable140[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable141[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable142[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable145[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable146[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable151[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable152[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable154[22]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable155[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable156[40]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable157[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable158[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable159[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable160[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable161[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable162[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable163[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable164[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable165[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable166[33]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable167[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable168[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable169[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable170[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable171[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable183[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable184[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable185[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable190[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable194[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable195[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable201[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable203[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable204[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable205[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable209[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable211[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable213[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable214[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable215[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable216[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable217[19]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable219[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable221[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable223[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable224[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable225[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable226[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable227[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable231[29]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable232[47]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable233[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable234[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable235[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable236[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable237[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable238[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable239[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable240[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable241[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable243[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable244[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable245[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable246[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable247[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable248[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable249[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable251[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable253[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable254[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable255[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable256[23]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable258[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable259[48]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable260[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable261[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable263[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable265[23]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable266[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable267[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable270[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable272[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable273[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable274[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable275[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable276[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable277[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable278[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable279[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable280[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable281[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable282[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable283[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable284[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable285[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable286[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable288[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable290[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable291[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable292[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable293[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable294[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable296[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable297[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable299[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable300[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable301[26]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable303[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable304[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable305[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable307[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable308[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable309[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable310[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable311[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable312[44]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable313[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable314[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable315[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable316[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable317[35]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable318[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable319[396]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable320[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable321[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable322[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable323[19]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable328[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable331[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable332[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable333[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable334[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable335[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable337[20]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable338[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable340[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable341[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable342[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable343[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable344[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable345[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable346[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable348[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable349[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable351[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable352[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable353[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable356[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable357[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable358[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable359[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable360[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable361[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable362[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable363[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable364[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable367[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable368[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable369[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable370[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable371[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable372[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable373[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable374[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable375[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable376[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable377[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable379[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable380[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable381[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable382[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable383[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable384[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable385[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable386[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable387[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable388[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable390[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable391[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable392[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable393[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable394[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable395[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable396[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable397[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable398[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable399[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable400[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable403[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable404[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable406[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable407[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable408[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable409[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable410[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable411[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable412[22]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable413[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable414[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable415[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable418[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable419[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable420[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable421[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable422[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable423[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable424[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable425[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable426[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable427[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable428[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable429[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable430[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable431[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable432[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable434[21]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable435[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable436[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable437[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable438[20]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable439[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable442[23]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable445[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable446[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable447[25]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable449[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable450[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable452[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable453[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable454[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable455[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable456[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable457[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable461[33]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable465[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable466[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable467[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable468[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable469[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable471[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable472[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable474[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable475[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable477[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable478[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable479[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable482[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable484[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable487[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable488[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable490[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable492[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable497[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable498[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable503[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable504[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable506[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable515[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable521[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable524[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable525[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable526[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable531[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable532[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable534[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable535[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable537[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable538[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable540[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable541[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable542[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable544[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable545[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable547[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable548[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable549[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable550[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable552[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable553[13]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable554[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable556[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable557[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable558[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable560[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable561[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable562[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable563[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable565[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable567[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable568[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable569[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable570[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable571[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable574[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable575[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable576[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable577[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable578[27]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable579[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable580[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable581[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable582[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable583[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable585[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable586[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable588[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable589[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable590[21]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable591[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable592[25]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable593[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable594[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable595[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable596[84]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable597[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable598[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable599[25]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable600[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable601[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable602[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable603[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable604[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable605[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable606[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable607[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable608[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable609[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable610[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable611[20]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable612[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable613[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable614[36]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable615[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable617[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable618[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable619[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable620[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable621[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable622[31]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable623[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable624[21]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable625[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable626[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable627[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable628[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable629[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable630[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable631[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable632[38]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable633[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable634[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable636[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable637[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable638[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable639[13]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable640[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable641[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable642[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable643[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable644[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable646[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable647[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable648[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable649[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable651[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable652[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable653[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable655[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable658[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable661[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable662[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable663[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable664[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable665[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable675[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable676[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable677[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable679[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable680[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable681[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable687[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable688[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable689[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable690[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable691[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable692[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable694[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable697[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable699[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable700[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable705[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable706[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable707[39]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable709[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable710[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable713[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable714[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable715[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable716[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable718[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable719[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable721[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable722[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable723[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable724[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable726[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable727[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable728[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable729[22]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable730[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable732[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable733[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable734[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable735[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable738[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable739[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable741[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable742[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable743[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable744[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable745[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable746[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable747[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable748[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable749[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable750[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable752[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable753[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable755[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable756[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable757[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable758[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable761[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable762[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable766[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable770[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable771[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable772[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable773[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable777[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable778[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable786[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable787[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable788[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable789[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable790[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable791[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable792[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable793[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable794[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable795[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable796[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable798[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable799[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable805[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable806[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable807[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable808[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable809[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable810[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable811[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable812[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable813[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable814[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable815[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable816[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable817[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable818[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable821[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable822[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable823[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable824[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable825[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable826[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable827[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable828[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable829[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable830[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable831[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable832[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable833[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable834[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable835[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable836[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable837[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable839[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable840[20]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable841[47]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable842[24]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable843[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable844[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable845[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable846[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable847[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable848[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable849[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable850[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable851[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable852[20]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable853[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable854[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable855[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable856[21]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable857[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable858[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable859[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable860[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable861[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable862[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable863[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable864[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable865[24]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable866[21]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable867[25]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable868[41]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable869[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable870[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable871[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable872[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable873[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable874[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable875[13]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable876[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable877[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable878[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable879[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable880[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable884[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable885[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable886[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable887[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable888[13]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable889[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable890[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable891[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable894[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable895[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable896[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable897[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable900[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable901[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable902[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable903[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable904[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable905[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable906[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable907[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable909[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable911[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable912[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable913[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable917[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable918[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable919[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable920[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable921[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable922[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable923[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable924[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable926[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable938[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable939[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable940[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable941[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable942[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable944[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable952[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable953[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable954[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable956[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable961[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable962[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable963[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable965[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable967[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable968[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable969[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable970[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable971[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable972[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable973[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable974[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable975[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable976[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable977[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable978[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable979[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable980[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable981[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable982[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable983[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable984[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable986[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable987[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable997[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable998[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable999[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1000[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1001[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1002[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1003[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1004[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1008[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1009[13]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1011[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1012[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1013[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1016[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1018[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1019[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1020[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1021[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1022[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1023[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1024[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1025[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1026[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1027[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1032[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1033[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1034[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1035[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1036[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1037[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1038[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1039[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1040[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1041[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1042[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1043[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1046[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1047[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1049[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1050[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1053[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1057[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1059[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1061[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1062[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1063[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1064[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1065[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1066[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1067[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1068[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1069[45]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1070[39]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1072[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1077[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1078[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1079[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1080[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1081[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1082[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1083[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1085[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1089[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1090[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1091[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1092[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1093[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1094[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1110[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1111[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1112[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1114[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1115[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1116[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1117[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1118[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1121[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1122[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1123[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1124[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1126[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1127[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1139[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1140[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1141[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1142[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1144[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1145[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1147[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1148[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1150[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1151[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1152[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1153[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1154[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1155[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1156[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1157[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1161[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1164[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1165[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1166[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1167[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1168[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1169[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1170[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1171[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1172[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1177[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1178[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1183[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1204[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1205[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1209[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1210[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1211[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1212[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1213[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1214[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1215[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1216[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1217[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1218[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1220[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1262[101]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1272[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1279[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1284[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1289[56]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1290[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1291[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1292[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1293[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1294[29]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1296[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1297[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1298[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1299[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1300[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1301[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1302[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1303[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1305[26]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1310[30]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1311[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1313[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1314[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1316[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1317[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1319[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1320[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1321[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1323[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1324[19]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1325[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1326[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1327[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1328[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1329[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1330[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1331[20]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1333[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1334[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1335[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1337[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1341[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1342[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1343[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1351[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1352[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1353[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1355[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1356[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1357[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1358[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1360[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1361[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1362[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1363[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1365[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1366[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1367[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1368[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1369[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1370[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1372[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1373[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1374[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1375[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1376[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1379[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1380[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1381[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1382[32]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1383[48]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1386[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1410[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1411[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1412[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1413[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1414[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1416[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1417[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1418[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1421[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1425[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1428[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1429[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1430[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1431[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1432[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1433[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1434[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1436[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1437[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1440[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1441[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1442[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1443[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1446[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1450[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1451[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1452[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1454[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1456[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1457[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1458[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1459[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1460[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1461[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1468[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1469[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1470[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1471[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1487[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1488[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1489[41]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1490[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1491[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1492[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1493[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1494[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1497[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1498[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1499[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1500[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1501[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1502[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1504[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1505[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1507[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1508[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1509[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1511[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1513[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1514[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1515[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1516[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1517[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1518[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1519[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1520[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1522[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1523[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1526[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1527[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1533[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1534[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1536[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1537[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1538[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1539[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1540[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1541[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1542[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1543[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1544[71]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1545[29]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1546[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1547[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1548[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1549[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1550[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1552[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1554[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1562[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1563[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1565[327]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1568[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1569[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1570[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1571[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1572[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1573[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1574[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1575[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1576[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1577[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1578[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1582[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1583[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1584[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1585[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1587[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1589[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1590[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1592[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1593[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1598[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1604[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1611[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1615[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1616[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1617[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1619[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1622[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1624[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1626[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1627[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1629[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1630[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1631[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1632[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1635[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1636[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1645[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1648[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1649[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1650[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1651[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1652[26]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1654[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1656[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1657[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1660[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1664[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1665[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1667[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1668[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1669[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1670[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1672[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1674[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1675[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1676[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1677[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1678[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1679[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1680[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1681[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1682[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1683[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1684[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1686[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1688[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1690[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1692[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1694[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1695[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1697[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1698[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1699[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1701[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1702[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1703[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1704[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1705[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1706[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1708[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1841[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1842[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1843[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1844[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1845[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1848[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1849[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1850[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1851[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1852[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1853[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1855[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1856[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1857[13]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1858[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1859[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1860[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1861[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1862[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1863[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1865[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1866[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1867[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1869[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1870[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1871[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1872[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1873[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1874[27]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1875[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1876[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1877[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1879[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1880[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1881[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1882[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1886[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1890[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1891[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1892[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1893[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1894[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1895[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1896[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1898[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1899[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1900[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1901[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1902[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1903[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1904[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1905[13]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1906[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1907[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1908[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1909[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1912[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1913[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1914[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1915[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1916[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1917[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1920[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1921[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1922[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1923[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1924[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1925[138]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1930[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1931[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1932[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1933[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1936[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1937[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1939[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1940[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1944[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1945[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1946[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1947[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1948[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1949[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1950[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1951[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1952[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1953[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1955[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1959[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1961[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1962[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1963[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1964[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1967[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1968[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1969[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1970[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1973[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1974[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1975[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1976[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1977[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1978[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1979[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1980[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1981[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1982[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1983[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1984[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1987[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1990[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1994[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1995[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1996[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1997[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable1999[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2000[39]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2001[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2003[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2004[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2006[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2007[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2008[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2009[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2010[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2012[30]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2013[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2014[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2015[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2016[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2018[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2019[21]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2020[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2023[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2024[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2026[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2027[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2028[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2029[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2030[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2031[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2032[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2040[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2041[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2051[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2052[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2053[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2055[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2056[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2059[17]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2060[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2064[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2066[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2067[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2068[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2070[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2071[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2072[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2076[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2078[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2079[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2080[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2081[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2082[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2083[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2085[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2086[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2087[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2088[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2089[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2090[22]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2091[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2092[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2093[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2094[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2098[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2099[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2100[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2101[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2102[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2103[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2104[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2105[21]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2106[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2107[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2108[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2109[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2113[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2114[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2115[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2116[51]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2117[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2118[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2119[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2120[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2121[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2122[15]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2123[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2124[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2125[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2126[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2127[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2128[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2130[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2136[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2137[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2138[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2139[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2140[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2141[9]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2144[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2147[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2151[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2152[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2153[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2154[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2155[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2156[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2158[37]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2159[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2161[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2162[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2163[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2164[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2165[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2166[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2168[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2170[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2171[16]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2172[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2173[10]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2174[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2175[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2176[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2178[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2179[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2180[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2181[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2182[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2189[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2190[12]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2192[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2197[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2198[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2200[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2202[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2204[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2205[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2206[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2207[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2208[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2209[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2210[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2211[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2212[22]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2213[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2232[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2234[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2235[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2236[18]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2238[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2239[19]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2241[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2242[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2243[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2244[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2245[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2246[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2247[14]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2248[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2249[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2250[11]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2251[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2252[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2253[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2254[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2255[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2258[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2260[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2261[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2262[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2264[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2266[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2267[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2268[7]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2269[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2270[4]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2271[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2272[5]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2277[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2280[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2281[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2282[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2283[8]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2284[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2285[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2287[1]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2288[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2289[3]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2290[2]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2291[6]; IL2CPP_EXTERN_C_CONST int32_t g_FieldOffsetTable2292[5]; IL2CPP_EXTERN_C_CONST int32_t* g_FieldOffsetTable[2293] = { NULL, NULL, NULL, NULL, g_FieldOffsetTable4, g_FieldOffsetTable5, g_FieldOffsetTable6, g_FieldOffsetTable7, g_FieldOffsetTable8, g_FieldOffsetTable9, NULL, g_FieldOffsetTable11, NULL, g_FieldOffsetTable13, g_FieldOffsetTable14, g_FieldOffsetTable15, g_FieldOffsetTable16, NULL, g_FieldOffsetTable18, g_FieldOffsetTable19, g_FieldOffsetTable20, g_FieldOffsetTable21, g_FieldOffsetTable22, NULL, NULL, g_FieldOffsetTable25, g_FieldOffsetTable26, g_FieldOffsetTable27, g_FieldOffsetTable28, g_FieldOffsetTable29, g_FieldOffsetTable30, g_FieldOffsetTable31, g_FieldOffsetTable32, g_FieldOffsetTable33, g_FieldOffsetTable34, g_FieldOffsetTable35, g_FieldOffsetTable36, g_FieldOffsetTable37, g_FieldOffsetTable38, g_FieldOffsetTable39, g_FieldOffsetTable40, g_FieldOffsetTable41, g_FieldOffsetTable42, g_FieldOffsetTable43, NULL, NULL, g_FieldOffsetTable46, g_FieldOffsetTable47, g_FieldOffsetTable48, g_FieldOffsetTable49, g_FieldOffsetTable50, g_FieldOffsetTable51, NULL, g_FieldOffsetTable53, NULL, g_FieldOffsetTable55, g_FieldOffsetTable56, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable64, g_FieldOffsetTable65, g_FieldOffsetTable66, g_FieldOffsetTable67, g_FieldOffsetTable68, NULL, NULL, NULL, g_FieldOffsetTable72, g_FieldOffsetTable73, g_FieldOffsetTable74, g_FieldOffsetTable75, g_FieldOffsetTable76, g_FieldOffsetTable77, g_FieldOffsetTable78, g_FieldOffsetTable79, g_FieldOffsetTable80, g_FieldOffsetTable81, g_FieldOffsetTable82, g_FieldOffsetTable83, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable98, NULL, g_FieldOffsetTable100, NULL, NULL, NULL, NULL, g_FieldOffsetTable105, g_FieldOffsetTable106, g_FieldOffsetTable107, g_FieldOffsetTable108, g_FieldOffsetTable109, NULL, g_FieldOffsetTable111, NULL, g_FieldOffsetTable113, g_FieldOffsetTable114, g_FieldOffsetTable115, NULL, g_FieldOffsetTable117, g_FieldOffsetTable118, g_FieldOffsetTable119, g_FieldOffsetTable120, g_FieldOffsetTable121, g_FieldOffsetTable122, NULL, NULL, g_FieldOffsetTable125, g_FieldOffsetTable126, g_FieldOffsetTable127, g_FieldOffsetTable128, g_FieldOffsetTable129, g_FieldOffsetTable130, g_FieldOffsetTable131, g_FieldOffsetTable132, g_FieldOffsetTable133, NULL, NULL, NULL, g_FieldOffsetTable137, g_FieldOffsetTable138, NULL, g_FieldOffsetTable140, g_FieldOffsetTable141, g_FieldOffsetTable142, NULL, NULL, g_FieldOffsetTable145, g_FieldOffsetTable146, NULL, NULL, NULL, NULL, g_FieldOffsetTable151, g_FieldOffsetTable152, NULL, g_FieldOffsetTable154, g_FieldOffsetTable155, g_FieldOffsetTable156, g_FieldOffsetTable157, g_FieldOffsetTable158, g_FieldOffsetTable159, g_FieldOffsetTable160, g_FieldOffsetTable161, g_FieldOffsetTable162, g_FieldOffsetTable163, g_FieldOffsetTable164, g_FieldOffsetTable165, g_FieldOffsetTable166, g_FieldOffsetTable167, g_FieldOffsetTable168, g_FieldOffsetTable169, g_FieldOffsetTable170, g_FieldOffsetTable171, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable183, g_FieldOffsetTable184, g_FieldOffsetTable185, NULL, NULL, NULL, NULL, g_FieldOffsetTable190, NULL, NULL, NULL, g_FieldOffsetTable194, g_FieldOffsetTable195, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable201, NULL, g_FieldOffsetTable203, g_FieldOffsetTable204, g_FieldOffsetTable205, NULL, NULL, NULL, g_FieldOffsetTable209, NULL, g_FieldOffsetTable211, NULL, g_FieldOffsetTable213, g_FieldOffsetTable214, g_FieldOffsetTable215, g_FieldOffsetTable216, g_FieldOffsetTable217, NULL, g_FieldOffsetTable219, NULL, g_FieldOffsetTable221, NULL, g_FieldOffsetTable223, g_FieldOffsetTable224, g_FieldOffsetTable225, g_FieldOffsetTable226, g_FieldOffsetTable227, NULL, NULL, NULL, g_FieldOffsetTable231, g_FieldOffsetTable232, g_FieldOffsetTable233, g_FieldOffsetTable234, g_FieldOffsetTable235, g_FieldOffsetTable236, g_FieldOffsetTable237, g_FieldOffsetTable238, g_FieldOffsetTable239, g_FieldOffsetTable240, g_FieldOffsetTable241, NULL, g_FieldOffsetTable243, g_FieldOffsetTable244, g_FieldOffsetTable245, g_FieldOffsetTable246, g_FieldOffsetTable247, g_FieldOffsetTable248, g_FieldOffsetTable249, NULL, g_FieldOffsetTable251, NULL, g_FieldOffsetTable253, g_FieldOffsetTable254, g_FieldOffsetTable255, g_FieldOffsetTable256, NULL, g_FieldOffsetTable258, g_FieldOffsetTable259, g_FieldOffsetTable260, g_FieldOffsetTable261, NULL, g_FieldOffsetTable263, NULL, g_FieldOffsetTable265, g_FieldOffsetTable266, g_FieldOffsetTable267, NULL, NULL, g_FieldOffsetTable270, NULL, g_FieldOffsetTable272, g_FieldOffsetTable273, g_FieldOffsetTable274, g_FieldOffsetTable275, g_FieldOffsetTable276, g_FieldOffsetTable277, g_FieldOffsetTable278, g_FieldOffsetTable279, g_FieldOffsetTable280, g_FieldOffsetTable281, g_FieldOffsetTable282, g_FieldOffsetTable283, g_FieldOffsetTable284, g_FieldOffsetTable285, g_FieldOffsetTable286, NULL, g_FieldOffsetTable288, NULL, g_FieldOffsetTable290, g_FieldOffsetTable291, g_FieldOffsetTable292, g_FieldOffsetTable293, g_FieldOffsetTable294, NULL, g_FieldOffsetTable296, g_FieldOffsetTable297, NULL, g_FieldOffsetTable299, g_FieldOffsetTable300, g_FieldOffsetTable301, NULL, g_FieldOffsetTable303, g_FieldOffsetTable304, g_FieldOffsetTable305, NULL, g_FieldOffsetTable307, g_FieldOffsetTable308, g_FieldOffsetTable309, g_FieldOffsetTable310, g_FieldOffsetTable311, g_FieldOffsetTable312, g_FieldOffsetTable313, g_FieldOffsetTable314, g_FieldOffsetTable315, g_FieldOffsetTable316, g_FieldOffsetTable317, g_FieldOffsetTable318, g_FieldOffsetTable319, g_FieldOffsetTable320, g_FieldOffsetTable321, g_FieldOffsetTable322, g_FieldOffsetTable323, NULL, NULL, NULL, NULL, g_FieldOffsetTable328, NULL, NULL, g_FieldOffsetTable331, g_FieldOffsetTable332, g_FieldOffsetTable333, g_FieldOffsetTable334, g_FieldOffsetTable335, NULL, g_FieldOffsetTable337, g_FieldOffsetTable338, NULL, g_FieldOffsetTable340, g_FieldOffsetTable341, g_FieldOffsetTable342, g_FieldOffsetTable343, g_FieldOffsetTable344, g_FieldOffsetTable345, g_FieldOffsetTable346, NULL, g_FieldOffsetTable348, g_FieldOffsetTable349, NULL, g_FieldOffsetTable351, g_FieldOffsetTable352, g_FieldOffsetTable353, NULL, NULL, g_FieldOffsetTable356, g_FieldOffsetTable357, g_FieldOffsetTable358, g_FieldOffsetTable359, g_FieldOffsetTable360, g_FieldOffsetTable361, g_FieldOffsetTable362, g_FieldOffsetTable363, g_FieldOffsetTable364, NULL, NULL, g_FieldOffsetTable367, g_FieldOffsetTable368, g_FieldOffsetTable369, g_FieldOffsetTable370, g_FieldOffsetTable371, g_FieldOffsetTable372, g_FieldOffsetTable373, g_FieldOffsetTable374, g_FieldOffsetTable375, g_FieldOffsetTable376, g_FieldOffsetTable377, NULL, g_FieldOffsetTable379, g_FieldOffsetTable380, g_FieldOffsetTable381, g_FieldOffsetTable382, g_FieldOffsetTable383, g_FieldOffsetTable384, g_FieldOffsetTable385, g_FieldOffsetTable386, g_FieldOffsetTable387, g_FieldOffsetTable388, NULL, g_FieldOffsetTable390, g_FieldOffsetTable391, g_FieldOffsetTable392, g_FieldOffsetTable393, g_FieldOffsetTable394, g_FieldOffsetTable395, g_FieldOffsetTable396, g_FieldOffsetTable397, g_FieldOffsetTable398, g_FieldOffsetTable399, g_FieldOffsetTable400, NULL, NULL, g_FieldOffsetTable403, g_FieldOffsetTable404, NULL, g_FieldOffsetTable406, g_FieldOffsetTable407, g_FieldOffsetTable408, g_FieldOffsetTable409, g_FieldOffsetTable410, g_FieldOffsetTable411, g_FieldOffsetTable412, g_FieldOffsetTable413, g_FieldOffsetTable414, g_FieldOffsetTable415, NULL, NULL, g_FieldOffsetTable418, g_FieldOffsetTable419, g_FieldOffsetTable420, g_FieldOffsetTable421, g_FieldOffsetTable422, g_FieldOffsetTable423, g_FieldOffsetTable424, g_FieldOffsetTable425, g_FieldOffsetTable426, g_FieldOffsetTable427, g_FieldOffsetTable428, g_FieldOffsetTable429, g_FieldOffsetTable430, g_FieldOffsetTable431, g_FieldOffsetTable432, NULL, g_FieldOffsetTable434, g_FieldOffsetTable435, g_FieldOffsetTable436, g_FieldOffsetTable437, g_FieldOffsetTable438, g_FieldOffsetTable439, NULL, NULL, g_FieldOffsetTable442, NULL, NULL, g_FieldOffsetTable445, g_FieldOffsetTable446, g_FieldOffsetTable447, NULL, g_FieldOffsetTable449, g_FieldOffsetTable450, NULL, g_FieldOffsetTable452, g_FieldOffsetTable453, g_FieldOffsetTable454, g_FieldOffsetTable455, g_FieldOffsetTable456, g_FieldOffsetTable457, NULL, NULL, NULL, g_FieldOffsetTable461, NULL, NULL, NULL, g_FieldOffsetTable465, g_FieldOffsetTable466, g_FieldOffsetTable467, g_FieldOffsetTable468, g_FieldOffsetTable469, NULL, g_FieldOffsetTable471, g_FieldOffsetTable472, NULL, g_FieldOffsetTable474, g_FieldOffsetTable475, NULL, g_FieldOffsetTable477, g_FieldOffsetTable478, g_FieldOffsetTable479, NULL, NULL, g_FieldOffsetTable482, NULL, g_FieldOffsetTable484, NULL, NULL, g_FieldOffsetTable487, g_FieldOffsetTable488, NULL, g_FieldOffsetTable490, NULL, g_FieldOffsetTable492, NULL, NULL, NULL, NULL, g_FieldOffsetTable497, g_FieldOffsetTable498, NULL, NULL, NULL, NULL, g_FieldOffsetTable503, g_FieldOffsetTable504, NULL, g_FieldOffsetTable506, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable515, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable521, NULL, NULL, g_FieldOffsetTable524, g_FieldOffsetTable525, g_FieldOffsetTable526, NULL, NULL, NULL, NULL, g_FieldOffsetTable531, g_FieldOffsetTable532, NULL, g_FieldOffsetTable534, g_FieldOffsetTable535, NULL, g_FieldOffsetTable537, g_FieldOffsetTable538, NULL, g_FieldOffsetTable540, g_FieldOffsetTable541, g_FieldOffsetTable542, NULL, g_FieldOffsetTable544, g_FieldOffsetTable545, NULL, g_FieldOffsetTable547, g_FieldOffsetTable548, g_FieldOffsetTable549, g_FieldOffsetTable550, NULL, g_FieldOffsetTable552, g_FieldOffsetTable553, g_FieldOffsetTable554, NULL, g_FieldOffsetTable556, g_FieldOffsetTable557, g_FieldOffsetTable558, NULL, g_FieldOffsetTable560, g_FieldOffsetTable561, g_FieldOffsetTable562, g_FieldOffsetTable563, NULL, g_FieldOffsetTable565, NULL, g_FieldOffsetTable567, g_FieldOffsetTable568, g_FieldOffsetTable569, g_FieldOffsetTable570, g_FieldOffsetTable571, NULL, NULL, g_FieldOffsetTable574, g_FieldOffsetTable575, g_FieldOffsetTable576, g_FieldOffsetTable577, g_FieldOffsetTable578, g_FieldOffsetTable579, g_FieldOffsetTable580, g_FieldOffsetTable581, g_FieldOffsetTable582, g_FieldOffsetTable583, NULL, g_FieldOffsetTable585, g_FieldOffsetTable586, NULL, g_FieldOffsetTable588, g_FieldOffsetTable589, g_FieldOffsetTable590, g_FieldOffsetTable591, g_FieldOffsetTable592, g_FieldOffsetTable593, g_FieldOffsetTable594, g_FieldOffsetTable595, g_FieldOffsetTable596, g_FieldOffsetTable597, g_FieldOffsetTable598, g_FieldOffsetTable599, g_FieldOffsetTable600, g_FieldOffsetTable601, g_FieldOffsetTable602, g_FieldOffsetTable603, g_FieldOffsetTable604, g_FieldOffsetTable605, g_FieldOffsetTable606, g_FieldOffsetTable607, g_FieldOffsetTable608, g_FieldOffsetTable609, g_FieldOffsetTable610, g_FieldOffsetTable611, g_FieldOffsetTable612, g_FieldOffsetTable613, g_FieldOffsetTable614, g_FieldOffsetTable615, NULL, g_FieldOffsetTable617, g_FieldOffsetTable618, g_FieldOffsetTable619, g_FieldOffsetTable620, g_FieldOffsetTable621, g_FieldOffsetTable622, g_FieldOffsetTable623, g_FieldOffsetTable624, g_FieldOffsetTable625, g_FieldOffsetTable626, g_FieldOffsetTable627, g_FieldOffsetTable628, g_FieldOffsetTable629, g_FieldOffsetTable630, g_FieldOffsetTable631, g_FieldOffsetTable632, g_FieldOffsetTable633, g_FieldOffsetTable634, NULL, g_FieldOffsetTable636, g_FieldOffsetTable637, g_FieldOffsetTable638, g_FieldOffsetTable639, g_FieldOffsetTable640, g_FieldOffsetTable641, g_FieldOffsetTable642, g_FieldOffsetTable643, g_FieldOffsetTable644, NULL, g_FieldOffsetTable646, g_FieldOffsetTable647, g_FieldOffsetTable648, g_FieldOffsetTable649, NULL, g_FieldOffsetTable651, g_FieldOffsetTable652, g_FieldOffsetTable653, NULL, g_FieldOffsetTable655, NULL, NULL, g_FieldOffsetTable658, NULL, NULL, g_FieldOffsetTable661, g_FieldOffsetTable662, g_FieldOffsetTable663, g_FieldOffsetTable664, g_FieldOffsetTable665, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable675, g_FieldOffsetTable676, g_FieldOffsetTable677, NULL, g_FieldOffsetTable679, g_FieldOffsetTable680, g_FieldOffsetTable681, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable687, g_FieldOffsetTable688, g_FieldOffsetTable689, g_FieldOffsetTable690, g_FieldOffsetTable691, g_FieldOffsetTable692, NULL, g_FieldOffsetTable694, NULL, NULL, g_FieldOffsetTable697, NULL, g_FieldOffsetTable699, g_FieldOffsetTable700, NULL, NULL, NULL, NULL, g_FieldOffsetTable705, g_FieldOffsetTable706, g_FieldOffsetTable707, NULL, g_FieldOffsetTable709, g_FieldOffsetTable710, NULL, NULL, g_FieldOffsetTable713, g_FieldOffsetTable714, g_FieldOffsetTable715, g_FieldOffsetTable716, NULL, g_FieldOffsetTable718, g_FieldOffsetTable719, NULL, g_FieldOffsetTable721, g_FieldOffsetTable722, g_FieldOffsetTable723, g_FieldOffsetTable724, NULL, g_FieldOffsetTable726, g_FieldOffsetTable727, g_FieldOffsetTable728, g_FieldOffsetTable729, g_FieldOffsetTable730, NULL, g_FieldOffsetTable732, g_FieldOffsetTable733, g_FieldOffsetTable734, g_FieldOffsetTable735, NULL, NULL, g_FieldOffsetTable738, g_FieldOffsetTable739, NULL, g_FieldOffsetTable741, g_FieldOffsetTable742, g_FieldOffsetTable743, g_FieldOffsetTable744, g_FieldOffsetTable745, g_FieldOffsetTable746, g_FieldOffsetTable747, g_FieldOffsetTable748, g_FieldOffsetTable749, g_FieldOffsetTable750, NULL, g_FieldOffsetTable752, g_FieldOffsetTable753, NULL, g_FieldOffsetTable755, g_FieldOffsetTable756, g_FieldOffsetTable757, g_FieldOffsetTable758, NULL, NULL, g_FieldOffsetTable761, g_FieldOffsetTable762, NULL, NULL, NULL, g_FieldOffsetTable766, NULL, NULL, NULL, g_FieldOffsetTable770, g_FieldOffsetTable771, g_FieldOffsetTable772, g_FieldOffsetTable773, NULL, NULL, NULL, g_FieldOffsetTable777, g_FieldOffsetTable778, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable786, g_FieldOffsetTable787, g_FieldOffsetTable788, g_FieldOffsetTable789, g_FieldOffsetTable790, g_FieldOffsetTable791, g_FieldOffsetTable792, g_FieldOffsetTable793, g_FieldOffsetTable794, g_FieldOffsetTable795, g_FieldOffsetTable796, NULL, g_FieldOffsetTable798, g_FieldOffsetTable799, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable805, g_FieldOffsetTable806, g_FieldOffsetTable807, g_FieldOffsetTable808, g_FieldOffsetTable809, g_FieldOffsetTable810, g_FieldOffsetTable811, g_FieldOffsetTable812, g_FieldOffsetTable813, g_FieldOffsetTable814, g_FieldOffsetTable815, g_FieldOffsetTable816, g_FieldOffsetTable817, g_FieldOffsetTable818, NULL, NULL, g_FieldOffsetTable821, g_FieldOffsetTable822, g_FieldOffsetTable823, g_FieldOffsetTable824, g_FieldOffsetTable825, g_FieldOffsetTable826, g_FieldOffsetTable827, g_FieldOffsetTable828, g_FieldOffsetTable829, g_FieldOffsetTable830, g_FieldOffsetTable831, g_FieldOffsetTable832, g_FieldOffsetTable833, g_FieldOffsetTable834, g_FieldOffsetTable835, g_FieldOffsetTable836, g_FieldOffsetTable837, NULL, g_FieldOffsetTable839, g_FieldOffsetTable840, g_FieldOffsetTable841, g_FieldOffsetTable842, g_FieldOffsetTable843, g_FieldOffsetTable844, g_FieldOffsetTable845, g_FieldOffsetTable846, g_FieldOffsetTable847, g_FieldOffsetTable848, g_FieldOffsetTable849, g_FieldOffsetTable850, g_FieldOffsetTable851, g_FieldOffsetTable852, g_FieldOffsetTable853, g_FieldOffsetTable854, g_FieldOffsetTable855, g_FieldOffsetTable856, g_FieldOffsetTable857, g_FieldOffsetTable858, g_FieldOffsetTable859, g_FieldOffsetTable860, g_FieldOffsetTable861, g_FieldOffsetTable862, g_FieldOffsetTable863, g_FieldOffsetTable864, g_FieldOffsetTable865, g_FieldOffsetTable866, g_FieldOffsetTable867, g_FieldOffsetTable868, g_FieldOffsetTable869, g_FieldOffsetTable870, g_FieldOffsetTable871, g_FieldOffsetTable872, g_FieldOffsetTable873, g_FieldOffsetTable874, g_FieldOffsetTable875, g_FieldOffsetTable876, g_FieldOffsetTable877, g_FieldOffsetTable878, g_FieldOffsetTable879, g_FieldOffsetTable880, NULL, NULL, NULL, g_FieldOffsetTable884, g_FieldOffsetTable885, g_FieldOffsetTable886, g_FieldOffsetTable887, g_FieldOffsetTable888, g_FieldOffsetTable889, g_FieldOffsetTable890, g_FieldOffsetTable891, NULL, NULL, g_FieldOffsetTable894, g_FieldOffsetTable895, g_FieldOffsetTable896, g_FieldOffsetTable897, NULL, NULL, g_FieldOffsetTable900, g_FieldOffsetTable901, g_FieldOffsetTable902, g_FieldOffsetTable903, g_FieldOffsetTable904, g_FieldOffsetTable905, g_FieldOffsetTable906, g_FieldOffsetTable907, NULL, g_FieldOffsetTable909, NULL, g_FieldOffsetTable911, g_FieldOffsetTable912, g_FieldOffsetTable913, NULL, NULL, NULL, g_FieldOffsetTable917, g_FieldOffsetTable918, g_FieldOffsetTable919, g_FieldOffsetTable920, g_FieldOffsetTable921, g_FieldOffsetTable922, g_FieldOffsetTable923, g_FieldOffsetTable924, NULL, g_FieldOffsetTable926, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable938, g_FieldOffsetTable939, g_FieldOffsetTable940, g_FieldOffsetTable941, g_FieldOffsetTable942, NULL, g_FieldOffsetTable944, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable952, g_FieldOffsetTable953, g_FieldOffsetTable954, NULL, g_FieldOffsetTable956, NULL, NULL, NULL, NULL, g_FieldOffsetTable961, g_FieldOffsetTable962, g_FieldOffsetTable963, NULL, g_FieldOffsetTable965, NULL, g_FieldOffsetTable967, g_FieldOffsetTable968, g_FieldOffsetTable969, g_FieldOffsetTable970, g_FieldOffsetTable971, g_FieldOffsetTable972, g_FieldOffsetTable973, g_FieldOffsetTable974, g_FieldOffsetTable975, g_FieldOffsetTable976, g_FieldOffsetTable977, g_FieldOffsetTable978, g_FieldOffsetTable979, g_FieldOffsetTable980, g_FieldOffsetTable981, g_FieldOffsetTable982, g_FieldOffsetTable983, g_FieldOffsetTable984, NULL, g_FieldOffsetTable986, g_FieldOffsetTable987, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable997, g_FieldOffsetTable998, g_FieldOffsetTable999, g_FieldOffsetTable1000, g_FieldOffsetTable1001, g_FieldOffsetTable1002, g_FieldOffsetTable1003, g_FieldOffsetTable1004, NULL, NULL, NULL, g_FieldOffsetTable1008, g_FieldOffsetTable1009, NULL, g_FieldOffsetTable1011, g_FieldOffsetTable1012, g_FieldOffsetTable1013, NULL, NULL, g_FieldOffsetTable1016, NULL, g_FieldOffsetTable1018, g_FieldOffsetTable1019, g_FieldOffsetTable1020, g_FieldOffsetTable1021, g_FieldOffsetTable1022, g_FieldOffsetTable1023, g_FieldOffsetTable1024, g_FieldOffsetTable1025, g_FieldOffsetTable1026, g_FieldOffsetTable1027, NULL, NULL, NULL, NULL, g_FieldOffsetTable1032, g_FieldOffsetTable1033, g_FieldOffsetTable1034, g_FieldOffsetTable1035, g_FieldOffsetTable1036, g_FieldOffsetTable1037, g_FieldOffsetTable1038, g_FieldOffsetTable1039, g_FieldOffsetTable1040, g_FieldOffsetTable1041, g_FieldOffsetTable1042, g_FieldOffsetTable1043, NULL, NULL, g_FieldOffsetTable1046, g_FieldOffsetTable1047, NULL, g_FieldOffsetTable1049, g_FieldOffsetTable1050, NULL, NULL, g_FieldOffsetTable1053, NULL, NULL, NULL, g_FieldOffsetTable1057, NULL, g_FieldOffsetTable1059, NULL, g_FieldOffsetTable1061, g_FieldOffsetTable1062, g_FieldOffsetTable1063, g_FieldOffsetTable1064, g_FieldOffsetTable1065, g_FieldOffsetTable1066, g_FieldOffsetTable1067, g_FieldOffsetTable1068, g_FieldOffsetTable1069, g_FieldOffsetTable1070, NULL, g_FieldOffsetTable1072, NULL, NULL, NULL, NULL, g_FieldOffsetTable1077, g_FieldOffsetTable1078, g_FieldOffsetTable1079, g_FieldOffsetTable1080, g_FieldOffsetTable1081, g_FieldOffsetTable1082, g_FieldOffsetTable1083, NULL, g_FieldOffsetTable1085, NULL, NULL, NULL, g_FieldOffsetTable1089, g_FieldOffsetTable1090, g_FieldOffsetTable1091, g_FieldOffsetTable1092, g_FieldOffsetTable1093, g_FieldOffsetTable1094, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1110, g_FieldOffsetTable1111, g_FieldOffsetTable1112, NULL, g_FieldOffsetTable1114, g_FieldOffsetTable1115, g_FieldOffsetTable1116, g_FieldOffsetTable1117, g_FieldOffsetTable1118, NULL, NULL, g_FieldOffsetTable1121, g_FieldOffsetTable1122, g_FieldOffsetTable1123, g_FieldOffsetTable1124, NULL, g_FieldOffsetTable1126, g_FieldOffsetTable1127, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1139, g_FieldOffsetTable1140, g_FieldOffsetTable1141, g_FieldOffsetTable1142, NULL, g_FieldOffsetTable1144, g_FieldOffsetTable1145, NULL, g_FieldOffsetTable1147, g_FieldOffsetTable1148, NULL, g_FieldOffsetTable1150, g_FieldOffsetTable1151, g_FieldOffsetTable1152, g_FieldOffsetTable1153, g_FieldOffsetTable1154, g_FieldOffsetTable1155, g_FieldOffsetTable1156, g_FieldOffsetTable1157, NULL, NULL, NULL, g_FieldOffsetTable1161, NULL, NULL, g_FieldOffsetTable1164, g_FieldOffsetTable1165, g_FieldOffsetTable1166, g_FieldOffsetTable1167, g_FieldOffsetTable1168, g_FieldOffsetTable1169, g_FieldOffsetTable1170, g_FieldOffsetTable1171, g_FieldOffsetTable1172, NULL, NULL, NULL, NULL, g_FieldOffsetTable1177, g_FieldOffsetTable1178, NULL, NULL, NULL, NULL, g_FieldOffsetTable1183, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1204, g_FieldOffsetTable1205, NULL, NULL, NULL, g_FieldOffsetTable1209, g_FieldOffsetTable1210, g_FieldOffsetTable1211, g_FieldOffsetTable1212, g_FieldOffsetTable1213, g_FieldOffsetTable1214, g_FieldOffsetTable1215, g_FieldOffsetTable1216, g_FieldOffsetTable1217, g_FieldOffsetTable1218, NULL, g_FieldOffsetTable1220, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1262, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1272, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1279, NULL, NULL, NULL, NULL, g_FieldOffsetTable1284, NULL, NULL, NULL, NULL, g_FieldOffsetTable1289, g_FieldOffsetTable1290, g_FieldOffsetTable1291, g_FieldOffsetTable1292, g_FieldOffsetTable1293, g_FieldOffsetTable1294, NULL, g_FieldOffsetTable1296, g_FieldOffsetTable1297, g_FieldOffsetTable1298, g_FieldOffsetTable1299, g_FieldOffsetTable1300, g_FieldOffsetTable1301, g_FieldOffsetTable1302, g_FieldOffsetTable1303, NULL, g_FieldOffsetTable1305, NULL, NULL, NULL, NULL, g_FieldOffsetTable1310, g_FieldOffsetTable1311, NULL, g_FieldOffsetTable1313, g_FieldOffsetTable1314, NULL, g_FieldOffsetTable1316, g_FieldOffsetTable1317, NULL, g_FieldOffsetTable1319, g_FieldOffsetTable1320, g_FieldOffsetTable1321, NULL, g_FieldOffsetTable1323, g_FieldOffsetTable1324, g_FieldOffsetTable1325, g_FieldOffsetTable1326, g_FieldOffsetTable1327, g_FieldOffsetTable1328, g_FieldOffsetTable1329, g_FieldOffsetTable1330, g_FieldOffsetTable1331, NULL, g_FieldOffsetTable1333, g_FieldOffsetTable1334, g_FieldOffsetTable1335, NULL, g_FieldOffsetTable1337, NULL, NULL, NULL, g_FieldOffsetTable1341, g_FieldOffsetTable1342, g_FieldOffsetTable1343, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1351, g_FieldOffsetTable1352, g_FieldOffsetTable1353, NULL, g_FieldOffsetTable1355, g_FieldOffsetTable1356, g_FieldOffsetTable1357, g_FieldOffsetTable1358, NULL, g_FieldOffsetTable1360, g_FieldOffsetTable1361, g_FieldOffsetTable1362, g_FieldOffsetTable1363, NULL, g_FieldOffsetTable1365, g_FieldOffsetTable1366, g_FieldOffsetTable1367, g_FieldOffsetTable1368, g_FieldOffsetTable1369, g_FieldOffsetTable1370, NULL, g_FieldOffsetTable1372, g_FieldOffsetTable1373, g_FieldOffsetTable1374, g_FieldOffsetTable1375, g_FieldOffsetTable1376, NULL, NULL, g_FieldOffsetTable1379, g_FieldOffsetTable1380, g_FieldOffsetTable1381, g_FieldOffsetTable1382, g_FieldOffsetTable1383, NULL, NULL, g_FieldOffsetTable1386, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1410, g_FieldOffsetTable1411, g_FieldOffsetTable1412, g_FieldOffsetTable1413, g_FieldOffsetTable1414, NULL, g_FieldOffsetTable1416, g_FieldOffsetTable1417, g_FieldOffsetTable1418, NULL, NULL, g_FieldOffsetTable1421, NULL, NULL, NULL, g_FieldOffsetTable1425, NULL, NULL, g_FieldOffsetTable1428, g_FieldOffsetTable1429, g_FieldOffsetTable1430, g_FieldOffsetTable1431, g_FieldOffsetTable1432, g_FieldOffsetTable1433, g_FieldOffsetTable1434, NULL, g_FieldOffsetTable1436, g_FieldOffsetTable1437, NULL, NULL, g_FieldOffsetTable1440, g_FieldOffsetTable1441, g_FieldOffsetTable1442, g_FieldOffsetTable1443, NULL, NULL, g_FieldOffsetTable1446, NULL, NULL, NULL, g_FieldOffsetTable1450, g_FieldOffsetTable1451, g_FieldOffsetTable1452, NULL, g_FieldOffsetTable1454, NULL, g_FieldOffsetTable1456, g_FieldOffsetTable1457, g_FieldOffsetTable1458, g_FieldOffsetTable1459, g_FieldOffsetTable1460, g_FieldOffsetTable1461, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1468, g_FieldOffsetTable1469, g_FieldOffsetTable1470, g_FieldOffsetTable1471, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1487, g_FieldOffsetTable1488, g_FieldOffsetTable1489, g_FieldOffsetTable1490, g_FieldOffsetTable1491, g_FieldOffsetTable1492, g_FieldOffsetTable1493, g_FieldOffsetTable1494, NULL, NULL, g_FieldOffsetTable1497, g_FieldOffsetTable1498, g_FieldOffsetTable1499, g_FieldOffsetTable1500, g_FieldOffsetTable1501, g_FieldOffsetTable1502, NULL, g_FieldOffsetTable1504, g_FieldOffsetTable1505, NULL, g_FieldOffsetTable1507, g_FieldOffsetTable1508, g_FieldOffsetTable1509, NULL, g_FieldOffsetTable1511, NULL, g_FieldOffsetTable1513, g_FieldOffsetTable1514, g_FieldOffsetTable1515, g_FieldOffsetTable1516, g_FieldOffsetTable1517, g_FieldOffsetTable1518, g_FieldOffsetTable1519, g_FieldOffsetTable1520, NULL, g_FieldOffsetTable1522, g_FieldOffsetTable1523, NULL, NULL, g_FieldOffsetTable1526, g_FieldOffsetTable1527, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1533, g_FieldOffsetTable1534, NULL, g_FieldOffsetTable1536, g_FieldOffsetTable1537, g_FieldOffsetTable1538, g_FieldOffsetTable1539, g_FieldOffsetTable1540, g_FieldOffsetTable1541, g_FieldOffsetTable1542, g_FieldOffsetTable1543, g_FieldOffsetTable1544, g_FieldOffsetTable1545, g_FieldOffsetTable1546, g_FieldOffsetTable1547, g_FieldOffsetTable1548, g_FieldOffsetTable1549, g_FieldOffsetTable1550, NULL, g_FieldOffsetTable1552, NULL, g_FieldOffsetTable1554, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1562, g_FieldOffsetTable1563, NULL, g_FieldOffsetTable1565, NULL, NULL, g_FieldOffsetTable1568, g_FieldOffsetTable1569, g_FieldOffsetTable1570, g_FieldOffsetTable1571, g_FieldOffsetTable1572, g_FieldOffsetTable1573, g_FieldOffsetTable1574, g_FieldOffsetTable1575, g_FieldOffsetTable1576, g_FieldOffsetTable1577, g_FieldOffsetTable1578, NULL, NULL, NULL, g_FieldOffsetTable1582, g_FieldOffsetTable1583, g_FieldOffsetTable1584, g_FieldOffsetTable1585, NULL, g_FieldOffsetTable1587, NULL, g_FieldOffsetTable1589, g_FieldOffsetTable1590, NULL, g_FieldOffsetTable1592, g_FieldOffsetTable1593, NULL, NULL, NULL, NULL, g_FieldOffsetTable1598, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1604, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1611, NULL, NULL, NULL, g_FieldOffsetTable1615, g_FieldOffsetTable1616, g_FieldOffsetTable1617, NULL, g_FieldOffsetTable1619, NULL, NULL, g_FieldOffsetTable1622, NULL, g_FieldOffsetTable1624, NULL, g_FieldOffsetTable1626, g_FieldOffsetTable1627, NULL, g_FieldOffsetTable1629, g_FieldOffsetTable1630, g_FieldOffsetTable1631, g_FieldOffsetTable1632, NULL, NULL, g_FieldOffsetTable1635, g_FieldOffsetTable1636, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1645, NULL, NULL, g_FieldOffsetTable1648, g_FieldOffsetTable1649, g_FieldOffsetTable1650, g_FieldOffsetTable1651, g_FieldOffsetTable1652, NULL, g_FieldOffsetTable1654, NULL, g_FieldOffsetTable1656, g_FieldOffsetTable1657, NULL, NULL, g_FieldOffsetTable1660, NULL, NULL, NULL, g_FieldOffsetTable1664, g_FieldOffsetTable1665, NULL, g_FieldOffsetTable1667, g_FieldOffsetTable1668, g_FieldOffsetTable1669, g_FieldOffsetTable1670, NULL, g_FieldOffsetTable1672, NULL, g_FieldOffsetTable1674, g_FieldOffsetTable1675, g_FieldOffsetTable1676, g_FieldOffsetTable1677, g_FieldOffsetTable1678, g_FieldOffsetTable1679, g_FieldOffsetTable1680, g_FieldOffsetTable1681, g_FieldOffsetTable1682, g_FieldOffsetTable1683, g_FieldOffsetTable1684, NULL, g_FieldOffsetTable1686, NULL, g_FieldOffsetTable1688, NULL, g_FieldOffsetTable1690, NULL, g_FieldOffsetTable1692, NULL, g_FieldOffsetTable1694, g_FieldOffsetTable1695, NULL, g_FieldOffsetTable1697, g_FieldOffsetTable1698, g_FieldOffsetTable1699, NULL, g_FieldOffsetTable1701, g_FieldOffsetTable1702, g_FieldOffsetTable1703, g_FieldOffsetTable1704, g_FieldOffsetTable1705, g_FieldOffsetTable1706, NULL, g_FieldOffsetTable1708, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable1841, g_FieldOffsetTable1842, g_FieldOffsetTable1843, g_FieldOffsetTable1844, g_FieldOffsetTable1845, NULL, NULL, g_FieldOffsetTable1848, g_FieldOffsetTable1849, g_FieldOffsetTable1850, g_FieldOffsetTable1851, g_FieldOffsetTable1852, g_FieldOffsetTable1853, NULL, g_FieldOffsetTable1855, g_FieldOffsetTable1856, g_FieldOffsetTable1857, g_FieldOffsetTable1858, g_FieldOffsetTable1859, g_FieldOffsetTable1860, g_FieldOffsetTable1861, g_FieldOffsetTable1862, g_FieldOffsetTable1863, NULL, g_FieldOffsetTable1865, g_FieldOffsetTable1866, g_FieldOffsetTable1867, NULL, g_FieldOffsetTable1869, g_FieldOffsetTable1870, g_FieldOffsetTable1871, g_FieldOffsetTable1872, g_FieldOffsetTable1873, g_FieldOffsetTable1874, g_FieldOffsetTable1875, g_FieldOffsetTable1876, g_FieldOffsetTable1877, NULL, g_FieldOffsetTable1879, g_FieldOffsetTable1880, g_FieldOffsetTable1881, g_FieldOffsetTable1882, NULL, NULL, NULL, g_FieldOffsetTable1886, NULL, NULL, NULL, g_FieldOffsetTable1890, g_FieldOffsetTable1891, g_FieldOffsetTable1892, g_FieldOffsetTable1893, g_FieldOffsetTable1894, g_FieldOffsetTable1895, g_FieldOffsetTable1896, NULL, g_FieldOffsetTable1898, g_FieldOffsetTable1899, g_FieldOffsetTable1900, g_FieldOffsetTable1901, g_FieldOffsetTable1902, g_FieldOffsetTable1903, g_FieldOffsetTable1904, g_FieldOffsetTable1905, g_FieldOffsetTable1906, g_FieldOffsetTable1907, g_FieldOffsetTable1908, g_FieldOffsetTable1909, NULL, NULL, g_FieldOffsetTable1912, g_FieldOffsetTable1913, g_FieldOffsetTable1914, g_FieldOffsetTable1915, g_FieldOffsetTable1916, g_FieldOffsetTable1917, NULL, NULL, g_FieldOffsetTable1920, g_FieldOffsetTable1921, g_FieldOffsetTable1922, g_FieldOffsetTable1923, g_FieldOffsetTable1924, g_FieldOffsetTable1925, NULL, NULL, NULL, NULL, g_FieldOffsetTable1930, g_FieldOffsetTable1931, g_FieldOffsetTable1932, g_FieldOffsetTable1933, NULL, NULL, g_FieldOffsetTable1936, g_FieldOffsetTable1937, NULL, g_FieldOffsetTable1939, g_FieldOffsetTable1940, NULL, NULL, NULL, g_FieldOffsetTable1944, g_FieldOffsetTable1945, g_FieldOffsetTable1946, g_FieldOffsetTable1947, g_FieldOffsetTable1948, g_FieldOffsetTable1949, g_FieldOffsetTable1950, g_FieldOffsetTable1951, g_FieldOffsetTable1952, g_FieldOffsetTable1953, NULL, g_FieldOffsetTable1955, NULL, NULL, NULL, g_FieldOffsetTable1959, NULL, g_FieldOffsetTable1961, g_FieldOffsetTable1962, g_FieldOffsetTable1963, g_FieldOffsetTable1964, NULL, NULL, g_FieldOffsetTable1967, g_FieldOffsetTable1968, g_FieldOffsetTable1969, g_FieldOffsetTable1970, NULL, NULL, g_FieldOffsetTable1973, g_FieldOffsetTable1974, g_FieldOffsetTable1975, g_FieldOffsetTable1976, g_FieldOffsetTable1977, g_FieldOffsetTable1978, g_FieldOffsetTable1979, g_FieldOffsetTable1980, g_FieldOffsetTable1981, g_FieldOffsetTable1982, g_FieldOffsetTable1983, g_FieldOffsetTable1984, NULL, NULL, g_FieldOffsetTable1987, NULL, NULL, g_FieldOffsetTable1990, NULL, NULL, NULL, g_FieldOffsetTable1994, g_FieldOffsetTable1995, g_FieldOffsetTable1996, g_FieldOffsetTable1997, NULL, g_FieldOffsetTable1999, g_FieldOffsetTable2000, g_FieldOffsetTable2001, NULL, g_FieldOffsetTable2003, g_FieldOffsetTable2004, NULL, g_FieldOffsetTable2006, g_FieldOffsetTable2007, g_FieldOffsetTable2008, g_FieldOffsetTable2009, g_FieldOffsetTable2010, NULL, g_FieldOffsetTable2012, g_FieldOffsetTable2013, g_FieldOffsetTable2014, g_FieldOffsetTable2015, g_FieldOffsetTable2016, NULL, g_FieldOffsetTable2018, g_FieldOffsetTable2019, g_FieldOffsetTable2020, NULL, NULL, g_FieldOffsetTable2023, g_FieldOffsetTable2024, NULL, g_FieldOffsetTable2026, g_FieldOffsetTable2027, g_FieldOffsetTable2028, g_FieldOffsetTable2029, g_FieldOffsetTable2030, g_FieldOffsetTable2031, g_FieldOffsetTable2032, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable2040, g_FieldOffsetTable2041, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable2051, g_FieldOffsetTable2052, g_FieldOffsetTable2053, NULL, g_FieldOffsetTable2055, g_FieldOffsetTable2056, NULL, NULL, g_FieldOffsetTable2059, g_FieldOffsetTable2060, NULL, NULL, NULL, g_FieldOffsetTable2064, NULL, g_FieldOffsetTable2066, g_FieldOffsetTable2067, g_FieldOffsetTable2068, NULL, g_FieldOffsetTable2070, g_FieldOffsetTable2071, g_FieldOffsetTable2072, NULL, NULL, NULL, g_FieldOffsetTable2076, NULL, g_FieldOffsetTable2078, g_FieldOffsetTable2079, g_FieldOffsetTable2080, g_FieldOffsetTable2081, g_FieldOffsetTable2082, g_FieldOffsetTable2083, NULL, g_FieldOffsetTable2085, g_FieldOffsetTable2086, g_FieldOffsetTable2087, g_FieldOffsetTable2088, g_FieldOffsetTable2089, g_FieldOffsetTable2090, g_FieldOffsetTable2091, g_FieldOffsetTable2092, g_FieldOffsetTable2093, g_FieldOffsetTable2094, NULL, NULL, NULL, g_FieldOffsetTable2098, g_FieldOffsetTable2099, g_FieldOffsetTable2100, g_FieldOffsetTable2101, g_FieldOffsetTable2102, g_FieldOffsetTable2103, g_FieldOffsetTable2104, g_FieldOffsetTable2105, g_FieldOffsetTable2106, g_FieldOffsetTable2107, g_FieldOffsetTable2108, g_FieldOffsetTable2109, NULL, NULL, NULL, g_FieldOffsetTable2113, g_FieldOffsetTable2114, g_FieldOffsetTable2115, g_FieldOffsetTable2116, g_FieldOffsetTable2117, g_FieldOffsetTable2118, g_FieldOffsetTable2119, g_FieldOffsetTable2120, g_FieldOffsetTable2121, g_FieldOffsetTable2122, g_FieldOffsetTable2123, g_FieldOffsetTable2124, g_FieldOffsetTable2125, g_FieldOffsetTable2126, g_FieldOffsetTable2127, g_FieldOffsetTable2128, NULL, g_FieldOffsetTable2130, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable2136, g_FieldOffsetTable2137, g_FieldOffsetTable2138, g_FieldOffsetTable2139, g_FieldOffsetTable2140, g_FieldOffsetTable2141, NULL, NULL, g_FieldOffsetTable2144, NULL, NULL, g_FieldOffsetTable2147, NULL, NULL, NULL, g_FieldOffsetTable2151, g_FieldOffsetTable2152, g_FieldOffsetTable2153, g_FieldOffsetTable2154, g_FieldOffsetTable2155, g_FieldOffsetTable2156, NULL, g_FieldOffsetTable2158, g_FieldOffsetTable2159, NULL, g_FieldOffsetTable2161, g_FieldOffsetTable2162, g_FieldOffsetTable2163, g_FieldOffsetTable2164, g_FieldOffsetTable2165, g_FieldOffsetTable2166, NULL, g_FieldOffsetTable2168, NULL, g_FieldOffsetTable2170, g_FieldOffsetTable2171, g_FieldOffsetTable2172, g_FieldOffsetTable2173, g_FieldOffsetTable2174, g_FieldOffsetTable2175, g_FieldOffsetTable2176, NULL, g_FieldOffsetTable2178, g_FieldOffsetTable2179, g_FieldOffsetTable2180, g_FieldOffsetTable2181, g_FieldOffsetTable2182, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable2189, g_FieldOffsetTable2190, NULL, g_FieldOffsetTable2192, NULL, NULL, NULL, NULL, g_FieldOffsetTable2197, g_FieldOffsetTable2198, NULL, g_FieldOffsetTable2200, NULL, g_FieldOffsetTable2202, NULL, g_FieldOffsetTable2204, g_FieldOffsetTable2205, g_FieldOffsetTable2206, g_FieldOffsetTable2207, g_FieldOffsetTable2208, g_FieldOffsetTable2209, g_FieldOffsetTable2210, g_FieldOffsetTable2211, g_FieldOffsetTable2212, g_FieldOffsetTable2213, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, g_FieldOffsetTable2232, NULL, g_FieldOffsetTable2234, g_FieldOffsetTable2235, g_FieldOffsetTable2236, NULL, g_FieldOffsetTable2238, g_FieldOffsetTable2239, NULL, g_FieldOffsetTable2241, g_FieldOffsetTable2242, g_FieldOffsetTable2243, g_FieldOffsetTable2244, g_FieldOffsetTable2245, g_FieldOffsetTable2246, g_FieldOffsetTable2247, g_FieldOffsetTable2248, g_FieldOffsetTable2249, g_FieldOffsetTable2250, g_FieldOffsetTable2251, g_FieldOffsetTable2252, g_FieldOffsetTable2253, g_FieldOffsetTable2254, g_FieldOffsetTable2255, NULL, NULL, g_FieldOffsetTable2258, NULL, g_FieldOffsetTable2260, g_FieldOffsetTable2261, g_FieldOffsetTable2262, NULL, g_FieldOffsetTable2264, NULL, g_FieldOffsetTable2266, g_FieldOffsetTable2267, g_FieldOffsetTable2268, g_FieldOffsetTable2269, g_FieldOffsetTable2270, g_FieldOffsetTable2271, g_FieldOffsetTable2272, NULL, NULL, NULL, NULL, g_FieldOffsetTable2277, NULL, NULL, g_FieldOffsetTable2280, g_FieldOffsetTable2281, g_FieldOffsetTable2282, g_FieldOffsetTable2283, g_FieldOffsetTable2284, g_FieldOffsetTable2285, NULL, g_FieldOffsetTable2287, g_FieldOffsetTable2288, g_FieldOffsetTable2289, g_FieldOffsetTable2290, g_FieldOffsetTable2291, g_FieldOffsetTable2292, }; <file_sep>#include "pch-c.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include "codegen/il2cpp-codegen-metadata.h" // 0x00000001 System.Exception System.Linq.Error::ArgumentNull(System.String) extern void Error_ArgumentNull_m0EDA0D46D72CA692518E3E2EB75B48044D8FD41E (void); // 0x00000002 System.Exception System.Linq.Error::MoreThanOneMatch() extern void Error_MoreThanOneMatch_m4C4756AF34A76EF12F3B2B6D8C78DE547F0FBCF8 (void); // 0x00000003 System.Exception System.Linq.Error::NoElements() extern void Error_NoElements_mB89E91246572F009281D79730950808F17C3F353 (void); // 0x00000004 System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable::Where(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>) // 0x00000005 System.Func`2<TSource,System.Boolean> System.Linq.Enumerable::CombinePredicates(System.Func`2<TSource,System.Boolean>,System.Func`2<TSource,System.Boolean>) // 0x00000006 TSource System.Linq.Enumerable::First(System.Collections.Generic.IEnumerable`1<TSource>) // 0x00000007 TSource System.Linq.Enumerable::SingleOrDefault(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>) // 0x00000008 System.Boolean System.Linq.Enumerable::Any(System.Collections.Generic.IEnumerable`1<TSource>) // 0x00000009 System.Boolean System.Linq.Enumerable::Any(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>) // 0x0000000A System.Int32 System.Linq.Enumerable::Count(System.Collections.Generic.IEnumerable`1<TSource>) // 0x0000000B System.Void System.Linq.Enumerable/Iterator`1::.ctor() // 0x0000000C TSource System.Linq.Enumerable/Iterator`1::get_Current() // 0x0000000D System.Linq.Enumerable/Iterator`1<TSource> System.Linq.Enumerable/Iterator`1::Clone() // 0x0000000E System.Void System.Linq.Enumerable/Iterator`1::Dispose() // 0x0000000F System.Collections.Generic.IEnumerator`1<TSource> System.Linq.Enumerable/Iterator`1::GetEnumerator() // 0x00000010 System.Boolean System.Linq.Enumerable/Iterator`1::MoveNext() // 0x00000011 System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable/Iterator`1::Where(System.Func`2<TSource,System.Boolean>) // 0x00000012 System.Object System.Linq.Enumerable/Iterator`1::System.Collections.IEnumerator.get_Current() // 0x00000013 System.Collections.IEnumerator System.Linq.Enumerable/Iterator`1::System.Collections.IEnumerable.GetEnumerator() // 0x00000014 System.Void System.Linq.Enumerable/Iterator`1::System.Collections.IEnumerator.Reset() // 0x00000015 System.Void System.Linq.Enumerable/WhereEnumerableIterator`1::.ctor(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>) // 0x00000016 System.Linq.Enumerable/Iterator`1<TSource> System.Linq.Enumerable/WhereEnumerableIterator`1::Clone() // 0x00000017 System.Void System.Linq.Enumerable/WhereEnumerableIterator`1::Dispose() // 0x00000018 System.Boolean System.Linq.Enumerable/WhereEnumerableIterator`1::MoveNext() // 0x00000019 System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable/WhereEnumerableIterator`1::Where(System.Func`2<TSource,System.Boolean>) // 0x0000001A System.Void System.Linq.Enumerable/WhereArrayIterator`1::.ctor(TSource[],System.Func`2<TSource,System.Boolean>) // 0x0000001B System.Linq.Enumerable/Iterator`1<TSource> System.Linq.Enumerable/WhereArrayIterator`1::Clone() // 0x0000001C System.Boolean System.Linq.Enumerable/WhereArrayIterator`1::MoveNext() // 0x0000001D System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable/WhereArrayIterator`1::Where(System.Func`2<TSource,System.Boolean>) // 0x0000001E System.Void System.Linq.Enumerable/WhereListIterator`1::.ctor(System.Collections.Generic.List`1<TSource>,System.Func`2<TSource,System.Boolean>) // 0x0000001F System.Linq.Enumerable/Iterator`1<TSource> System.Linq.Enumerable/WhereListIterator`1::Clone() // 0x00000020 System.Boolean System.Linq.Enumerable/WhereListIterator`1::MoveNext() // 0x00000021 System.Collections.Generic.IEnumerable`1<TSource> System.Linq.Enumerable/WhereListIterator`1::Where(System.Func`2<TSource,System.Boolean>) // 0x00000022 System.Void System.Linq.Enumerable/<>c__DisplayClass6_0`1::.ctor() // 0x00000023 System.Boolean System.Linq.Enumerable/<>c__DisplayClass6_0`1::<CombinePredicates>b__0(TSource) // 0x00000024 System.Void System.Collections.Generic.HashSet`1::.ctor() // 0x00000025 System.Void System.Collections.Generic.HashSet`1::.ctor(System.Collections.Generic.IEqualityComparer`1<T>) // 0x00000026 System.Void System.Collections.Generic.HashSet`1::.ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) // 0x00000027 System.Void System.Collections.Generic.HashSet`1::System.Collections.Generic.ICollection<T>.Add(T) // 0x00000028 System.Void System.Collections.Generic.HashSet`1::Clear() // 0x00000029 System.Boolean System.Collections.Generic.HashSet`1::Contains(T) // 0x0000002A System.Void System.Collections.Generic.HashSet`1::CopyTo(T[],System.Int32) // 0x0000002B System.Boolean System.Collections.Generic.HashSet`1::Remove(T) // 0x0000002C System.Int32 System.Collections.Generic.HashSet`1::get_Count() // 0x0000002D System.Boolean System.Collections.Generic.HashSet`1::System.Collections.Generic.ICollection<T>.get_IsReadOnly() // 0x0000002E System.Collections.Generic.HashSet`1/Enumerator<T> System.Collections.Generic.HashSet`1::GetEnumerator() // 0x0000002F System.Collections.Generic.IEnumerator`1<T> System.Collections.Generic.HashSet`1::System.Collections.Generic.IEnumerable<T>.GetEnumerator() // 0x00000030 System.Collections.IEnumerator System.Collections.Generic.HashSet`1::System.Collections.IEnumerable.GetEnumerator() // 0x00000031 System.Void System.Collections.Generic.HashSet`1::GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) // 0x00000032 System.Void System.Collections.Generic.HashSet`1::OnDeserialization(System.Object) // 0x00000033 System.Boolean System.Collections.Generic.HashSet`1::Add(T) // 0x00000034 System.Void System.Collections.Generic.HashSet`1::CopyTo(T[]) // 0x00000035 System.Void System.Collections.Generic.HashSet`1::CopyTo(T[],System.Int32,System.Int32) // 0x00000036 System.Void System.Collections.Generic.HashSet`1::Initialize(System.Int32) // 0x00000037 System.Void System.Collections.Generic.HashSet`1::IncreaseCapacity() // 0x00000038 System.Void System.Collections.Generic.HashSet`1::SetCapacity(System.Int32) // 0x00000039 System.Boolean System.Collections.Generic.HashSet`1::AddIfNotPresent(T) // 0x0000003A System.Int32 System.Collections.Generic.HashSet`1::InternalGetHashCode(T) // 0x0000003B System.Void System.Collections.Generic.HashSet`1/Enumerator::.ctor(System.Collections.Generic.HashSet`1<T>) // 0x0000003C System.Void System.Collections.Generic.HashSet`1/Enumerator::Dispose() // 0x0000003D System.Boolean System.Collections.Generic.HashSet`1/Enumerator::MoveNext() // 0x0000003E T System.Collections.Generic.HashSet`1/Enumerator::get_Current() // 0x0000003F System.Object System.Collections.Generic.HashSet`1/Enumerator::System.Collections.IEnumerator.get_Current() // 0x00000040 System.Void System.Collections.Generic.HashSet`1/Enumerator::System.Collections.IEnumerator.Reset() static Il2CppMethodPointer s_methodPointers[64] = { Error_ArgumentNull_m0EDA0D46D72CA692518E3E2EB75B48044D8FD41E, Error_MoreThanOneMatch_m4C4756AF34A76EF12F3B2B6D8C78DE547F0FBCF8, Error_NoElements_mB89E91246572F009281D79730950808F17C3F353, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; static const int32_t s_InvokerIndices[64] = { 1812, 1890, 1890, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; static const Il2CppTokenRangePair s_rgctxIndices[14] = { { 0x02000004, { 28, 4 } }, { 0x02000005, { 32, 9 } }, { 0x02000006, { 41, 7 } }, { 0x02000007, { 48, 10 } }, { 0x02000008, { 58, 1 } }, { 0x02000009, { 59, 21 } }, { 0x0200000B, { 80, 2 } }, { 0x06000004, { 0, 10 } }, { 0x06000005, { 10, 5 } }, { 0x06000006, { 15, 4 } }, { 0x06000007, { 19, 3 } }, { 0x06000008, { 22, 1 } }, { 0x06000009, { 23, 3 } }, { 0x0600000A, { 26, 2 } }, }; static const Il2CppRGCTXDefinition s_rgctxValues[82] = { { (Il2CppRGCTXDataType)2, 914 }, { (Il2CppRGCTXDataType)3, 2647 }, { (Il2CppRGCTXDataType)2, 1549 }, { (Il2CppRGCTXDataType)2, 1280 }, { (Il2CppRGCTXDataType)3, 4696 }, { (Il2CppRGCTXDataType)2, 970 }, { (Il2CppRGCTXDataType)2, 1284 }, { (Il2CppRGCTXDataType)3, 4709 }, { (Il2CppRGCTXDataType)2, 1282 }, { (Il2CppRGCTXDataType)3, 4702 }, { (Il2CppRGCTXDataType)2, 346 }, { (Il2CppRGCTXDataType)3, 14 }, { (Il2CppRGCTXDataType)3, 15 }, { (Il2CppRGCTXDataType)2, 602 }, { (Il2CppRGCTXDataType)3, 1930 }, { (Il2CppRGCTXDataType)2, 865 }, { (Il2CppRGCTXDataType)2, 642 }, { (Il2CppRGCTXDataType)2, 710 }, { (Il2CppRGCTXDataType)2, 747 }, { (Il2CppRGCTXDataType)2, 711 }, { (Il2CppRGCTXDataType)2, 748 }, { (Il2CppRGCTXDataType)3, 1931 }, { (Il2CppRGCTXDataType)2, 706 }, { (Il2CppRGCTXDataType)2, 707 }, { (Il2CppRGCTXDataType)2, 746 }, { (Il2CppRGCTXDataType)3, 1929 }, { (Il2CppRGCTXDataType)2, 641 }, { (Il2CppRGCTXDataType)2, 709 }, { (Il2CppRGCTXDataType)3, 2648 }, { (Il2CppRGCTXDataType)3, 2650 }, { (Il2CppRGCTXDataType)2, 246 }, { (Il2CppRGCTXDataType)3, 2649 }, { (Il2CppRGCTXDataType)3, 2658 }, { (Il2CppRGCTXDataType)2, 917 }, { (Il2CppRGCTXDataType)2, 1283 }, { (Il2CppRGCTXDataType)3, 4703 }, { (Il2CppRGCTXDataType)3, 2659 }, { (Il2CppRGCTXDataType)2, 727 }, { (Il2CppRGCTXDataType)2, 763 }, { (Il2CppRGCTXDataType)3, 1935 }, { (Il2CppRGCTXDataType)3, 5610 }, { (Il2CppRGCTXDataType)3, 2651 }, { (Il2CppRGCTXDataType)2, 916 }, { (Il2CppRGCTXDataType)2, 1281 }, { (Il2CppRGCTXDataType)3, 4697 }, { (Il2CppRGCTXDataType)3, 1934 }, { (Il2CppRGCTXDataType)3, 2652 }, { (Il2CppRGCTXDataType)3, 5609 }, { (Il2CppRGCTXDataType)3, 2665 }, { (Il2CppRGCTXDataType)2, 918 }, { (Il2CppRGCTXDataType)2, 1285 }, { (Il2CppRGCTXDataType)3, 4710 }, { (Il2CppRGCTXDataType)3, 2911 }, { (Il2CppRGCTXDataType)3, 1384 }, { (Il2CppRGCTXDataType)3, 1936 }, { (Il2CppRGCTXDataType)3, 1383 }, { (Il2CppRGCTXDataType)3, 2666 }, { (Il2CppRGCTXDataType)3, 5611 }, { (Il2CppRGCTXDataType)3, 1933 }, { (Il2CppRGCTXDataType)3, 1667 }, { (Il2CppRGCTXDataType)2, 536 }, { (Il2CppRGCTXDataType)3, 2080 }, { (Il2CppRGCTXDataType)3, 2081 }, { (Il2CppRGCTXDataType)3, 2086 }, { (Il2CppRGCTXDataType)2, 792 }, { (Il2CppRGCTXDataType)3, 2083 }, { (Il2CppRGCTXDataType)3, 5798 }, { (Il2CppRGCTXDataType)2, 518 }, { (Il2CppRGCTXDataType)3, 1378 }, { (Il2CppRGCTXDataType)1, 695 }, { (Il2CppRGCTXDataType)2, 1565 }, { (Il2CppRGCTXDataType)3, 2082 }, { (Il2CppRGCTXDataType)1, 1565 }, { (Il2CppRGCTXDataType)1, 792 }, { (Il2CppRGCTXDataType)2, 1601 }, { (Il2CppRGCTXDataType)2, 1565 }, { (Il2CppRGCTXDataType)3, 2087 }, { (Il2CppRGCTXDataType)3, 2085 }, { (Il2CppRGCTXDataType)3, 2084 }, { (Il2CppRGCTXDataType)2, 166 }, { (Il2CppRGCTXDataType)3, 1385 }, { (Il2CppRGCTXDataType)2, 252 }, }; extern const CustomAttributesCacheGenerator g_System_Core_AttributeGenerators[]; IL2CPP_EXTERN_C const Il2CppCodeGenModule g_System_Core_CodeGenModule; const Il2CppCodeGenModule g_System_Core_CodeGenModule = { "System.Core.dll", 64, s_methodPointers, 0, NULL, s_InvokerIndices, 0, NULL, 14, s_rgctxIndices, 82, s_rgctxValues, NULL, g_System_Core_AttributeGenerators, NULL, // module initializer, NULL, NULL, NULL, }; <file_sep>#include "pch-c.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include "codegen/il2cpp-codegen-metadata.h" // 0x00000001 UnityEngine.GameObject UnityEngine.Collision::get_gameObject() extern void Collision_get_gameObject_m5682F872FD28419AA36F0651CE8B19825A21859D (void); // 0x00000002 UnityEngine.Collider UnityEngine.RaycastHit::get_collider() extern void RaycastHit_get_collider_m13A3DE16FBC631E0A1F987E0B22CE70AF8AB539E (void); // 0x00000003 UnityEngine.Vector3 UnityEngine.RaycastHit::get_point() extern void RaycastHit_get_point_m32F7282CBB2E13393A33BAD046BDA218E48DD21E (void); // 0x00000004 UnityEngine.Vector3 UnityEngine.RaycastHit::get_normal() extern void RaycastHit_get_normal_m2C813B25BAECD87FD9E9CB294278B291F4CC6674 (void); // 0x00000005 System.Single UnityEngine.RaycastHit::get_distance() extern void RaycastHit_get_distance_m85FCA98D7957C3BF1D449CA1B48C116CCD6226FA (void); // 0x00000006 UnityEngine.Vector3 UnityEngine.Rigidbody::get_velocity() extern void Rigidbody_get_velocity_mCFB033F3BD14C2BA68E797DFA4950F9307EC8E2C (void); // 0x00000007 System.Void UnityEngine.Rigidbody::set_velocity(UnityEngine.Vector3) extern void Rigidbody_set_velocity_m8DC0988916EB38DFD7D4584830B41D79140BF18D (void); // 0x00000008 System.Single UnityEngine.Rigidbody::get_mass() extern void Rigidbody_get_mass_mB7B19406DAC6336A8244E98BE271BDA8B5C26223 (void); // 0x00000009 System.Void UnityEngine.Rigidbody::set_useGravity(System.Boolean) extern void Rigidbody_set_useGravity_m1057292FB3199E87664F40B8BCBA7A7E64D1A096 (void); // 0x0000000A System.Void UnityEngine.Rigidbody::set_freezeRotation(System.Boolean) extern void Rigidbody_set_freezeRotation_mE08A39E98D46F82D6DD86CC389D86D242C694D52 (void); // 0x0000000B System.Void UnityEngine.Rigidbody::set_constraints(UnityEngine.RigidbodyConstraints) extern void Rigidbody_set_constraints_mA76F562D16D3BE8889E095D0309C8FE38DA914F1 (void); // 0x0000000C System.Void UnityEngine.Rigidbody::AddForce(UnityEngine.Vector3,UnityEngine.ForceMode) extern void Rigidbody_AddForce_m78B9D94F505E19F3C63461362AD6DE7EA0836700 (void); // 0x0000000D System.Void UnityEngine.Rigidbody::AddForce(UnityEngine.Vector3) extern void Rigidbody_AddForce_mDFB0D57C25682B826999B0074F5C0FD399C6401D (void); // 0x0000000E System.Void UnityEngine.Rigidbody::get_velocity_Injected(UnityEngine.Vector3&) extern void Rigidbody_get_velocity_Injected_m79C6BB8C054D0B5F03F3F13325910BC068E5B796 (void); // 0x0000000F System.Void UnityEngine.Rigidbody::set_velocity_Injected(UnityEngine.Vector3&) extern void Rigidbody_set_velocity_Injected_mBFBC7681B33942F69A5CD908941D399777F66ADD (void); // 0x00000010 System.Void UnityEngine.Rigidbody::AddForce_Injected(UnityEngine.Vector3&,UnityEngine.ForceMode) extern void Rigidbody_AddForce_Injected_m233C3E22C3FE9D2BCBBC510132B82CE26057370C (void); // 0x00000011 UnityEngine.CollisionFlags UnityEngine.CharacterController::Move(UnityEngine.Vector3) extern void CharacterController_Move_mE0EBC32C72A0BEC18EDEBE748D44309A4BA32E60 (void); // 0x00000012 System.Boolean UnityEngine.CharacterController::get_isGrounded() extern void CharacterController_get_isGrounded_m327A1A1940F225FE81E751F255316BB0D8698CBC (void); // 0x00000013 UnityEngine.CollisionFlags UnityEngine.CharacterController::Move_Injected(UnityEngine.Vector3&) extern void CharacterController_Move_Injected_m6A2168A4CDC70CB62E4A4DCB15A74133E8C6C46D (void); // 0x00000014 System.String UnityEngine.PhysicsScene::ToString() extern void PhysicsScene_ToString_mBB6D0AC1E3E2EDC34CB4A7A34485B24B6271903F (void); // 0x00000015 System.Int32 UnityEngine.PhysicsScene::GetHashCode() extern void PhysicsScene_GetHashCode_m5344CC6CCCB1CA6EBB149775EE028089DD74B8A2 (void); // 0x00000016 System.Boolean UnityEngine.PhysicsScene::Equals(System.Object) extern void PhysicsScene_Equals_m2645ABB96C598F197F734EB712494795928CBCEC (void); // 0x00000017 System.Boolean UnityEngine.PhysicsScene::Equals(UnityEngine.PhysicsScene) extern void PhysicsScene_Equals_m8C948B86D105177D519A3608816CDC698C8686B8 (void); // 0x00000018 System.Boolean UnityEngine.PhysicsScene::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void PhysicsScene_Raycast_m8C3E61EB7C3DB8AAC6FEB098D815062BEF821187 (void); // 0x00000019 System.Boolean UnityEngine.PhysicsScene::Internal_RaycastTest(UnityEngine.PhysicsScene,UnityEngine.Ray,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void PhysicsScene_Internal_RaycastTest_m6715CAD8D0330195269AA7FCCD91613BC564E3EB (void); // 0x0000001A System.Boolean UnityEngine.PhysicsScene::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit&,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void PhysicsScene_Raycast_mFC0D59C4439EE9DA6E8AA5F6891915132D587208 (void); // 0x0000001B System.Boolean UnityEngine.PhysicsScene::Internal_Raycast(UnityEngine.PhysicsScene,UnityEngine.Ray,System.Single,UnityEngine.RaycastHit&,System.Int32,UnityEngine.QueryTriggerInteraction) extern void PhysicsScene_Internal_Raycast_m1E630AA11805114B090FC50741AEF64D677AF2C7 (void); // 0x0000001C System.Int32 UnityEngine.PhysicsScene::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit[],System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void PhysicsScene_Raycast_m95CAB68EB9165E3AB2A4D441F7DF9767AD4B7F73 (void); // 0x0000001D System.Int32 UnityEngine.PhysicsScene::Internal_RaycastNonAlloc(UnityEngine.PhysicsScene,UnityEngine.Ray,UnityEngine.RaycastHit[],System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void PhysicsScene_Internal_RaycastNonAlloc_mE7833EE5F1082431A4C2D29362F5DCDEFBF6D2BD (void); // 0x0000001E System.Boolean UnityEngine.PhysicsScene::Internal_RaycastTest_Injected(UnityEngine.PhysicsScene&,UnityEngine.Ray&,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void PhysicsScene_Internal_RaycastTest_Injected_m956474EFEA507F82ABE0BCB75DDB3CC8EFF4D12B (void); // 0x0000001F System.Boolean UnityEngine.PhysicsScene::Internal_Raycast_Injected(UnityEngine.PhysicsScene&,UnityEngine.Ray&,System.Single,UnityEngine.RaycastHit&,System.Int32,UnityEngine.QueryTriggerInteraction) extern void PhysicsScene_Internal_Raycast_Injected_m8868E0BF89F8C42D11F42F94F9CF767647433BB1 (void); // 0x00000020 System.Int32 UnityEngine.PhysicsScene::Internal_RaycastNonAlloc_Injected(UnityEngine.PhysicsScene&,UnityEngine.Ray&,UnityEngine.RaycastHit[],System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void PhysicsScene_Internal_RaycastNonAlloc_Injected_m59FB44C18E62D21E9320F30229C0AA9F9B971211 (void); // 0x00000021 UnityEngine.PhysicsScene UnityEngine.Physics::get_defaultPhysicsScene() extern void Physics_get_defaultPhysicsScene_mA6361488FBAC110DA8397E5E4CB473EBF4191010 (void); // 0x00000022 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_Raycast_m9DE0EEA1CF8DEF7D06216225F19E2958D341F7BA (void); // 0x00000023 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,System.Single,System.Int32) extern void Physics_Raycast_m09F21E13465121A73F19C07FC5F5314CF15ACD15 (void); // 0x00000024 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,System.Single) extern void Physics_Raycast_m284670765E1627E43B7B0F5EC811A688EE595091 (void); // 0x00000025 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Vector3,UnityEngine.Vector3) extern void Physics_Raycast_mDA2EB8C7692308A7178222D31CBA4C7A1C7DC915 (void); // 0x00000026 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit&,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_Raycast_m2EA572B4613E1BD7DBAA299511CFD2DBA179A163 (void); // 0x00000027 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit&,System.Single,System.Int32) extern void Physics_Raycast_mCBD5F7D498C246713EDDBB446E97205DA206C49C (void); // 0x00000028 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit&,System.Single) extern void Physics_Raycast_m18E12C65F127D1AA50D196623F04F81CB138FD12 (void); // 0x00000029 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit&) extern void Physics_Raycast_mE84D30EEFE59DA28DA172342068F092A35B2BE4A (void); // 0x0000002A System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Ray,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_Raycast_m77560CCAA49DC821E51FDDD1570B921D7704646F (void); // 0x0000002B System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Ray,System.Single,System.Int32) extern void Physics_Raycast_mFDC4B8E7979495E3C22D0E3CEA4BCAB271EEC25A (void); // 0x0000002C System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Ray,System.Single) extern void Physics_Raycast_mD7A711D3A790AC505F7229A4FFFA2E389008176B (void); // 0x0000002D System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Ray) extern void Physics_Raycast_m111AFC36A136A67BE4776670E356E99A82010BFE (void); // 0x0000002E System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Ray,UnityEngine.RaycastHit&,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_Raycast_mCA3F2DD1DC08199AAD8466BB857318CD454AC774 (void); // 0x0000002F System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Ray,UnityEngine.RaycastHit&,System.Single,System.Int32) extern void Physics_Raycast_m46E12070D6996F4C8C91D49ADC27C74AC1D6A3D8 (void); // 0x00000030 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Ray,UnityEngine.RaycastHit&,System.Single) extern void Physics_Raycast_mA64F8C30681E3A6A8F2B7EDE592FE7BBC0D354F4 (void); // 0x00000031 System.Boolean UnityEngine.Physics::Raycast(UnityEngine.Ray,UnityEngine.RaycastHit&) extern void Physics_Raycast_m80EC8EEDA0ABA8B01838BA9054834CD1A381916E (void); // 0x00000032 UnityEngine.RaycastHit[] UnityEngine.Physics::Internal_RaycastAll(UnityEngine.PhysicsScene,UnityEngine.Ray,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_Internal_RaycastAll_m39EE7CF896F9D8BA58CC623F14E4DB0641480523 (void); // 0x00000033 UnityEngine.RaycastHit[] UnityEngine.Physics::RaycastAll(UnityEngine.Vector3,UnityEngine.Vector3,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_RaycastAll_m5103E7C60CC66BAFA6534D1736138A92EB1EF2B8 (void); // 0x00000034 UnityEngine.RaycastHit[] UnityEngine.Physics::RaycastAll(UnityEngine.Vector3,UnityEngine.Vector3,System.Single,System.Int32) extern void Physics_RaycastAll_m2C977C8B022672F42B5E18F40B529C0A74B7E471 (void); // 0x00000035 UnityEngine.RaycastHit[] UnityEngine.Physics::RaycastAll(UnityEngine.Vector3,UnityEngine.Vector3,System.Single) extern void Physics_RaycastAll_m2BBC8D2731B38EE0B704A5C6A09D0F8BBA074A4D (void); // 0x00000036 UnityEngine.RaycastHit[] UnityEngine.Physics::RaycastAll(UnityEngine.Vector3,UnityEngine.Vector3) extern void Physics_RaycastAll_m83F28CB671653C07995FB1BCDC561121DE3D9CA6 (void); // 0x00000037 UnityEngine.RaycastHit[] UnityEngine.Physics::RaycastAll(UnityEngine.Ray,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_RaycastAll_m55EB4478198ED6EF838500257FA3BE1A871D3605 (void); // 0x00000038 UnityEngine.RaycastHit[] UnityEngine.Physics::RaycastAll(UnityEngine.Ray,System.Single,System.Int32) extern void Physics_RaycastAll_mA24B9B922C98C5D18397FAE55C04AEAFDD47F029 (void); // 0x00000039 UnityEngine.RaycastHit[] UnityEngine.Physics::RaycastAll(UnityEngine.Ray,System.Single) extern void Physics_RaycastAll_m72947571EFB0EFB34E48340AA2EC0C8030D27C50 (void); // 0x0000003A UnityEngine.RaycastHit[] UnityEngine.Physics::RaycastAll(UnityEngine.Ray) extern void Physics_RaycastAll_m529EE59D6D03E4CFAECE4016C8CC4181BEC2D26D (void); // 0x0000003B System.Int32 UnityEngine.Physics::RaycastNonAlloc(UnityEngine.Ray,UnityEngine.RaycastHit[],System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_RaycastNonAlloc_m7C81125AD7D5891EBC3AB48C6DED7B60F53DF099 (void); // 0x0000003C System.Int32 UnityEngine.Physics::RaycastNonAlloc(UnityEngine.Ray,UnityEngine.RaycastHit[],System.Single,System.Int32) extern void Physics_RaycastNonAlloc_m8F62EE5A33E81A02E4983A171023B7BC4AC700CA (void); // 0x0000003D System.Int32 UnityEngine.Physics::RaycastNonAlloc(UnityEngine.Ray,UnityEngine.RaycastHit[],System.Single) extern void Physics_RaycastNonAlloc_m41BB7BB8755B09700C10F59A29C3541D45AB9CCD (void); // 0x0000003E System.Int32 UnityEngine.Physics::RaycastNonAlloc(UnityEngine.Ray,UnityEngine.RaycastHit[]) extern void Physics_RaycastNonAlloc_mBC5BE514E55B8D98A8F4752DED6850E02EE8AD98 (void); // 0x0000003F System.Int32 UnityEngine.Physics::RaycastNonAlloc(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit[],System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_RaycastNonAlloc_m2C90D14E472DE7929EFD54FDA7BC512D3FBDE4ED (void); // 0x00000040 System.Int32 UnityEngine.Physics::RaycastNonAlloc(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit[],System.Single,System.Int32) extern void Physics_RaycastNonAlloc_m316F597067055C9F923F57CC68D68FF917C3B4D1 (void); // 0x00000041 System.Int32 UnityEngine.Physics::RaycastNonAlloc(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit[],System.Single) extern void Physics_RaycastNonAlloc_m1B8F31BF41F756F561F6AC3A2E0736F2BC9C4DB4 (void); // 0x00000042 System.Int32 UnityEngine.Physics::RaycastNonAlloc(UnityEngine.Vector3,UnityEngine.Vector3,UnityEngine.RaycastHit[]) extern void Physics_RaycastNonAlloc_m9076DDE1A65F87DB3D2824DAD4E5B8B534159F1F (void); // 0x00000043 System.Void UnityEngine.Physics::get_defaultPhysicsScene_Injected(UnityEngine.PhysicsScene&) extern void Physics_get_defaultPhysicsScene_Injected_m0B71068269B3C8499A258BBCAEA7E3D9D020BADA (void); // 0x00000044 UnityEngine.RaycastHit[] UnityEngine.Physics::Internal_RaycastAll_Injected(UnityEngine.PhysicsScene&,UnityEngine.Ray&,System.Single,System.Int32,UnityEngine.QueryTriggerInteraction) extern void Physics_Internal_RaycastAll_Injected_mD4C3E8762D9FCEE654CE0415E636EB7DBEC92A5B (void); static Il2CppMethodPointer s_methodPointers[68] = { Collision_get_gameObject_m5682F872FD28419AA36F0651CE8B19825A21859D, RaycastHit_get_collider_m13A3DE16FBC631E0A1F987E0B22CE70AF8AB539E, RaycastHit_get_point_m32F7282CBB2E13393A33BAD046BDA218E48DD21E, RaycastHit_get_normal_m2C813B25BAECD87FD9E9CB294278B291F4CC6674, RaycastHit_get_distance_m85FCA98D7957C3BF1D449CA1B48C116CCD6226FA, Rigidbody_get_velocity_mCFB033F3BD14C2BA68E797DFA4950F9307EC8E2C, Rigidbody_set_velocity_m8DC0988916EB38DFD7D4584830B41D79140BF18D, Rigidbody_get_mass_mB7B19406DAC6336A8244E98BE271BDA8B5C26223, Rigidbody_set_useGravity_m1057292FB3199E87664F40B8BCBA7A7E64D1A096, Rigidbody_set_freezeRotation_mE08A39E98D46F82D6DD86CC389D86D242C694D52, Rigidbody_set_constraints_mA76F562D16D3BE8889E095D0309C8FE38DA914F1, Rigidbody_AddForce_m78B9D94F505E19F3C63461362AD6DE7EA0836700, Rigidbody_AddForce_mDFB0D57C25682B826999B0074F5C0FD399C6401D, Rigidbody_get_velocity_Injected_m79C6BB8C054D0B5F03F3F13325910BC068E5B796, Rigidbody_set_velocity_Injected_mBFBC7681B33942F69A5CD908941D399777F66ADD, Rigidbody_AddForce_Injected_m233C3E22C3FE9D2BCBBC510132B82CE26057370C, CharacterController_Move_mE0EBC32C72A0BEC18EDEBE748D44309A4BA32E60, CharacterController_get_isGrounded_m327A1A1940F225FE81E751F255316BB0D8698CBC, CharacterController_Move_Injected_m6A2168A4CDC70CB62E4A4DCB15A74133E8C6C46D, PhysicsScene_ToString_mBB6D0AC1E3E2EDC34CB4A7A34485B24B6271903F, PhysicsScene_GetHashCode_m5344CC6CCCB1CA6EBB149775EE028089DD74B8A2, PhysicsScene_Equals_m2645ABB96C598F197F734EB712494795928CBCEC, PhysicsScene_Equals_m8C948B86D105177D519A3608816CDC698C8686B8, PhysicsScene_Raycast_m8C3E61EB7C3DB8AAC6FEB098D815062BEF821187, PhysicsScene_Internal_RaycastTest_m6715CAD8D0330195269AA7FCCD91613BC564E3EB, PhysicsScene_Raycast_mFC0D59C4439EE9DA6E8AA5F6891915132D587208, PhysicsScene_Internal_Raycast_m1E630AA11805114B090FC50741AEF64D677AF2C7, PhysicsScene_Raycast_m95CAB68EB9165E3AB2A4D441F7DF9767AD4B7F73, PhysicsScene_Internal_RaycastNonAlloc_mE7833EE5F1082431A4C2D29362F5DCDEFBF6D2BD, PhysicsScene_Internal_RaycastTest_Injected_m956474EFEA507F82ABE0BCB75DDB3CC8EFF4D12B, PhysicsScene_Internal_Raycast_Injected_m8868E0BF89F8C42D11F42F94F9CF767647433BB1, PhysicsScene_Internal_RaycastNonAlloc_Injected_m59FB44C18E62D21E9320F30229C0AA9F9B971211, Physics_get_defaultPhysicsScene_mA6361488FBAC110DA8397E5E4CB473EBF4191010, Physics_Raycast_m9DE0EEA1CF8DEF7D06216225F19E2958D341F7BA, Physics_Raycast_m09F21E13465121A73F19C07FC5F5314CF15ACD15, Physics_Raycast_m284670765E1627E43B7B0F5EC811A688EE595091, Physics_Raycast_mDA2EB8C7692308A7178222D31CBA4C7A1C7DC915, Physics_Raycast_m2EA572B4613E1BD7DBAA299511CFD2DBA179A163, Physics_Raycast_mCBD5F7D498C246713EDDBB446E97205DA206C49C, Physics_Raycast_m18E12C65F127D1AA50D196623F04F81CB138FD12, Physics_Raycast_mE84D30EEFE59DA28DA172342068F092A35B2BE4A, Physics_Raycast_m77560CCAA49DC821E51FDDD1570B921D7704646F, Physics_Raycast_mFDC4B8E7979495E3C22D0E3CEA4BCAB271EEC25A, Physics_Raycast_mD7A711D3A790AC505F7229A4FFFA2E389008176B, Physics_Raycast_m111AFC36A136A67BE4776670E356E99A82010BFE, Physics_Raycast_mCA3F2DD1DC08199AAD8466BB857318CD454AC774, Physics_Raycast_m46E12070D6996F4C8C91D49ADC27C74AC1D6A3D8, Physics_Raycast_mA64F8C30681E3A6A8F2B7EDE592FE7BBC0D354F4, Physics_Raycast_m80EC8EEDA0ABA8B01838BA9054834CD1A381916E, Physics_Internal_RaycastAll_m39EE7CF896F9D8BA58CC623F14E4DB0641480523, Physics_RaycastAll_m5103E7C60CC66BAFA6534D1736138A92EB1EF2B8, Physics_RaycastAll_m2C977C8B022672F42B5E18F40B529C0A74B7E471, Physics_RaycastAll_m2BBC8D2731B38EE0B704A5C6A09D0F8BBA074A4D, Physics_RaycastAll_m83F28CB671653C07995FB1BCDC561121DE3D9CA6, Physics_RaycastAll_m55EB4478198ED6EF838500257FA3BE1A871D3605, Physics_RaycastAll_mA24B9B922C98C5D18397FAE55C04AEAFDD47F029, Physics_RaycastAll_m72947571EFB0EFB34E48340AA2EC0C8030D27C50, Physics_RaycastAll_m529EE59D6D03E4CFAECE4016C8CC4181BEC2D26D, Physics_RaycastNonAlloc_m7C81125AD7D5891EBC3AB48C6DED7B60F53DF099, Physics_RaycastNonAlloc_m8F62EE5A33E81A02E4983A171023B7BC4AC700CA, Physics_RaycastNonAlloc_m41BB7BB8755B09700C10F59A29C3541D45AB9CCD, Physics_RaycastNonAlloc_mBC5BE514E55B8D98A8F4752DED6850E02EE8AD98, Physics_RaycastNonAlloc_m2C90D14E472DE7929EFD54FDA7BC512D3FBDE4ED, Physics_RaycastNonAlloc_m316F597067055C9F923F57CC68D68FF917C3B4D1, Physics_RaycastNonAlloc_m1B8F31BF41F756F561F6AC3A2E0736F2BC9C4DB4, Physics_RaycastNonAlloc_m9076DDE1A65F87DB3D2824DAD4E5B8B534159F1F, Physics_get_defaultPhysicsScene_Injected_m0B71068269B3C8499A258BBCAEA7E3D9D020BADA, Physics_Internal_RaycastAll_Injected_mD4C3E8762D9FCEE654CE0415E636EB7DBEC92A5B, }; extern void RaycastHit_get_collider_m13A3DE16FBC631E0A1F987E0B22CE70AF8AB539E_AdjustorThunk (void); extern void RaycastHit_get_point_m32F7282CBB2E13393A33BAD046BDA218E48DD21E_AdjustorThunk (void); extern void RaycastHit_get_normal_m2C813B25BAECD87FD9E9CB294278B291F4CC6674_AdjustorThunk (void); extern void RaycastHit_get_distance_m85FCA98D7957C3BF1D449CA1B48C116CCD6226FA_AdjustorThunk (void); extern void PhysicsScene_ToString_mBB6D0AC1E3E2EDC34CB4A7A34485B24B6271903F_AdjustorThunk (void); extern void PhysicsScene_GetHashCode_m5344CC6CCCB1CA6EBB149775EE028089DD74B8A2_AdjustorThunk (void); extern void PhysicsScene_Equals_m2645ABB96C598F197F734EB712494795928CBCEC_AdjustorThunk (void); extern void PhysicsScene_Equals_m8C948B86D105177D519A3608816CDC698C8686B8_AdjustorThunk (void); extern void PhysicsScene_Raycast_m8C3E61EB7C3DB8AAC6FEB098D815062BEF821187_AdjustorThunk (void); extern void PhysicsScene_Raycast_mFC0D59C4439EE9DA6E8AA5F6891915132D587208_AdjustorThunk (void); extern void PhysicsScene_Raycast_m95CAB68EB9165E3AB2A4D441F7DF9767AD4B7F73_AdjustorThunk (void); static Il2CppTokenAdjustorThunkPair s_adjustorThunks[11] = { { 0x06000002, RaycastHit_get_collider_m13A3DE16FBC631E0A1F987E0B22CE70AF8AB539E_AdjustorThunk }, { 0x06000003, RaycastHit_get_point_m32F7282CBB2E13393A33BAD046BDA218E48DD21E_AdjustorThunk }, { 0x06000004, RaycastHit_get_normal_m2C813B25BAECD87FD9E9CB294278B291F4CC6674_AdjustorThunk }, { 0x06000005, RaycastHit_get_distance_m85FCA98D7957C3BF1D449CA1B48C116CCD6226FA_AdjustorThunk }, { 0x06000014, PhysicsScene_ToString_mBB6D0AC1E3E2EDC34CB4A7A34485B24B6271903F_AdjustorThunk }, { 0x06000015, PhysicsScene_GetHashCode_m5344CC6CCCB1CA6EBB149775EE028089DD74B8A2_AdjustorThunk }, { 0x06000016, PhysicsScene_Equals_m2645ABB96C598F197F734EB712494795928CBCEC_AdjustorThunk }, { 0x06000017, PhysicsScene_Equals_m8C948B86D105177D519A3608816CDC698C8686B8_AdjustorThunk }, { 0x06000018, PhysicsScene_Raycast_m8C3E61EB7C3DB8AAC6FEB098D815062BEF821187_AdjustorThunk }, { 0x0600001A, PhysicsScene_Raycast_mFC0D59C4439EE9DA6E8AA5F6891915132D587208_AdjustorThunk }, { 0x0600001C, PhysicsScene_Raycast_m95CAB68EB9165E3AB2A4D441F7DF9767AD4B7F73_AdjustorThunk }, }; static const int32_t s_InvokerIndices[68] = { 1097, 1097, 1126, 1126, 1118, 1126, 994, 1118, 983, 983, 958, 655, 994, 935, 935, 550, 751, 1116, 711, 1097, 1086, 856, 858, 118, 1269, 71, 1202, 57, 1183, 1257, 1195, 1176, 1891, 1272, 1390, 1512, 1672, 1203, 1271, 1389, 1511, 1386, 1509, 1667, 1834, 1270, 1385, 1508, 1666, 1255, 1256, 1359, 1489, 1625, 1357, 1486, 1620, 1813, 1241, 1321, 1448, 1591, 1184, 1242, 1322, 1450, 1864, 1243, }; extern const CustomAttributesCacheGenerator g_UnityEngine_PhysicsModule_AttributeGenerators[]; IL2CPP_EXTERN_C const Il2CppCodeGenModule g_UnityEngine_PhysicsModule_CodeGenModule; const Il2CppCodeGenModule g_UnityEngine_PhysicsModule_CodeGenModule = { "UnityEngine.PhysicsModule.dll", 68, s_methodPointers, 11, s_adjustorThunks, s_InvokerIndices, 0, NULL, 0, NULL, 0, NULL, NULL, g_UnityEngine_PhysicsModule_AttributeGenerators, NULL, // module initializer, NULL, NULL, NULL, }; <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Fog: MonoBehaviour { public float fogDensity = 0.002f; // Update is called once per frame void Update() { fogDensity += Time.deltaTime / 300; RenderSettings.fogDensity = fogDensity; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class MainMenu : MonoBehaviour { // Start is called before the first frame update public void Play() //Lataa ekan kentšn kun painaa play-nappia { SceneManager.LoadScene("Level1"); } public void Credits() { SceneManager.LoadScene("Credits"); } public void Quit() //Poistuu pelistš { Application.Quit(); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Lighting : MonoBehaviour //valonvälkkymistä tässä skriptissä juum { public float intensityMin; public float intensityMax; public float intensitySpeed; float random; public Light roofLight; // Start is called before the first frame update void Start() { roofLight = GetComponent<Light>(); random = Random.Range(0.0f, 1f); } // Update is called once per frame void Update() { float noise = Mathf.PerlinNoise(random, Time.deltaTime * intensitySpeed); roofLight.intensity = Mathf.Lerp(intensityMin, intensityMax, noise); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerLight : MonoBehaviour { public Light spotLight; public static float lightIntensity; public float reduceSpeed; public int maxIntensity; // Start is called before the first frame update void Start() { lightIntensity = maxIntensity; spotLight = GetComponent<Light>(); } // Update is called once per frame void Update() { if (lightIntensity > 0.001) //pienentää lampun valon määrää pikkuhiljaa { lightIntensity -= (Time.deltaTime * reduceSpeed); spotLight.intensity = lightIntensity; } else { return; } } public void IncreaseIntensity() //lisää valon määrää { if (lightIntensity <= maxIntensity) { lightIntensity = lightIntensity + 5; } if (lightIntensity > maxIntensity) { lightIntensity = maxIntensity; } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Nosferatu : MonoBehaviour { public float distance; //miten etäällä nosferatu huomaa pelaajan private Transform target; public Animator animator; // Start is called before the first frame update void Start() { animator = GetComponent<Animator>(); } // Update is called once per frame void Update() { target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>(); if (Vector2.Distance(transform.position, target.position) > distance) { animator.SetBool("Active", true); Debug.Log("prööt"); } else { animator.SetBool("Active", false); Debug.Log("tätä ei pitäis tapahtua"); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Video; public class PlayVideo : MonoBehaviour { // Start is called before the first frame update /* You should put this script on the same component that have the VideoPlayer component */ private VideoPlayer videoPlayer; [SerializeField] private string nomVideo; //name of your video file with his extension like hello.mp4 void Start() { videoPlayer = gameObject.GetComponent<VideoPlayer>(); videoPlayer.url = System.IO.Path.Combine(Application.streamingAssetsPath, nomVideo); videoPlayer.Play(); } // Update is called once per frame void Update() { } }<file_sep>#include "pch-c.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include "codegen/il2cpp-codegen-metadata.h" // 0x00000001 System.Void Door::Start() extern void Door_Start_mA9CDA5E1EC4C187EAC0FD892B42D65A4BA874637 (void); // 0x00000002 System.Void Door::Update() extern void Door_Update_m4D88DB18FEC8010A04BDD6317A04C821A9DE83C9 (void); // 0x00000003 System.Void Door::.ctor() extern void Door__ctor_m233920680DCEDAF41D0AE736031A0D1AB5C99773 (void); // 0x00000004 System.Void DoorGenerator::Start() extern void DoorGenerator_Start_mBDC8D72274B85CA8E4E55B193612CE974C81F77E (void); // 0x00000005 System.Collections.IEnumerator DoorGenerator::SpawnerCoroutine1() extern void DoorGenerator_SpawnerCoroutine1_m491C8AAB3DC3A33DE2CD28DF5DDB6905402DA760 (void); // 0x00000006 System.Void DoorGenerator::.ctor() extern void DoorGenerator__ctor_mBC5083E33A9E19ACCB5E642392D3A72B494023F1 (void); // 0x00000007 System.Void DoorGenerator/<SpawnerCoroutine1>d__4::.ctor(System.Int32) extern void U3CSpawnerCoroutine1U3Ed__4__ctor_mF876BFA52EBF1DBCBBEF1A73AC898ECE915EE7EB (void); // 0x00000008 System.Void DoorGenerator/<SpawnerCoroutine1>d__4::System.IDisposable.Dispose() extern void U3CSpawnerCoroutine1U3Ed__4_System_IDisposable_Dispose_mF3CC80BC28E1B5ADB05A1F24EDF1B4B2944C1D54 (void); // 0x00000009 System.Boolean DoorGenerator/<SpawnerCoroutine1>d__4::MoveNext() extern void U3CSpawnerCoroutine1U3Ed__4_MoveNext_m2BD59AC0FB7960F05823B6BEC9E6505916FEACBF (void); // 0x0000000A System.Object DoorGenerator/<SpawnerCoroutine1>d__4::System.Collections.Generic.IEnumerator<System.Object>.get_Current() extern void U3CSpawnerCoroutine1U3Ed__4_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m53440945F615B9FD629A17723AE00B3285569A78 (void); // 0x0000000B System.Void DoorGenerator/<SpawnerCoroutine1>d__4::System.Collections.IEnumerator.Reset() extern void U3CSpawnerCoroutine1U3Ed__4_System_Collections_IEnumerator_Reset_mC693C89E69AB6F0008DCCFD9CFBA6B89215EA69E (void); // 0x0000000C System.Object DoorGenerator/<SpawnerCoroutine1>d__4::System.Collections.IEnumerator.get_Current() extern void U3CSpawnerCoroutine1U3Ed__4_System_Collections_IEnumerator_get_Current_m387A94449BD691F5509AC7CFA752FA65B94C7B02 (void); // 0x0000000D System.Void EnvironmentGenerator::Start() extern void EnvironmentGenerator_Start_m3183461E261FB43204230D3FC9E7D59E8BC08D9D (void); // 0x0000000E System.Void EnvironmentGenerator::Update() extern void EnvironmentGenerator_Update_mC43E5A427F7568BD6904177C8638C9E4D19C7725 (void); // 0x0000000F System.Void EnvironmentGenerator::.ctor() extern void EnvironmentGenerator__ctor_mA22EA18C2912700B1986350200F4E073A2ECD256 (void); // 0x00000010 System.Void EnvironmentTiling::ActivateCorridor() extern void EnvironmentTiling_ActivateCorridor_m4A158ED61356D3521485976518BA96A4B134CC60 (void); // 0x00000011 System.Void EnvironmentTiling::.ctor() extern void EnvironmentTiling__ctor_m3BADD9213125A58F90C19BF5ABE3D570488D765B (void); // 0x00000012 System.Void GameOverScreen::ScoreSetup(System.Int32) extern void GameOverScreen_ScoreSetup_m77E8D24D02B018BB207656638DF3EFBF237A768F (void); // 0x00000013 System.Void GameOverScreen::Restart() extern void GameOverScreen_Restart_m2986624D742F5C4456A3F6013AF115FE88FA0660 (void); // 0x00000014 System.Void GameOverScreen::MainMenu() extern void GameOverScreen_MainMenu_m86003623895F8ABC194E55B614EFCD4E561D06DA (void); // 0x00000015 System.Void GameOverScreen::.ctor() extern void GameOverScreen__ctor_mE9F89EF0E4A9BFE845256528F4FDE19F075BCD95 (void); // 0x00000016 System.Void MainMenu::Play() extern void MainMenu_Play_m2149EC8228ACC7B581B979DB27BCE127F5EBD2B9 (void); // 0x00000017 System.Void MainMenu::Credits() extern void MainMenu_Credits_m9C985FEF5E2D0CB5C1E31BB67665B4A15ABBF963 (void); // 0x00000018 System.Void MainMenu::Quit() extern void MainMenu_Quit_m65E045D8746B583667D2641184783FDD7796758A (void); // 0x00000019 System.Void MainMenu::.ctor() extern void MainMenu__ctor_m4D77CEC8F91682A2D9492AE815F89B178BF9717D (void); // 0x0000001A System.Void ObstacleMove::Start() extern void ObstacleMove_Start_mE77C89D9B2FE4AF554FF4F30FA779DC3E2482636 (void); // 0x0000001B System.Void ObstacleMove::Update() extern void ObstacleMove_Update_mE4B79D78456499B3A27CA980B09D995F557C0EF5 (void); // 0x0000001C System.Void ObstacleMove::.ctor() extern void ObstacleMove__ctor_m9ABAFED61C7CF65CA4BDE79F6B7606B1B0E38309 (void); // 0x0000001D System.Void ObstacleSpawner::Start() extern void ObstacleSpawner_Start_mBD8A272A8EEAD54E0988D0AE0D7663548DA0C745 (void); // 0x0000001E System.Collections.IEnumerator ObstacleSpawner::SpawnerCoroutine() extern void ObstacleSpawner_SpawnerCoroutine_m4DFA5FB411ADFAF0AC803A49901A8725D75641F8 (void); // 0x0000001F System.Void ObstacleSpawner::.ctor() extern void ObstacleSpawner__ctor_m347D7FB8C7FAEB149F02F9A147EE7E51A28F57ED (void); // 0x00000020 System.Void ObstacleSpawner/<SpawnerCoroutine>d__4::.ctor(System.Int32) extern void U3CSpawnerCoroutineU3Ed__4__ctor_m00AB12936ACCDE67EAED4471CD2C5A91D17BF5CF (void); // 0x00000021 System.Void ObstacleSpawner/<SpawnerCoroutine>d__4::System.IDisposable.Dispose() extern void U3CSpawnerCoroutineU3Ed__4_System_IDisposable_Dispose_m12EC7C2B7C04ACB12DECBD40720DEFD20E6FBF65 (void); // 0x00000022 System.Boolean ObstacleSpawner/<SpawnerCoroutine>d__4::MoveNext() extern void U3CSpawnerCoroutineU3Ed__4_MoveNext_m863FE26CD5AE24AC6FD826B675F6B8C03B684784 (void); // 0x00000023 System.Object ObstacleSpawner/<SpawnerCoroutine>d__4::System.Collections.Generic.IEnumerator<System.Object>.get_Current() extern void U3CSpawnerCoroutineU3Ed__4_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m99720DEC25BBD332E960804E83445B3F04EE585F (void); // 0x00000024 System.Void ObstacleSpawner/<SpawnerCoroutine>d__4::System.Collections.IEnumerator.Reset() extern void U3CSpawnerCoroutineU3Ed__4_System_Collections_IEnumerator_Reset_m16149D060D481F2BD31D3C231DA8A5F3C711D0C5 (void); // 0x00000025 System.Object ObstacleSpawner/<SpawnerCoroutine>d__4::System.Collections.IEnumerator.get_Current() extern void U3CSpawnerCoroutineU3Ed__4_System_Collections_IEnumerator_get_Current_mE5C36A38AA0F1728DFBC8859FAAD5C8934AC08CD (void); // 0x00000026 System.Void PlayVideo::Start() extern void PlayVideo_Start_m96145A3223FEC1254BD1D542C64BCA11B2969F22 (void); // 0x00000027 System.Void PlayVideo::Update() extern void PlayVideo_Update_m3548AFDC6F608BEEBCE2B732BBB5A24DAD098F6B (void); // 0x00000028 System.Void PlayVideo::.ctor() extern void PlayVideo__ctor_mBAE85B15D751315571F6A0E1A677257B6E728C50 (void); // 0x00000029 System.Void Player::Start() extern void Player_Start_mBD692B64AAC791B93A589E7D3596F36787EAF021 (void); // 0x0000002A System.Void Player::Update() extern void Player_Update_mBA04F1D6FE3C18037EA95DFAEEAA9977BFD49CD3 (void); // 0x0000002B System.Void Player::FixedUpdate() extern void Player_FixedUpdate_mD7447EDFC86F29A3E5FBDEF7E0139535BD4C5088 (void); // 0x0000002C System.Void Player::OnCollisionStay() extern void Player_OnCollisionStay_mB00D04AB497C62711DECF8803DE77F16C4E007B0 (void); // 0x0000002D System.Single Player::CalculateJumpVerticalSpeed() extern void Player_CalculateJumpVerticalSpeed_mA671C584D141496A5A4E71A3294CE34FCCC44AD5 (void); // 0x0000002E System.Void Player::OnCollisionEnter(UnityEngine.Collision) extern void Player_OnCollisionEnter_mC2785602469BC029A5E804A22D83459ECE1C42BE (void); // 0x0000002F System.Void Player::Die() extern void Player_Die_m16A200929DBDF9FF88C8191A26327C2CCCC80C19 (void); // 0x00000030 System.Void Player::.ctor() extern void Player__ctor_mDE8EB5B351975D4E7E24DE341B8B49B8A29CC2B7 (void); // 0x00000031 System.Void PlayerMotor::Start() extern void PlayerMotor_Start_mE33AFBCA4469F39BAD92F136838FAC1970470FD6 (void); // 0x00000032 System.Void PlayerMotor::Update() extern void PlayerMotor_Update_m2B85C51BB405823DBA4EF969244010E1CF7D3349 (void); // 0x00000033 System.Void PlayerMotor::.ctor() extern void PlayerMotor__ctor_m69F6DC58548EA8671F5A04801ADAB3D5F22D5E7E (void); static Il2CppMethodPointer s_methodPointers[51] = { Door_Start_mA9CDA5E1EC4C187EAC0FD892B42D65A4BA874637, Door_Update_m4D88DB18FEC8010A04BDD6317A04C821A9DE83C9, Door__ctor_m233920680DCEDAF41D0AE736031A0D1AB5C99773, DoorGenerator_Start_mBDC8D72274B85CA8E4E55B193612CE974C81F77E, DoorGenerator_SpawnerCoroutine1_m491C8AAB3DC3A33DE2CD28DF5DDB6905402DA760, DoorGenerator__ctor_mBC5083E33A9E19ACCB5E642392D3A72B494023F1, U3CSpawnerCoroutine1U3Ed__4__ctor_mF876BFA52EBF1DBCBBEF1A73AC898ECE915EE7EB, U3CSpawnerCoroutine1U3Ed__4_System_IDisposable_Dispose_mF3CC80BC28E1B5ADB05A1F24EDF1B4B2944C1D54, U3CSpawnerCoroutine1U3Ed__4_MoveNext_m2BD59AC0FB7960F05823B6BEC9E6505916FEACBF, U3CSpawnerCoroutine1U3Ed__4_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m53440945F615B9FD629A17723AE00B3285569A78, U3CSpawnerCoroutine1U3Ed__4_System_Collections_IEnumerator_Reset_mC693C89E69AB6F0008DCCFD9CFBA6B89215EA69E, U3CSpawnerCoroutine1U3Ed__4_System_Collections_IEnumerator_get_Current_m387A94449BD691F5509AC7CFA752FA65B94C7B02, EnvironmentGenerator_Start_m3183461E261FB43204230D3FC9E7D59E8BC08D9D, EnvironmentGenerator_Update_mC43E5A427F7568BD6904177C8638C9E4D19C7725, EnvironmentGenerator__ctor_mA22EA18C2912700B1986350200F4E073A2ECD256, EnvironmentTiling_ActivateCorridor_m4A158ED61356D3521485976518BA96A4B134CC60, EnvironmentTiling__ctor_m3BADD9213125A58F90C19BF5ABE3D570488D765B, GameOverScreen_ScoreSetup_m77E8D24D02B018BB207656638DF3EFBF237A768F, GameOverScreen_Restart_m2986624D742F5C4456A3F6013AF115FE88FA0660, GameOverScreen_MainMenu_m86003623895F8ABC194E55B614EFCD4E561D06DA, GameOverScreen__ctor_mE9F89EF0E4A9BFE845256528F4FDE19F075BCD95, MainMenu_Play_m2149EC8228ACC7B581B979DB27BCE127F5EBD2B9, MainMenu_Credits_m9C985FEF5E2D0CB5C1E31BB67665B4A15ABBF963, MainMenu_Quit_m65E045D8746B583667D2641184783FDD7796758A, MainMenu__ctor_m4D77CEC8F91682A2D9492AE815F89B178BF9717D, ObstacleMove_Start_mE77C89D9B2FE4AF554FF4F30FA779DC3E2482636, ObstacleMove_Update_mE4B79D78456499B3A27CA980B09D995F557C0EF5, ObstacleMove__ctor_m9ABAFED61C7CF65CA4BDE79F6B7606B1B0E38309, ObstacleSpawner_Start_mBD8A272A8EEAD54E0988D0AE0D7663548DA0C745, ObstacleSpawner_SpawnerCoroutine_m4DFA5FB411ADFAF0AC803A49901A8725D75641F8, ObstacleSpawner__ctor_m347D7FB8C7FAEB149F02F9A147EE7E51A28F57ED, U3CSpawnerCoroutineU3Ed__4__ctor_m00AB12936ACCDE67EAED4471CD2C5A91D17BF5CF, U3CSpawnerCoroutineU3Ed__4_System_IDisposable_Dispose_m12EC7C2B7C04ACB12DECBD40720DEFD20E6FBF65, U3CSpawnerCoroutineU3Ed__4_MoveNext_m863FE26CD5AE24AC6FD826B675F6B8C03B684784, U3CSpawnerCoroutineU3Ed__4_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m99720DEC25BBD332E960804E83445B3F04EE585F, U3CSpawnerCoroutineU3Ed__4_System_Collections_IEnumerator_Reset_m16149D060D481F2BD31D3C231DA8A5F3C711D0C5, U3CSpawnerCoroutineU3Ed__4_System_Collections_IEnumerator_get_Current_mE5C36A38AA0F1728DFBC8859FAAD5C8934AC08CD, PlayVideo_Start_m96145A3223FEC1254BD1D542C64BCA11B2969F22, PlayVideo_Update_m3548AFDC6F608BEEBCE2B732BBB5A24DAD098F6B, PlayVideo__ctor_mBAE85B15D751315571F6A0E1A677257B6E728C50, Player_Start_mBD692B64AAC791B93A589E7D3596F36787EAF021, Player_Update_mBA04F1D6FE3C18037EA95DFAEEAA9977BFD49CD3, Player_FixedUpdate_mD7447EDFC86F29A3E5FBDEF7E0139535BD4C5088, Player_OnCollisionStay_mB00D04AB497C62711DECF8803DE77F16C4E007B0, Player_CalculateJumpVerticalSpeed_mA671C584D141496A5A4E71A3294CE34FCCC44AD5, Player_OnCollisionEnter_mC2785602469BC029A5E804A22D83459ECE1C42BE, Player_Die_m16A200929DBDF9FF88C8191A26327C2CCCC80C19, Player__ctor_mDE8EB5B351975D4E7E24DE341B8B49B8A29CC2B7, PlayerMotor_Start_mE33AFBCA4469F39BAD92F136838FAC1970470FD6, PlayerMotor_Update_m2B85C51BB405823DBA4EF969244010E1CF7D3349, PlayerMotor__ctor_m69F6DC58548EA8671F5A04801ADAB3D5F22D5E7E, }; static const int32_t s_InvokerIndices[51] = { 1128, 1128, 1128, 1128, 1097, 1128, 958, 1128, 1116, 1097, 1128, 1097, 1128, 1128, 1128, 1128, 1128, 958, 1128, 1128, 1128, 1128, 1128, 1128, 1128, 1128, 1128, 1128, 1128, 1097, 1128, 958, 1128, 1116, 1097, 1128, 1097, 1128, 1128, 1128, 1128, 1128, 1128, 1128, 1118, 967, 1128, 1128, 1128, 1128, 1128, }; extern const CustomAttributesCacheGenerator g_AssemblyU2DCSharp_AttributeGenerators[]; IL2CPP_EXTERN_C const Il2CppCodeGenModule g_AssemblyU2DCSharp_CodeGenModule; const Il2CppCodeGenModule g_AssemblyU2DCSharp_CodeGenModule = { "Assembly-CSharp.dll", 51, s_methodPointers, 0, NULL, s_InvokerIndices, 0, NULL, 0, NULL, 0, NULL, NULL, g_AssemblyU2DCSharp_AttributeGenerators, NULL, // module initializer, NULL, NULL, NULL, }; <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameOverScreen : MonoBehaviour { public Text score; public Text highScore; void Update() { int scoreNumber = PlayerPrefs.GetInt("Score", 0); score.text = "SCORE: " + scoreNumber.ToString(); int highScoreNumber = PlayerPrefs.GetInt("HighScore", 0); highScore.text = "HIGHSCORE: " + highScoreNumber.ToString(); } public void Restart() //Lataa ekan kentšn kun painaa play-nappia { RenderSettings.fogDensity = 0.002f; SceneManager.LoadScene("Level1"); } public void MainMenu() //lataa mainmenun { SceneManager.LoadScene("MainMenu"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CollectibleSpawner : MonoBehaviour { public GameObject candle; public float waitSecondsMin; public float waitSecondsMax; // Start is called before the first frame update void Start() { StartCoroutine(CandleCoroutine()); } IEnumerator CandleCoroutine() { while (enabled) { yield return new WaitForSeconds(Random.Range(waitSecondsMin, waitSecondsMax)); Instantiate(candle, new Vector3(Random.Range(-1.5f, 1.5f), transform.position.y, transform.position.z), transform.rotation); } } }<file_sep>#include "pch-cpp.hpp" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <limits> #include <stdint.h> template <typename R, typename T1, typename T2> struct VirtFuncInvoker2 { typedef R (*Func)(void*, T1, T2, const RuntimeMethod*); static inline R Invoke (Il2CppMethodSlot slot, RuntimeObject* obj, T1 p1, T2 p2) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj); return ((Func)invokeData.methodPtr)(obj, p1, p2, invokeData.method); } }; template <typename T1> struct VirtActionInvoker1 { typedef void (*Action)(void*, T1, const RuntimeMethod*); static inline void Invoke (Il2CppMethodSlot slot, RuntimeObject* obj, T1 p1) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj); ((Action)invokeData.methodPtr)(obj, p1, invokeData.method); } }; // System.Collections.Generic.List`1<EnvironmentTiling> struct List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB; // System.Collections.Generic.List`1<System.Object> struct List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5; // UnityEngine.UI.CoroutineTween.TweenRunner`1<UnityEngine.UI.CoroutineTween.ColorTween> struct TweenRunner_1_tD84B9953874682FCC36990AF2C54D748293908F3; // System.Char[] struct CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34; // UnityEngine.ContactPoint[] struct ContactPointU5BU5D_t1ACD262B1EA44CD48E2039381DE96847F203E62B; // EnvironmentTiling[] struct EnvironmentTilingU5BU5D_tF3C5702B440125FB0BDC3C8FDFF7B730FD0DBC32; // UnityEngine.GameObject[] struct GameObjectU5BU5D_tA88FC1A1FC9D4D73D0B3984D4B0ECE88F4C47642; // System.Int32[] struct Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32; // System.IntPtr[] struct IntPtrU5BU5D_t27FC72B0409D75AAF33EC42498E8094E95FEE9A6; // System.Object[] struct ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE; // System.Diagnostics.StackTrace[] struct StackTraceU5BU5D_t4AD999C288CB6D1F38A299D12B1598D606588971; // UnityEngine.UIVertex[] struct UIVertexU5BU5D_tE3D523C48DFEBC775876720DE2539A79FB7E5E5A; // UnityEngine.Vector2[] struct Vector2U5BU5D_tE0F58A2D6D8592B5EC37D9CDEF09103A02E5D7FA; // UnityEngine.Vector3[] struct Vector3U5BU5D_t5FB88EAA33E46838BDC2ABDAEA3E8727491CB9E4; // UnityEngine.Behaviour struct Behaviour_t1A3DDDCF73B4627928FBFE02ED52B7251777DBD9; // UnityEngine.Camera struct Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C; // UnityEngine.Canvas struct Canvas_t2B7E56B7BDC287962E092755372E214ACB6393EA; // UnityEngine.CanvasRenderer struct CanvasRenderer_tCF8ABE659F7C3A6ED0D99A988D0BDFB651310F0E; // UnityEngine.CharacterController struct CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E; // UnityEngine.Collider struct Collider_t5E81E43C2ECA0209A7C4528E84A632712D192B02; // UnityEngine.Collision struct Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0; // UnityEngine.Component struct Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684; // UnityEngine.Coroutine struct Coroutine_t899D5232EF542CB8BA70AF9ECEECA494FAA9CCB7; // Door struct Door_t7B1F8C89F7CCF5EBECA830A8D7799005C9EE44F6; // DoorGenerator struct DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136; // EnvironmentGenerator struct EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D; // EnvironmentTiling struct EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE; // UnityEngine.UI.FontData struct FontData_t0F1E9B3ED8136CD40782AC9A6AFB69CAD127C738; // UnityEngine.GameObject struct GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319; // GameOverScreen struct GameOverScreen_t66B7C93D73D16C603457FEA3A5424F7DDB6B68A7; // System.Collections.IDictionary struct IDictionary_t99871C56B8EC2452AC5C4CF3831695E617B89D3A; // System.Collections.IEnumerator struct IEnumerator_t5956F3AFB7ECF1117E3BC5890E7FC7B7F7A04105; // MainMenu struct MainMenu_tEB11F5A993C42E93B585FBB65C9E92EC91C5707C; // UnityEngine.Material struct Material_t8927C00353A72755313F046D0CE85178AE8218EE; // UnityEngine.Mesh struct Mesh_t2F5992DBA650D5862B43D3823ACD997132A57DA6; // UnityEngine.MonoBehaviour struct MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A; // System.NotSupportedException struct NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339; // UnityEngine.Object struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A; // ObstacleMove struct ObstacleMove_tCA8BCDF4E1470FF52591F02A0E20D6091EB614DC; // ObstacleSpawner struct ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC; // PlayVideo struct PlayVideo_tD3F8CE49495C7017FEF089C05BC6D56CA20A3E98; // Player struct Player_t5689617909B48F7640EA0892D85C92C13CC22C6F; // PlayerMotor struct PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52; // System.Random struct Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118; // UnityEngine.UI.RectMask2D struct RectMask2D_tD909811991B341D752E4C978C89EFB80FA7A2B15; // UnityEngine.RectTransform struct RectTransform_t8A6A306FB29A6C8C22010CF9040E319753571072; // UnityEngine.Rigidbody struct Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A; // System.Runtime.Serialization.SafeSerializationManager struct SafeSerializationManager_tDE44F029589A028F8A3053C5C06153FAB4AAE29F; // System.String struct String_t; // UnityEngine.UI.Text struct Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1; // UnityEngine.TextGenerator struct TextGenerator_t893F256D3587633108E00E5731CDC5A77AFF1B70; // UnityEngine.Texture2D struct Texture2D_t9B604D0D8E28032123641A7E7338FA872E2698BF; // UnityEngine.Transform struct Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1; // UnityEngine.Events.UnityAction struct UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099; // UnityEngine.UI.VertexHelper struct VertexHelper_tDE8B67D3B076061C4F8DF325B0D63ED2E5367E55; // UnityEngine.Video.VideoPlayer struct VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86; // System.Void struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5; // UnityEngine.WaitForSeconds struct WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013; // UnityEngine.Camera/CameraCallback struct CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D; // DoorGenerator/<SpawnerCoroutine1>d__4 struct U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A; // UnityEngine.UI.MaskableGraphic/CullStateChangedEvent struct CullStateChangedEvent_t9B69755DEBEF041C3CC15C3604610BDD72856BD4; // ObstacleSpawner/<SpawnerCoroutine>d__4 struct U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75; // UnityEngine.Video.VideoPlayer/ErrorEventHandler struct ErrorEventHandler_tD47781EBB7CF0CC4C111496024BD59B1D1A6A1F2; // UnityEngine.Video.VideoPlayer/EventHandler struct EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD; // UnityEngine.Video.VideoPlayer/FrameReadyEventHandler struct FrameReadyEventHandler_t9529BD5A34E9C8BE7D8A39D46A6C4ABC673374EC; // UnityEngine.Video.VideoPlayer/TimeEventHandler struct TimeEventHandler_t7CA131EB85E0FFCBE8660E030698BD83D3994DD8; IL2CPP_EXTERN_C RuntimeClass* EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* Path_tF1D95B78D57C1C1211BA6633FF2AC22FD6C48921_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C String_t* _stringLiteral000E6F488C4BFBAD929A9ED558662797D830E719; IL2CPP_EXTERN_C String_t* _stringLiteral0A04B971B03DA607CE6C455184037B660CA89F78; IL2CPP_EXTERN_C String_t* _stringLiteral5C058FE20FD7652D620A17B5F9D6AE4EEFA76795; IL2CPP_EXTERN_C String_t* _stringLiteral7F8C014BD4810CC276D0F9F81A1E759C7B098B1E; IL2CPP_EXTERN_C String_t* _stringLiteral8739227E8E687EF781DA0D923452C2686CFF10A2; IL2CPP_EXTERN_C String_t* _stringLiteralA02431CF7C501A5B368C91E41283419D8FA9FB03; IL2CPP_EXTERN_C String_t* _stringLiteralB1E5119D36EC43B340C0A0DDC99F1156546EA9DF; IL2CPP_EXTERN_C String_t* _stringLiteralC62B61BC27E509D700023566A09D2AE606BE85A7; IL2CPP_EXTERN_C String_t* _stringLiteralC83B6926DE498999BC7E3D5467A98CDE9B139901; IL2CPP_EXTERN_C String_t* _stringLiteralED35FF3F063D29A026AE09F18392D9C7537823F2; IL2CPP_EXTERN_C String_t* _stringLiteralF59B8D72542CE7CA46EF3732C2A3A46BB5B8EF20; IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponent_TisCharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E_m3DB1DD5819F96D7C7F6F19C12138AC48D21DBBF2_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponent_TisRigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A_m9DC24AA806B0B65E917751F7A3AFDB58861157CE_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* GameObject_GetComponent_TisVideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86_mE0279031C6B378280F6E848C495D87D03F1647B2_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_Add_m9DD38E1D935506058FC2E3F3760DB0717097CEDB_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_RemoveAt_m6839717CCA2768D5DF8850CF9C896D0D4B223F3B_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_m92E7452A54F62BF12651BB65E9ABFCE56433C579_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_get_Count_mC0B6C3963C8EDEC72D02B324F705A66C9C6BB19C_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Object_Instantiate_TisEnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE_m71CB2DF77D915C7F7A0FE4F736AF7CCB0AAFF788_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* U3CSpawnerCoroutine1U3Ed__4_System_Collections_IEnumerator_Reset_mC693C89E69AB6F0008DCCFD9CFBA6B89215EA69E_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* U3CSpawnerCoroutineU3Ed__4_System_Collections_IEnumerator_Reset_m16149D060D481F2BD31D3C231DA8A5F3C711D0C5_RuntimeMethod_var; struct ContactPoint_tC179732A8E0014F5EFF5977ED1ADF12CF14A9017 ; struct Exception_t_marshaled_com; struct Exception_t_marshaled_pinvoke; struct GameObjectU5BU5D_tA88FC1A1FC9D4D73D0B3984D4B0ECE88F4C47642; struct ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_tFDCAFCBB4B3431CFF2DC4D3E03FBFDF54EFF7E9A { public: public: }; // System.Object // System.Collections.Generic.List`1<EnvironmentTiling> struct List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items EnvironmentTilingU5BU5D_tF3C5702B440125FB0BDC3C8FDFF7B730FD0DBC32* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB, ____items_1)); } inline EnvironmentTilingU5BU5D_tF3C5702B440125FB0BDC3C8FDFF7B730FD0DBC32* get__items_1() const { return ____items_1; } inline EnvironmentTilingU5BU5D_tF3C5702B440125FB0BDC3C8FDFF7B730FD0DBC32** get_address_of__items_1() { return &____items_1; } inline void set__items_1(EnvironmentTilingU5BU5D_tF3C5702B440125FB0BDC3C8FDFF7B730FD0DBC32* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray EnvironmentTilingU5BU5D_tF3C5702B440125FB0BDC3C8FDFF7B730FD0DBC32* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB_StaticFields, ____emptyArray_5)); } inline EnvironmentTilingU5BU5D_tF3C5702B440125FB0BDC3C8FDFF7B730FD0DBC32* get__emptyArray_5() const { return ____emptyArray_5; } inline EnvironmentTilingU5BU5D_tF3C5702B440125FB0BDC3C8FDFF7B730FD0DBC32** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(EnvironmentTilingU5BU5D_tF3C5702B440125FB0BDC3C8FDFF7B730FD0DBC32* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<System.Object> struct List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5, ____items_1)); } inline ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE* get__items_1() const { return ____items_1; } inline ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE** get_address_of__items_1() { return &____items_1; } inline void set__items_1(ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5_StaticFields, ____emptyArray_5)); } inline ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE* get__emptyArray_5() const { return ____emptyArray_5; } inline ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; struct Il2CppArrayBounds; // System.Array // System.Random struct Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118 : public RuntimeObject { public: // System.Int32 System.Random::inext int32_t ___inext_0; // System.Int32 System.Random::inextp int32_t ___inextp_1; // System.Int32[] System.Random::SeedArray Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* ___SeedArray_2; public: inline static int32_t get_offset_of_inext_0() { return static_cast<int32_t>(offsetof(Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118, ___inext_0)); } inline int32_t get_inext_0() const { return ___inext_0; } inline int32_t* get_address_of_inext_0() { return &___inext_0; } inline void set_inext_0(int32_t value) { ___inext_0 = value; } inline static int32_t get_offset_of_inextp_1() { return static_cast<int32_t>(offsetof(Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118, ___inextp_1)); } inline int32_t get_inextp_1() const { return ___inextp_1; } inline int32_t* get_address_of_inextp_1() { return &___inextp_1; } inline void set_inextp_1(int32_t value) { ___inextp_1 = value; } inline static int32_t get_offset_of_SeedArray_2() { return static_cast<int32_t>(offsetof(Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118, ___SeedArray_2)); } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* get_SeedArray_2() const { return ___SeedArray_2; } inline Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32** get_address_of_SeedArray_2() { return &___SeedArray_2; } inline void set_SeedArray_2(Int32U5BU5D_t70F1BDC14B1786481B176D6139A5E3B87DC54C32* value) { ___SeedArray_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___SeedArray_2), (void*)value); } }; // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::m_stringLength int32_t ___m_stringLength_0; // System.Char System.String::m_firstChar Il2CppChar ___m_firstChar_1; public: inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); } inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; } inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; } inline void set_m_stringLength_0(int32_t value) { ___m_stringLength_0 = value; } inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); } inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; } inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; } inline void set_m_firstChar_1(Il2CppChar value) { ___m_firstChar_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_5; public: inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); } inline String_t* get_Empty_5() const { return ___Empty_5; } inline String_t** get_address_of_Empty_5() { return &___Empty_5; } inline void set_Empty_5(String_t* value) { ___Empty_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___Empty_5), (void*)value); } }; // System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_com { }; // UnityEngine.YieldInstruction struct YieldInstruction_tB0B4E05316710E51ECCC1E57174C27FE6DEBBEAF : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of UnityEngine.YieldInstruction struct YieldInstruction_tB0B4E05316710E51ECCC1E57174C27FE6DEBBEAF_marshaled_pinvoke { }; // Native definition for COM marshalling of UnityEngine.YieldInstruction struct YieldInstruction_tB0B4E05316710E51ECCC1E57174C27FE6DEBBEAF_marshaled_com { }; // DoorGenerator/<SpawnerCoroutine1>d__4 struct U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A : public RuntimeObject { public: // System.Int32 DoorGenerator/<SpawnerCoroutine1>d__4::<>1__state int32_t ___U3CU3E1__state_0; // System.Object DoorGenerator/<SpawnerCoroutine1>d__4::<>2__current RuntimeObject * ___U3CU3E2__current_1; // DoorGenerator DoorGenerator/<SpawnerCoroutine1>d__4::<>4__this DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * ___U3CU3E4__this_2; public: inline static int32_t get_offset_of_U3CU3E1__state_0() { return static_cast<int32_t>(offsetof(U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A, ___U3CU3E1__state_0)); } inline int32_t get_U3CU3E1__state_0() const { return ___U3CU3E1__state_0; } inline int32_t* get_address_of_U3CU3E1__state_0() { return &___U3CU3E1__state_0; } inline void set_U3CU3E1__state_0(int32_t value) { ___U3CU3E1__state_0 = value; } inline static int32_t get_offset_of_U3CU3E2__current_1() { return static_cast<int32_t>(offsetof(U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A, ___U3CU3E2__current_1)); } inline RuntimeObject * get_U3CU3E2__current_1() const { return ___U3CU3E2__current_1; } inline RuntimeObject ** get_address_of_U3CU3E2__current_1() { return &___U3CU3E2__current_1; } inline void set_U3CU3E2__current_1(RuntimeObject * value) { ___U3CU3E2__current_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CU3E2__current_1), (void*)value); } inline static int32_t get_offset_of_U3CU3E4__this_2() { return static_cast<int32_t>(offsetof(U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A, ___U3CU3E4__this_2)); } inline DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * get_U3CU3E4__this_2() const { return ___U3CU3E4__this_2; } inline DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 ** get_address_of_U3CU3E4__this_2() { return &___U3CU3E4__this_2; } inline void set_U3CU3E4__this_2(DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * value) { ___U3CU3E4__this_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CU3E4__this_2), (void*)value); } }; // ObstacleSpawner/<SpawnerCoroutine>d__4 struct U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 : public RuntimeObject { public: // System.Int32 ObstacleSpawner/<SpawnerCoroutine>d__4::<>1__state int32_t ___U3CU3E1__state_0; // System.Object ObstacleSpawner/<SpawnerCoroutine>d__4::<>2__current RuntimeObject * ___U3CU3E2__current_1; // ObstacleSpawner ObstacleSpawner/<SpawnerCoroutine>d__4::<>4__this ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * ___U3CU3E4__this_2; public: inline static int32_t get_offset_of_U3CU3E1__state_0() { return static_cast<int32_t>(offsetof(U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75, ___U3CU3E1__state_0)); } inline int32_t get_U3CU3E1__state_0() const { return ___U3CU3E1__state_0; } inline int32_t* get_address_of_U3CU3E1__state_0() { return &___U3CU3E1__state_0; } inline void set_U3CU3E1__state_0(int32_t value) { ___U3CU3E1__state_0 = value; } inline static int32_t get_offset_of_U3CU3E2__current_1() { return static_cast<int32_t>(offsetof(U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75, ___U3CU3E2__current_1)); } inline RuntimeObject * get_U3CU3E2__current_1() const { return ___U3CU3E2__current_1; } inline RuntimeObject ** get_address_of_U3CU3E2__current_1() { return &___U3CU3E2__current_1; } inline void set_U3CU3E2__current_1(RuntimeObject * value) { ___U3CU3E2__current_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CU3E2__current_1), (void*)value); } inline static int32_t get_offset_of_U3CU3E4__this_2() { return static_cast<int32_t>(offsetof(U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75, ___U3CU3E4__this_2)); } inline ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * get_U3CU3E4__this_2() const { return ___U3CU3E4__this_2; } inline ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC ** get_address_of_U3CU3E4__this_2() { return &___U3CU3E4__this_2; } inline void set_U3CU3E4__this_2(ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * value) { ___U3CU3E4__this_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CU3E4__this_2), (void*)value); } }; // System.Boolean struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37 { public: // System.Boolean System.Boolean::m_value bool ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37, ___m_value_0)); } inline bool get_m_value_0() const { return ___m_value_0; } inline bool* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(bool value) { ___m_value_0 = value; } }; struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields { public: // System.String System.Boolean::TrueString String_t* ___TrueString_5; // System.String System.Boolean::FalseString String_t* ___FalseString_6; public: inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___TrueString_5)); } inline String_t* get_TrueString_5() const { return ___TrueString_5; } inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; } inline void set_TrueString_5(String_t* value) { ___TrueString_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___TrueString_5), (void*)value); } inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___FalseString_6)); } inline String_t* get_FalseString_6() const { return ___FalseString_6; } inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; } inline void set_FalseString_6(String_t* value) { ___FalseString_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___FalseString_6), (void*)value); } }; // UnityEngine.Color struct Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659 { public: // System.Single UnityEngine.Color::r float ___r_0; // System.Single UnityEngine.Color::g float ___g_1; // System.Single UnityEngine.Color::b float ___b_2; // System.Single UnityEngine.Color::a float ___a_3; public: inline static int32_t get_offset_of_r_0() { return static_cast<int32_t>(offsetof(Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659, ___r_0)); } inline float get_r_0() const { return ___r_0; } inline float* get_address_of_r_0() { return &___r_0; } inline void set_r_0(float value) { ___r_0 = value; } inline static int32_t get_offset_of_g_1() { return static_cast<int32_t>(offsetof(Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659, ___g_1)); } inline float get_g_1() const { return ___g_1; } inline float* get_address_of_g_1() { return &___g_1; } inline void set_g_1(float value) { ___g_1 = value; } inline static int32_t get_offset_of_b_2() { return static_cast<int32_t>(offsetof(Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659, ___b_2)); } inline float get_b_2() const { return ___b_2; } inline float* get_address_of_b_2() { return &___b_2; } inline void set_b_2(float value) { ___b_2 = value; } inline static int32_t get_offset_of_a_3() { return static_cast<int32_t>(offsetof(Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659, ___a_3)); } inline float get_a_3() const { return ___a_3; } inline float* get_address_of_a_3() { return &___a_3; } inline void set_a_3(float value) { ___a_3 = value; } }; // System.Enum struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA : public ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 { public: public: }; struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___enumSeperatorCharArray_0), (void*)value); } }; // Native definition for P/Invoke marshalling of System.Enum struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_com { }; // System.Int32 struct Int32_tFDE5F8CD43D10453F6A2E0C77FE48C6CC7009046 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_tFDE5F8CD43D10453F6A2E0C77FE48C6CC7009046, ___m_value_0)); } inline int32_t get_m_value_0() const { return ___m_value_0; } inline int32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int32_t value) { ___m_value_0 = value; } }; // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; // UnityEngine.Quaternion struct Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 { public: // System.Single UnityEngine.Quaternion::x float ___x_0; // System.Single UnityEngine.Quaternion::y float ___y_1; // System.Single UnityEngine.Quaternion::z float ___z_2; // System.Single UnityEngine.Quaternion::w float ___w_3; public: inline static int32_t get_offset_of_x_0() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4, ___x_0)); } inline float get_x_0() const { return ___x_0; } inline float* get_address_of_x_0() { return &___x_0; } inline void set_x_0(float value) { ___x_0 = value; } inline static int32_t get_offset_of_y_1() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4, ___y_1)); } inline float get_y_1() const { return ___y_1; } inline float* get_address_of_y_1() { return &___y_1; } inline void set_y_1(float value) { ___y_1 = value; } inline static int32_t get_offset_of_z_2() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4, ___z_2)); } inline float get_z_2() const { return ___z_2; } inline float* get_address_of_z_2() { return &___z_2; } inline void set_z_2(float value) { ___z_2 = value; } inline static int32_t get_offset_of_w_3() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4, ___w_3)); } inline float get_w_3() const { return ___w_3; } inline float* get_address_of_w_3() { return &___w_3; } inline void set_w_3(float value) { ___w_3 = value; } }; struct Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4_StaticFields { public: // UnityEngine.Quaternion UnityEngine.Quaternion::identityQuaternion Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 ___identityQuaternion_4; public: inline static int32_t get_offset_of_identityQuaternion_4() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4_StaticFields, ___identityQuaternion_4)); } inline Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 get_identityQuaternion_4() const { return ___identityQuaternion_4; } inline Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 * get_address_of_identityQuaternion_4() { return &___identityQuaternion_4; } inline void set_identityQuaternion_4(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 value) { ___identityQuaternion_4 = value; } }; // System.Single struct Single_tE07797BA3C98D4CA9B5A19413C19A76688AB899E { public: // System.Single System.Single::m_value float ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Single_tE07797BA3C98D4CA9B5A19413C19A76688AB899E, ___m_value_0)); } inline float get_m_value_0() const { return ___m_value_0; } inline float* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(float value) { ___m_value_0 = value; } }; // UnityEngine.Vector3 struct Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E { public: // System.Single UnityEngine.Vector3::x float ___x_2; // System.Single UnityEngine.Vector3::y float ___y_3; // System.Single UnityEngine.Vector3::z float ___z_4; public: inline static int32_t get_offset_of_x_2() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E, ___x_2)); } inline float get_x_2() const { return ___x_2; } inline float* get_address_of_x_2() { return &___x_2; } inline void set_x_2(float value) { ___x_2 = value; } inline static int32_t get_offset_of_y_3() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E, ___y_3)); } inline float get_y_3() const { return ___y_3; } inline float* get_address_of_y_3() { return &___y_3; } inline void set_y_3(float value) { ___y_3 = value; } inline static int32_t get_offset_of_z_4() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E, ___z_4)); } inline float get_z_4() const { return ___z_4; } inline float* get_address_of_z_4() { return &___z_4; } inline void set_z_4(float value) { ___z_4 = value; } }; struct Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields { public: // UnityEngine.Vector3 UnityEngine.Vector3::zeroVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___zeroVector_5; // UnityEngine.Vector3 UnityEngine.Vector3::oneVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___oneVector_6; // UnityEngine.Vector3 UnityEngine.Vector3::upVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___upVector_7; // UnityEngine.Vector3 UnityEngine.Vector3::downVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___downVector_8; // UnityEngine.Vector3 UnityEngine.Vector3::leftVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___leftVector_9; // UnityEngine.Vector3 UnityEngine.Vector3::rightVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___rightVector_10; // UnityEngine.Vector3 UnityEngine.Vector3::forwardVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___forwardVector_11; // UnityEngine.Vector3 UnityEngine.Vector3::backVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___backVector_12; // UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___positiveInfinityVector_13; // UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___negativeInfinityVector_14; public: inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___zeroVector_5)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_zeroVector_5() const { return ___zeroVector_5; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_zeroVector_5() { return &___zeroVector_5; } inline void set_zeroVector_5(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___zeroVector_5 = value; } inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___oneVector_6)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_oneVector_6() const { return ___oneVector_6; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_oneVector_6() { return &___oneVector_6; } inline void set_oneVector_6(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___oneVector_6 = value; } inline static int32_t get_offset_of_upVector_7() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___upVector_7)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_upVector_7() const { return ___upVector_7; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_upVector_7() { return &___upVector_7; } inline void set_upVector_7(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___upVector_7 = value; } inline static int32_t get_offset_of_downVector_8() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___downVector_8)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_downVector_8() const { return ___downVector_8; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_downVector_8() { return &___downVector_8; } inline void set_downVector_8(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___downVector_8 = value; } inline static int32_t get_offset_of_leftVector_9() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___leftVector_9)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_leftVector_9() const { return ___leftVector_9; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_leftVector_9() { return &___leftVector_9; } inline void set_leftVector_9(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___leftVector_9 = value; } inline static int32_t get_offset_of_rightVector_10() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___rightVector_10)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_rightVector_10() const { return ___rightVector_10; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_rightVector_10() { return &___rightVector_10; } inline void set_rightVector_10(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___rightVector_10 = value; } inline static int32_t get_offset_of_forwardVector_11() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___forwardVector_11)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_forwardVector_11() const { return ___forwardVector_11; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_forwardVector_11() { return &___forwardVector_11; } inline void set_forwardVector_11(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___forwardVector_11 = value; } inline static int32_t get_offset_of_backVector_12() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___backVector_12)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_backVector_12() const { return ___backVector_12; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_backVector_12() { return &___backVector_12; } inline void set_backVector_12(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___backVector_12 = value; } inline static int32_t get_offset_of_positiveInfinityVector_13() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___positiveInfinityVector_13)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_positiveInfinityVector_13() const { return ___positiveInfinityVector_13; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_positiveInfinityVector_13() { return &___positiveInfinityVector_13; } inline void set_positiveInfinityVector_13(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___positiveInfinityVector_13 = value; } inline static int32_t get_offset_of_negativeInfinityVector_14() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___negativeInfinityVector_14)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_negativeInfinityVector_14() const { return ___negativeInfinityVector_14; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_negativeInfinityVector_14() { return &___negativeInfinityVector_14; } inline void set_negativeInfinityVector_14(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___negativeInfinityVector_14 = value; } }; // UnityEngine.Vector4 struct Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 { public: // System.Single UnityEngine.Vector4::x float ___x_1; // System.Single UnityEngine.Vector4::y float ___y_2; // System.Single UnityEngine.Vector4::z float ___z_3; // System.Single UnityEngine.Vector4::w float ___w_4; public: inline static int32_t get_offset_of_x_1() { return static_cast<int32_t>(offsetof(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7, ___x_1)); } inline float get_x_1() const { return ___x_1; } inline float* get_address_of_x_1() { return &___x_1; } inline void set_x_1(float value) { ___x_1 = value; } inline static int32_t get_offset_of_y_2() { return static_cast<int32_t>(offsetof(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7, ___y_2)); } inline float get_y_2() const { return ___y_2; } inline float* get_address_of_y_2() { return &___y_2; } inline void set_y_2(float value) { ___y_2 = value; } inline static int32_t get_offset_of_z_3() { return static_cast<int32_t>(offsetof(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7, ___z_3)); } inline float get_z_3() const { return ___z_3; } inline float* get_address_of_z_3() { return &___z_3; } inline void set_z_3(float value) { ___z_3 = value; } inline static int32_t get_offset_of_w_4() { return static_cast<int32_t>(offsetof(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7, ___w_4)); } inline float get_w_4() const { return ___w_4; } inline float* get_address_of_w_4() { return &___w_4; } inline void set_w_4(float value) { ___w_4 = value; } }; struct Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7_StaticFields { public: // UnityEngine.Vector4 UnityEngine.Vector4::zeroVector Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 ___zeroVector_5; // UnityEngine.Vector4 UnityEngine.Vector4::oneVector Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 ___oneVector_6; // UnityEngine.Vector4 UnityEngine.Vector4::positiveInfinityVector Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 ___positiveInfinityVector_7; // UnityEngine.Vector4 UnityEngine.Vector4::negativeInfinityVector Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 ___negativeInfinityVector_8; public: inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7_StaticFields, ___zeroVector_5)); } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 get_zeroVector_5() const { return ___zeroVector_5; } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 * get_address_of_zeroVector_5() { return &___zeroVector_5; } inline void set_zeroVector_5(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 value) { ___zeroVector_5 = value; } inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7_StaticFields, ___oneVector_6)); } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 get_oneVector_6() const { return ___oneVector_6; } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 * get_address_of_oneVector_6() { return &___oneVector_6; } inline void set_oneVector_6(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 value) { ___oneVector_6 = value; } inline static int32_t get_offset_of_positiveInfinityVector_7() { return static_cast<int32_t>(offsetof(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7_StaticFields, ___positiveInfinityVector_7)); } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 get_positiveInfinityVector_7() const { return ___positiveInfinityVector_7; } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 * get_address_of_positiveInfinityVector_7() { return &___positiveInfinityVector_7; } inline void set_positiveInfinityVector_7(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 value) { ___positiveInfinityVector_7 = value; } inline static int32_t get_offset_of_negativeInfinityVector_8() { return static_cast<int32_t>(offsetof(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7_StaticFields, ___negativeInfinityVector_8)); } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 get_negativeInfinityVector_8() const { return ___negativeInfinityVector_8; } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 * get_address_of_negativeInfinityVector_8() { return &___negativeInfinityVector_8; } inline void set_negativeInfinityVector_8(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 value) { ___negativeInfinityVector_8 = value; } }; // System.Void struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5 { public: union { struct { }; uint8_t Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5__padding[1]; }; public: }; // UnityEngine.WaitForSeconds struct WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013 : public YieldInstruction_tB0B4E05316710E51ECCC1E57174C27FE6DEBBEAF { public: // System.Single UnityEngine.WaitForSeconds::m_Seconds float ___m_Seconds_0; public: inline static int32_t get_offset_of_m_Seconds_0() { return static_cast<int32_t>(offsetof(WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013, ___m_Seconds_0)); } inline float get_m_Seconds_0() const { return ___m_Seconds_0; } inline float* get_address_of_m_Seconds_0() { return &___m_Seconds_0; } inline void set_m_Seconds_0(float value) { ___m_Seconds_0 = value; } }; // Native definition for P/Invoke marshalling of UnityEngine.WaitForSeconds struct WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013_marshaled_pinvoke : public YieldInstruction_tB0B4E05316710E51ECCC1E57174C27FE6DEBBEAF_marshaled_pinvoke { float ___m_Seconds_0; }; // Native definition for COM marshalling of UnityEngine.WaitForSeconds struct WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013_marshaled_com : public YieldInstruction_tB0B4E05316710E51ECCC1E57174C27FE6DEBBEAF_marshaled_com { float ___m_Seconds_0; }; // UnityEngine.Collision struct Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0 : public RuntimeObject { public: // UnityEngine.Vector3 UnityEngine.Collision::m_Impulse Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___m_Impulse_0; // UnityEngine.Vector3 UnityEngine.Collision::m_RelativeVelocity Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___m_RelativeVelocity_1; // UnityEngine.Component UnityEngine.Collision::m_Body Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * ___m_Body_2; // UnityEngine.Collider UnityEngine.Collision::m_Collider Collider_t5E81E43C2ECA0209A7C4528E84A632712D192B02 * ___m_Collider_3; // System.Int32 UnityEngine.Collision::m_ContactCount int32_t ___m_ContactCount_4; // UnityEngine.ContactPoint[] UnityEngine.Collision::m_ReusedContacts ContactPointU5BU5D_t1ACD262B1EA44CD48E2039381DE96847F203E62B* ___m_ReusedContacts_5; // UnityEngine.ContactPoint[] UnityEngine.Collision::m_LegacyContacts ContactPointU5BU5D_t1ACD262B1EA44CD48E2039381DE96847F203E62B* ___m_LegacyContacts_6; public: inline static int32_t get_offset_of_m_Impulse_0() { return static_cast<int32_t>(offsetof(Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0, ___m_Impulse_0)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_m_Impulse_0() const { return ___m_Impulse_0; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_m_Impulse_0() { return &___m_Impulse_0; } inline void set_m_Impulse_0(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___m_Impulse_0 = value; } inline static int32_t get_offset_of_m_RelativeVelocity_1() { return static_cast<int32_t>(offsetof(Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0, ___m_RelativeVelocity_1)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_m_RelativeVelocity_1() const { return ___m_RelativeVelocity_1; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_m_RelativeVelocity_1() { return &___m_RelativeVelocity_1; } inline void set_m_RelativeVelocity_1(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___m_RelativeVelocity_1 = value; } inline static int32_t get_offset_of_m_Body_2() { return static_cast<int32_t>(offsetof(Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0, ___m_Body_2)); } inline Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * get_m_Body_2() const { return ___m_Body_2; } inline Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 ** get_address_of_m_Body_2() { return &___m_Body_2; } inline void set_m_Body_2(Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * value) { ___m_Body_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Body_2), (void*)value); } inline static int32_t get_offset_of_m_Collider_3() { return static_cast<int32_t>(offsetof(Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0, ___m_Collider_3)); } inline Collider_t5E81E43C2ECA0209A7C4528E84A632712D192B02 * get_m_Collider_3() const { return ___m_Collider_3; } inline Collider_t5E81E43C2ECA0209A7C4528E84A632712D192B02 ** get_address_of_m_Collider_3() { return &___m_Collider_3; } inline void set_m_Collider_3(Collider_t5E81E43C2ECA0209A7C4528E84A632712D192B02 * value) { ___m_Collider_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Collider_3), (void*)value); } inline static int32_t get_offset_of_m_ContactCount_4() { return static_cast<int32_t>(offsetof(Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0, ___m_ContactCount_4)); } inline int32_t get_m_ContactCount_4() const { return ___m_ContactCount_4; } inline int32_t* get_address_of_m_ContactCount_4() { return &___m_ContactCount_4; } inline void set_m_ContactCount_4(int32_t value) { ___m_ContactCount_4 = value; } inline static int32_t get_offset_of_m_ReusedContacts_5() { return static_cast<int32_t>(offsetof(Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0, ___m_ReusedContacts_5)); } inline ContactPointU5BU5D_t1ACD262B1EA44CD48E2039381DE96847F203E62B* get_m_ReusedContacts_5() const { return ___m_ReusedContacts_5; } inline ContactPointU5BU5D_t1ACD262B1EA44CD48E2039381DE96847F203E62B** get_address_of_m_ReusedContacts_5() { return &___m_ReusedContacts_5; } inline void set_m_ReusedContacts_5(ContactPointU5BU5D_t1ACD262B1EA44CD48E2039381DE96847F203E62B* value) { ___m_ReusedContacts_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_ReusedContacts_5), (void*)value); } inline static int32_t get_offset_of_m_LegacyContacts_6() { return static_cast<int32_t>(offsetof(Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0, ___m_LegacyContacts_6)); } inline ContactPointU5BU5D_t1ACD262B1EA44CD48E2039381DE96847F203E62B* get_m_LegacyContacts_6() const { return ___m_LegacyContacts_6; } inline ContactPointU5BU5D_t1ACD262B1EA44CD48E2039381DE96847F203E62B** get_address_of_m_LegacyContacts_6() { return &___m_LegacyContacts_6; } inline void set_m_LegacyContacts_6(ContactPointU5BU5D_t1ACD262B1EA44CD48E2039381DE96847F203E62B* value) { ___m_LegacyContacts_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_LegacyContacts_6), (void*)value); } }; // Native definition for P/Invoke marshalling of UnityEngine.Collision struct Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0_marshaled_pinvoke { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___m_Impulse_0; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___m_RelativeVelocity_1; Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * ___m_Body_2; Collider_t5E81E43C2ECA0209A7C4528E84A632712D192B02 * ___m_Collider_3; int32_t ___m_ContactCount_4; ContactPoint_tC179732A8E0014F5EFF5977ED1ADF12CF14A9017 * ___m_ReusedContacts_5; ContactPoint_tC179732A8E0014F5EFF5977ED1ADF12CF14A9017 * ___m_LegacyContacts_6; }; // Native definition for COM marshalling of UnityEngine.Collision struct Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0_marshaled_com { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___m_Impulse_0; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___m_RelativeVelocity_1; Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * ___m_Body_2; Collider_t5E81E43C2ECA0209A7C4528E84A632712D192B02 * ___m_Collider_3; int32_t ___m_ContactCount_4; ContactPoint_tC179732A8E0014F5EFF5977ED1ADF12CF14A9017 * ___m_ReusedContacts_5; ContactPoint_tC179732A8E0014F5EFF5977ED1ADF12CF14A9017 * ___m_LegacyContacts_6; }; // UnityEngine.CollisionFlags struct CollisionFlags_t435530D092E80B20FFD0DA008B4F298BF224B903 { public: // System.Int32 UnityEngine.CollisionFlags::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(CollisionFlags_t435530D092E80B20FFD0DA008B4F298BF224B903, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // UnityEngine.Coroutine struct Coroutine_t899D5232EF542CB8BA70AF9ECEECA494FAA9CCB7 : public YieldInstruction_tB0B4E05316710E51ECCC1E57174C27FE6DEBBEAF { public: // System.IntPtr UnityEngine.Coroutine::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(Coroutine_t899D5232EF542CB8BA70AF9ECEECA494FAA9CCB7, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; // Native definition for P/Invoke marshalling of UnityEngine.Coroutine struct Coroutine_t899D5232EF542CB8BA70AF9ECEECA494FAA9CCB7_marshaled_pinvoke : public YieldInstruction_tB0B4E05316710E51ECCC1E57174C27FE6DEBBEAF_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.Coroutine struct Coroutine_t899D5232EF542CB8BA70AF9ECEECA494FAA9CCB7_marshaled_com : public YieldInstruction_tB0B4E05316710E51ECCC1E57174C27FE6DEBBEAF_marshaled_com { intptr_t ___m_Ptr_0; }; // System.Exception struct Exception_t : public RuntimeObject { public: // System.String System.Exception::_className String_t* ____className_1; // System.String System.Exception::_message String_t* ____message_2; // System.Collections.IDictionary System.Exception::_data RuntimeObject* ____data_3; // System.Exception System.Exception::_innerException Exception_t * ____innerException_4; // System.String System.Exception::_helpURL String_t* ____helpURL_5; // System.Object System.Exception::_stackTrace RuntimeObject * ____stackTrace_6; // System.String System.Exception::_stackTraceString String_t* ____stackTraceString_7; // System.String System.Exception::_remoteStackTraceString String_t* ____remoteStackTraceString_8; // System.Int32 System.Exception::_remoteStackIndex int32_t ____remoteStackIndex_9; // System.Object System.Exception::_dynamicMethods RuntimeObject * ____dynamicMethods_10; // System.Int32 System.Exception::_HResult int32_t ____HResult_11; // System.String System.Exception::_source String_t* ____source_12; // System.Runtime.Serialization.SafeSerializationManager System.Exception::_safeSerializationManager SafeSerializationManager_tDE44F029589A028F8A3053C5C06153FAB4AAE29F * ____safeSerializationManager_13; // System.Diagnostics.StackTrace[] System.Exception::captured_traces StackTraceU5BU5D_t4AD999C288CB6D1F38A299D12B1598D606588971* ___captured_traces_14; // System.IntPtr[] System.Exception::native_trace_ips IntPtrU5BU5D_t27FC72B0409D75AAF33EC42498E8094E95FEE9A6* ___native_trace_ips_15; public: inline static int32_t get_offset_of__className_1() { return static_cast<int32_t>(offsetof(Exception_t, ____className_1)); } inline String_t* get__className_1() const { return ____className_1; } inline String_t** get_address_of__className_1() { return &____className_1; } inline void set__className_1(String_t* value) { ____className_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____className_1), (void*)value); } inline static int32_t get_offset_of__message_2() { return static_cast<int32_t>(offsetof(Exception_t, ____message_2)); } inline String_t* get__message_2() const { return ____message_2; } inline String_t** get_address_of__message_2() { return &____message_2; } inline void set__message_2(String_t* value) { ____message_2 = value; Il2CppCodeGenWriteBarrier((void**)(&____message_2), (void*)value); } inline static int32_t get_offset_of__data_3() { return static_cast<int32_t>(offsetof(Exception_t, ____data_3)); } inline RuntimeObject* get__data_3() const { return ____data_3; } inline RuntimeObject** get_address_of__data_3() { return &____data_3; } inline void set__data_3(RuntimeObject* value) { ____data_3 = value; Il2CppCodeGenWriteBarrier((void**)(&____data_3), (void*)value); } inline static int32_t get_offset_of__innerException_4() { return static_cast<int32_t>(offsetof(Exception_t, ____innerException_4)); } inline Exception_t * get__innerException_4() const { return ____innerException_4; } inline Exception_t ** get_address_of__innerException_4() { return &____innerException_4; } inline void set__innerException_4(Exception_t * value) { ____innerException_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____innerException_4), (void*)value); } inline static int32_t get_offset_of__helpURL_5() { return static_cast<int32_t>(offsetof(Exception_t, ____helpURL_5)); } inline String_t* get__helpURL_5() const { return ____helpURL_5; } inline String_t** get_address_of__helpURL_5() { return &____helpURL_5; } inline void set__helpURL_5(String_t* value) { ____helpURL_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____helpURL_5), (void*)value); } inline static int32_t get_offset_of__stackTrace_6() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTrace_6)); } inline RuntimeObject * get__stackTrace_6() const { return ____stackTrace_6; } inline RuntimeObject ** get_address_of__stackTrace_6() { return &____stackTrace_6; } inline void set__stackTrace_6(RuntimeObject * value) { ____stackTrace_6 = value; Il2CppCodeGenWriteBarrier((void**)(&____stackTrace_6), (void*)value); } inline static int32_t get_offset_of__stackTraceString_7() { return static_cast<int32_t>(offsetof(Exception_t, ____stackTraceString_7)); } inline String_t* get__stackTraceString_7() const { return ____stackTraceString_7; } inline String_t** get_address_of__stackTraceString_7() { return &____stackTraceString_7; } inline void set__stackTraceString_7(String_t* value) { ____stackTraceString_7 = value; Il2CppCodeGenWriteBarrier((void**)(&____stackTraceString_7), (void*)value); } inline static int32_t get_offset_of__remoteStackTraceString_8() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackTraceString_8)); } inline String_t* get__remoteStackTraceString_8() const { return ____remoteStackTraceString_8; } inline String_t** get_address_of__remoteStackTraceString_8() { return &____remoteStackTraceString_8; } inline void set__remoteStackTraceString_8(String_t* value) { ____remoteStackTraceString_8 = value; Il2CppCodeGenWriteBarrier((void**)(&____remoteStackTraceString_8), (void*)value); } inline static int32_t get_offset_of__remoteStackIndex_9() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackIndex_9)); } inline int32_t get__remoteStackIndex_9() const { return ____remoteStackIndex_9; } inline int32_t* get_address_of__remoteStackIndex_9() { return &____remoteStackIndex_9; } inline void set__remoteStackIndex_9(int32_t value) { ____remoteStackIndex_9 = value; } inline static int32_t get_offset_of__dynamicMethods_10() { return static_cast<int32_t>(offsetof(Exception_t, ____dynamicMethods_10)); } inline RuntimeObject * get__dynamicMethods_10() const { return ____dynamicMethods_10; } inline RuntimeObject ** get_address_of__dynamicMethods_10() { return &____dynamicMethods_10; } inline void set__dynamicMethods_10(RuntimeObject * value) { ____dynamicMethods_10 = value; Il2CppCodeGenWriteBarrier((void**)(&____dynamicMethods_10), (void*)value); } inline static int32_t get_offset_of__HResult_11() { return static_cast<int32_t>(offsetof(Exception_t, ____HResult_11)); } inline int32_t get__HResult_11() const { return ____HResult_11; } inline int32_t* get_address_of__HResult_11() { return &____HResult_11; } inline void set__HResult_11(int32_t value) { ____HResult_11 = value; } inline static int32_t get_offset_of__source_12() { return static_cast<int32_t>(offsetof(Exception_t, ____source_12)); } inline String_t* get__source_12() const { return ____source_12; } inline String_t** get_address_of__source_12() { return &____source_12; } inline void set__source_12(String_t* value) { ____source_12 = value; Il2CppCodeGenWriteBarrier((void**)(&____source_12), (void*)value); } inline static int32_t get_offset_of__safeSerializationManager_13() { return static_cast<int32_t>(offsetof(Exception_t, ____safeSerializationManager_13)); } inline SafeSerializationManager_tDE44F029589A028F8A3053C5C06153FAB4AAE29F * get__safeSerializationManager_13() const { return ____safeSerializationManager_13; } inline SafeSerializationManager_tDE44F029589A028F8A3053C5C06153FAB4AAE29F ** get_address_of__safeSerializationManager_13() { return &____safeSerializationManager_13; } inline void set__safeSerializationManager_13(SafeSerializationManager_tDE44F029589A028F8A3053C5C06153FAB4AAE29F * value) { ____safeSerializationManager_13 = value; Il2CppCodeGenWriteBarrier((void**)(&____safeSerializationManager_13), (void*)value); } inline static int32_t get_offset_of_captured_traces_14() { return static_cast<int32_t>(offsetof(Exception_t, ___captured_traces_14)); } inline StackTraceU5BU5D_t4AD999C288CB6D1F38A299D12B1598D606588971* get_captured_traces_14() const { return ___captured_traces_14; } inline StackTraceU5BU5D_t4AD999C288CB6D1F38A299D12B1598D606588971** get_address_of_captured_traces_14() { return &___captured_traces_14; } inline void set_captured_traces_14(StackTraceU5BU5D_t4AD999C288CB6D1F38A299D12B1598D606588971* value) { ___captured_traces_14 = value; Il2CppCodeGenWriteBarrier((void**)(&___captured_traces_14), (void*)value); } inline static int32_t get_offset_of_native_trace_ips_15() { return static_cast<int32_t>(offsetof(Exception_t, ___native_trace_ips_15)); } inline IntPtrU5BU5D_t27FC72B0409D75AAF33EC42498E8094E95FEE9A6* get_native_trace_ips_15() const { return ___native_trace_ips_15; } inline IntPtrU5BU5D_t27FC72B0409D75AAF33EC42498E8094E95FEE9A6** get_address_of_native_trace_ips_15() { return &___native_trace_ips_15; } inline void set_native_trace_ips_15(IntPtrU5BU5D_t27FC72B0409D75AAF33EC42498E8094E95FEE9A6* value) { ___native_trace_ips_15 = value; Il2CppCodeGenWriteBarrier((void**)(&___native_trace_ips_15), (void*)value); } }; struct Exception_t_StaticFields { public: // System.Object System.Exception::s_EDILock RuntimeObject * ___s_EDILock_0; public: inline static int32_t get_offset_of_s_EDILock_0() { return static_cast<int32_t>(offsetof(Exception_t_StaticFields, ___s_EDILock_0)); } inline RuntimeObject * get_s_EDILock_0() const { return ___s_EDILock_0; } inline RuntimeObject ** get_address_of_s_EDILock_0() { return &___s_EDILock_0; } inline void set_s_EDILock_0(RuntimeObject * value) { ___s_EDILock_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_EDILock_0), (void*)value); } }; // Native definition for P/Invoke marshalling of System.Exception struct Exception_t_marshaled_pinvoke { char* ____className_1; char* ____message_2; RuntimeObject* ____data_3; Exception_t_marshaled_pinvoke* ____innerException_4; char* ____helpURL_5; Il2CppIUnknown* ____stackTrace_6; char* ____stackTraceString_7; char* ____remoteStackTraceString_8; int32_t ____remoteStackIndex_9; Il2CppIUnknown* ____dynamicMethods_10; int32_t ____HResult_11; char* ____source_12; SafeSerializationManager_tDE44F029589A028F8A3053C5C06153FAB4AAE29F * ____safeSerializationManager_13; StackTraceU5BU5D_t4AD999C288CB6D1F38A299D12B1598D606588971* ___captured_traces_14; Il2CppSafeArray/*NONE*/* ___native_trace_ips_15; }; // Native definition for COM marshalling of System.Exception struct Exception_t_marshaled_com { Il2CppChar* ____className_1; Il2CppChar* ____message_2; RuntimeObject* ____data_3; Exception_t_marshaled_com* ____innerException_4; Il2CppChar* ____helpURL_5; Il2CppIUnknown* ____stackTrace_6; Il2CppChar* ____stackTraceString_7; Il2CppChar* ____remoteStackTraceString_8; int32_t ____remoteStackIndex_9; Il2CppIUnknown* ____dynamicMethods_10; int32_t ____HResult_11; Il2CppChar* ____source_12; SafeSerializationManager_tDE44F029589A028F8A3053C5C06153FAB4AAE29F * ____safeSerializationManager_13; StackTraceU5BU5D_t4AD999C288CB6D1F38A299D12B1598D606588971* ___captured_traces_14; Il2CppSafeArray/*NONE*/* ___native_trace_ips_15; }; // UnityEngine.KeyCode struct KeyCode_t1D303F7D061BF4429872E9F109ADDBCB431671F4 { public: // System.Int32 UnityEngine.KeyCode::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(KeyCode_t1D303F7D061BF4429872E9F109ADDBCB431671F4, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // UnityEngine.Object struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr intptr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A, ___m_CachedPtr_0)); } inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(intptr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_marshaled_com { intptr_t ___m_CachedPtr_0; }; // UnityEngine.RigidbodyConstraints struct RigidbodyConstraints_tB1AC534C460083518E5C8664CE62334E3B5A0F97 { public: // System.Int32 UnityEngine.RigidbodyConstraints::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(RigidbodyConstraints_tB1AC534C460083518E5C8664CE62334E3B5A0F97, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // UnityEngine.Space struct Space_t568D704D2B0AAC3E5894DDFF13DB2E02E2CD539E { public: // System.Int32 UnityEngine.Space::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(Space_t568D704D2B0AAC3E5894DDFF13DB2E02E2CD539E, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; // UnityEngine.Component struct Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 : public Object_tF2F3778131EFF286AF62B7B013A170F95A91571A { public: public: }; // UnityEngine.GameObject struct GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 : public Object_tF2F3778131EFF286AF62B7B013A170F95A91571A { public: public: }; // System.SystemException struct SystemException_tC551B4D6EE3772B5F32C71EE8C719F4B43ECCC62 : public Exception_t { public: public: }; // UnityEngine.Behaviour struct Behaviour_t1A3DDDCF73B4627928FBFE02ED52B7251777DBD9 : public Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 { public: public: }; // UnityEngine.Collider struct Collider_t5E81E43C2ECA0209A7C4528E84A632712D192B02 : public Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 { public: public: }; // System.NotSupportedException struct NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339 : public SystemException_tC551B4D6EE3772B5F32C71EE8C719F4B43ECCC62 { public: public: }; // UnityEngine.Rigidbody struct Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A : public Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 { public: public: }; // UnityEngine.Transform struct Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 : public Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 { public: public: }; // UnityEngine.Camera struct Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C : public Behaviour_t1A3DDDCF73B4627928FBFE02ED52B7251777DBD9 { public: public: }; struct Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_StaticFields { public: // UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPreCull CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * ___onPreCull_4; // UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPreRender CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * ___onPreRender_5; // UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPostRender CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * ___onPostRender_6; public: inline static int32_t get_offset_of_onPreCull_4() { return static_cast<int32_t>(offsetof(Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_StaticFields, ___onPreCull_4)); } inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * get_onPreCull_4() const { return ___onPreCull_4; } inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D ** get_address_of_onPreCull_4() { return &___onPreCull_4; } inline void set_onPreCull_4(CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * value) { ___onPreCull_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___onPreCull_4), (void*)value); } inline static int32_t get_offset_of_onPreRender_5() { return static_cast<int32_t>(offsetof(Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_StaticFields, ___onPreRender_5)); } inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * get_onPreRender_5() const { return ___onPreRender_5; } inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D ** get_address_of_onPreRender_5() { return &___onPreRender_5; } inline void set_onPreRender_5(CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * value) { ___onPreRender_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___onPreRender_5), (void*)value); } inline static int32_t get_offset_of_onPostRender_6() { return static_cast<int32_t>(offsetof(Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_StaticFields, ___onPostRender_6)); } inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * get_onPostRender_6() const { return ___onPostRender_6; } inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D ** get_address_of_onPostRender_6() { return &___onPostRender_6; } inline void set_onPostRender_6(CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * value) { ___onPostRender_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___onPostRender_6), (void*)value); } }; // UnityEngine.CharacterController struct CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E : public Collider_t5E81E43C2ECA0209A7C4528E84A632712D192B02 { public: public: }; // UnityEngine.MonoBehaviour struct MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A : public Behaviour_t1A3DDDCF73B4627928FBFE02ED52B7251777DBD9 { public: public: }; // UnityEngine.Video.VideoPlayer struct VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 : public Behaviour_t1A3DDDCF73B4627928FBFE02ED52B7251777DBD9 { public: // UnityEngine.Video.VideoPlayer/EventHandler UnityEngine.Video.VideoPlayer::prepareCompleted EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * ___prepareCompleted_4; // UnityEngine.Video.VideoPlayer/EventHandler UnityEngine.Video.VideoPlayer::loopPointReached EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * ___loopPointReached_5; // UnityEngine.Video.VideoPlayer/EventHandler UnityEngine.Video.VideoPlayer::started EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * ___started_6; // UnityEngine.Video.VideoPlayer/EventHandler UnityEngine.Video.VideoPlayer::frameDropped EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * ___frameDropped_7; // UnityEngine.Video.VideoPlayer/ErrorEventHandler UnityEngine.Video.VideoPlayer::errorReceived ErrorEventHandler_tD47781EBB7CF0CC4C111496024BD59B1D1A6A1F2 * ___errorReceived_8; // UnityEngine.Video.VideoPlayer/EventHandler UnityEngine.Video.VideoPlayer::seekCompleted EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * ___seekCompleted_9; // UnityEngine.Video.VideoPlayer/TimeEventHandler UnityEngine.Video.VideoPlayer::clockResyncOccurred TimeEventHandler_t7CA131EB85E0FFCBE8660E030698BD83D3994DD8 * ___clockResyncOccurred_10; // UnityEngine.Video.VideoPlayer/FrameReadyEventHandler UnityEngine.Video.VideoPlayer::frameReady FrameReadyEventHandler_t9529BD5A34E9C8BE7D8A39D46A6C4ABC673374EC * ___frameReady_11; public: inline static int32_t get_offset_of_prepareCompleted_4() { return static_cast<int32_t>(offsetof(VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86, ___prepareCompleted_4)); } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * get_prepareCompleted_4() const { return ___prepareCompleted_4; } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD ** get_address_of_prepareCompleted_4() { return &___prepareCompleted_4; } inline void set_prepareCompleted_4(EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * value) { ___prepareCompleted_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___prepareCompleted_4), (void*)value); } inline static int32_t get_offset_of_loopPointReached_5() { return static_cast<int32_t>(offsetof(VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86, ___loopPointReached_5)); } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * get_loopPointReached_5() const { return ___loopPointReached_5; } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD ** get_address_of_loopPointReached_5() { return &___loopPointReached_5; } inline void set_loopPointReached_5(EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * value) { ___loopPointReached_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___loopPointReached_5), (void*)value); } inline static int32_t get_offset_of_started_6() { return static_cast<int32_t>(offsetof(VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86, ___started_6)); } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * get_started_6() const { return ___started_6; } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD ** get_address_of_started_6() { return &___started_6; } inline void set_started_6(EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * value) { ___started_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___started_6), (void*)value); } inline static int32_t get_offset_of_frameDropped_7() { return static_cast<int32_t>(offsetof(VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86, ___frameDropped_7)); } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * get_frameDropped_7() const { return ___frameDropped_7; } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD ** get_address_of_frameDropped_7() { return &___frameDropped_7; } inline void set_frameDropped_7(EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * value) { ___frameDropped_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___frameDropped_7), (void*)value); } inline static int32_t get_offset_of_errorReceived_8() { return static_cast<int32_t>(offsetof(VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86, ___errorReceived_8)); } inline ErrorEventHandler_tD47781EBB7CF0CC4C111496024BD59B1D1A6A1F2 * get_errorReceived_8() const { return ___errorReceived_8; } inline ErrorEventHandler_tD47781EBB7CF0CC4C111496024BD59B1D1A6A1F2 ** get_address_of_errorReceived_8() { return &___errorReceived_8; } inline void set_errorReceived_8(ErrorEventHandler_tD47781EBB7CF0CC4C111496024BD59B1D1A6A1F2 * value) { ___errorReceived_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___errorReceived_8), (void*)value); } inline static int32_t get_offset_of_seekCompleted_9() { return static_cast<int32_t>(offsetof(VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86, ___seekCompleted_9)); } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * get_seekCompleted_9() const { return ___seekCompleted_9; } inline EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD ** get_address_of_seekCompleted_9() { return &___seekCompleted_9; } inline void set_seekCompleted_9(EventHandler_t99288A74FAB288C0033E28A5CD3DABE77B109BFD * value) { ___seekCompleted_9 = value; Il2CppCodeGenWriteBarrier((void**)(&___seekCompleted_9), (void*)value); } inline static int32_t get_offset_of_clockResyncOccurred_10() { return static_cast<int32_t>(offsetof(VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86, ___clockResyncOccurred_10)); } inline TimeEventHandler_t7CA131EB85E0FFCBE8660E030698BD83D3994DD8 * get_clockResyncOccurred_10() const { return ___clockResyncOccurred_10; } inline TimeEventHandler_t7CA131EB85E0FFCBE8660E030698BD83D3994DD8 ** get_address_of_clockResyncOccurred_10() { return &___clockResyncOccurred_10; } inline void set_clockResyncOccurred_10(TimeEventHandler_t7CA131EB85E0FFCBE8660E030698BD83D3994DD8 * value) { ___clockResyncOccurred_10 = value; Il2CppCodeGenWriteBarrier((void**)(&___clockResyncOccurred_10), (void*)value); } inline static int32_t get_offset_of_frameReady_11() { return static_cast<int32_t>(offsetof(VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86, ___frameReady_11)); } inline FrameReadyEventHandler_t9529BD5A34E9C8BE7D8A39D46A6C4ABC673374EC * get_frameReady_11() const { return ___frameReady_11; } inline FrameReadyEventHandler_t9529BD5A34E9C8BE7D8A39D46A6C4ABC673374EC ** get_address_of_frameReady_11() { return &___frameReady_11; } inline void set_frameReady_11(FrameReadyEventHandler_t9529BD5A34E9C8BE7D8A39D46A6C4ABC673374EC * value) { ___frameReady_11 = value; Il2CppCodeGenWriteBarrier((void**)(&___frameReady_11), (void*)value); } }; // Door struct Door_t7B1F8C89F7CCF5EBECA830A8D7799005C9EE44F6 : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // System.Single Door::movingSpeed float ___movingSpeed_4; public: inline static int32_t get_offset_of_movingSpeed_4() { return static_cast<int32_t>(offsetof(Door_t7B1F8C89F7CCF5EBECA830A8D7799005C9EE44F6, ___movingSpeed_4)); } inline float get_movingSpeed_4() const { return ___movingSpeed_4; } inline float* get_address_of_movingSpeed_4() { return &___movingSpeed_4; } inline void set_movingSpeed_4(float value) { ___movingSpeed_4 = value; } }; // DoorGenerator struct DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // UnityEngine.GameObject DoorGenerator::door GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * ___door_4; // System.Single DoorGenerator::waitSecondsMin float ___waitSecondsMin_5; // System.Single DoorGenerator::waitSecondsMax float ___waitSecondsMax_6; public: inline static int32_t get_offset_of_door_4() { return static_cast<int32_t>(offsetof(DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136, ___door_4)); } inline GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * get_door_4() const { return ___door_4; } inline GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 ** get_address_of_door_4() { return &___door_4; } inline void set_door_4(GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * value) { ___door_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___door_4), (void*)value); } inline static int32_t get_offset_of_waitSecondsMin_5() { return static_cast<int32_t>(offsetof(DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136, ___waitSecondsMin_5)); } inline float get_waitSecondsMin_5() const { return ___waitSecondsMin_5; } inline float* get_address_of_waitSecondsMin_5() { return &___waitSecondsMin_5; } inline void set_waitSecondsMin_5(float value) { ___waitSecondsMin_5 = value; } inline static int32_t get_offset_of_waitSecondsMax_6() { return static_cast<int32_t>(offsetof(DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136, ___waitSecondsMax_6)); } inline float get_waitSecondsMax_6() const { return ___waitSecondsMax_6; } inline float* get_address_of_waitSecondsMax_6() { return &___waitSecondsMax_6; } inline void set_waitSecondsMax_6(float value) { ___waitSecondsMax_6 = value; } }; // EnvironmentGenerator struct EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // UnityEngine.Camera EnvironmentGenerator::mainCamera Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * ___mainCamera_4; // UnityEngine.Transform EnvironmentGenerator::startPoint Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * ___startPoint_5; // EnvironmentTiling EnvironmentGenerator::tilePrefab EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * ___tilePrefab_6; // System.Single EnvironmentGenerator::movingSpeed float ___movingSpeed_7; // System.Int32 EnvironmentGenerator::tilesToPreSpawn int32_t ___tilesToPreSpawn_8; // System.Int32 EnvironmentGenerator::score int32_t ___score_9; // System.Collections.Generic.List`1<EnvironmentTiling> EnvironmentGenerator::spawnedTiles List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * ___spawnedTiles_10; public: inline static int32_t get_offset_of_mainCamera_4() { return static_cast<int32_t>(offsetof(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D, ___mainCamera_4)); } inline Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * get_mainCamera_4() const { return ___mainCamera_4; } inline Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C ** get_address_of_mainCamera_4() { return &___mainCamera_4; } inline void set_mainCamera_4(Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * value) { ___mainCamera_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___mainCamera_4), (void*)value); } inline static int32_t get_offset_of_startPoint_5() { return static_cast<int32_t>(offsetof(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D, ___startPoint_5)); } inline Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * get_startPoint_5() const { return ___startPoint_5; } inline Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 ** get_address_of_startPoint_5() { return &___startPoint_5; } inline void set_startPoint_5(Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * value) { ___startPoint_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___startPoint_5), (void*)value); } inline static int32_t get_offset_of_tilePrefab_6() { return static_cast<int32_t>(offsetof(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D, ___tilePrefab_6)); } inline EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * get_tilePrefab_6() const { return ___tilePrefab_6; } inline EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE ** get_address_of_tilePrefab_6() { return &___tilePrefab_6; } inline void set_tilePrefab_6(EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * value) { ___tilePrefab_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___tilePrefab_6), (void*)value); } inline static int32_t get_offset_of_movingSpeed_7() { return static_cast<int32_t>(offsetof(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D, ___movingSpeed_7)); } inline float get_movingSpeed_7() const { return ___movingSpeed_7; } inline float* get_address_of_movingSpeed_7() { return &___movingSpeed_7; } inline void set_movingSpeed_7(float value) { ___movingSpeed_7 = value; } inline static int32_t get_offset_of_tilesToPreSpawn_8() { return static_cast<int32_t>(offsetof(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D, ___tilesToPreSpawn_8)); } inline int32_t get_tilesToPreSpawn_8() const { return ___tilesToPreSpawn_8; } inline int32_t* get_address_of_tilesToPreSpawn_8() { return &___tilesToPreSpawn_8; } inline void set_tilesToPreSpawn_8(int32_t value) { ___tilesToPreSpawn_8 = value; } inline static int32_t get_offset_of_score_9() { return static_cast<int32_t>(offsetof(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D, ___score_9)); } inline int32_t get_score_9() const { return ___score_9; } inline int32_t* get_address_of_score_9() { return &___score_9; } inline void set_score_9(int32_t value) { ___score_9 = value; } inline static int32_t get_offset_of_spawnedTiles_10() { return static_cast<int32_t>(offsetof(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D, ___spawnedTiles_10)); } inline List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * get_spawnedTiles_10() const { return ___spawnedTiles_10; } inline List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB ** get_address_of_spawnedTiles_10() { return &___spawnedTiles_10; } inline void set_spawnedTiles_10(List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * value) { ___spawnedTiles_10 = value; Il2CppCodeGenWriteBarrier((void**)(&___spawnedTiles_10), (void*)value); } }; struct EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D_StaticFields { public: // EnvironmentGenerator EnvironmentGenerator::instance EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D * ___instance_11; public: inline static int32_t get_offset_of_instance_11() { return static_cast<int32_t>(offsetof(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D_StaticFields, ___instance_11)); } inline EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D * get_instance_11() const { return ___instance_11; } inline EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D ** get_address_of_instance_11() { return &___instance_11; } inline void set_instance_11(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D * value) { ___instance_11 = value; Il2CppCodeGenWriteBarrier((void**)(&___instance_11), (void*)value); } }; // EnvironmentTiling struct EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // UnityEngine.Transform EnvironmentTiling::startPoint Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * ___startPoint_4; // UnityEngine.Transform EnvironmentTiling::endPoint Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * ___endPoint_5; // UnityEngine.GameObject[] EnvironmentTiling::corridor GameObjectU5BU5D_tA88FC1A1FC9D4D73D0B3984D4B0ECE88F4C47642* ___corridor_6; public: inline static int32_t get_offset_of_startPoint_4() { return static_cast<int32_t>(offsetof(EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE, ___startPoint_4)); } inline Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * get_startPoint_4() const { return ___startPoint_4; } inline Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 ** get_address_of_startPoint_4() { return &___startPoint_4; } inline void set_startPoint_4(Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * value) { ___startPoint_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___startPoint_4), (void*)value); } inline static int32_t get_offset_of_endPoint_5() { return static_cast<int32_t>(offsetof(EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE, ___endPoint_5)); } inline Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * get_endPoint_5() const { return ___endPoint_5; } inline Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 ** get_address_of_endPoint_5() { return &___endPoint_5; } inline void set_endPoint_5(Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * value) { ___endPoint_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___endPoint_5), (void*)value); } inline static int32_t get_offset_of_corridor_6() { return static_cast<int32_t>(offsetof(EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE, ___corridor_6)); } inline GameObjectU5BU5D_tA88FC1A1FC9D4D73D0B3984D4B0ECE88F4C47642* get_corridor_6() const { return ___corridor_6; } inline GameObjectU5BU5D_tA88FC1A1FC9D4D73D0B3984D4B0ECE88F4C47642** get_address_of_corridor_6() { return &___corridor_6; } inline void set_corridor_6(GameObjectU5BU5D_tA88FC1A1FC9D4D73D0B3984D4B0ECE88F4C47642* value) { ___corridor_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___corridor_6), (void*)value); } }; // GameOverScreen struct GameOverScreen_t66B7C93D73D16C603457FEA3A5424F7DDB6B68A7 : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // UnityEngine.UI.Text GameOverScreen::scoreText Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1 * ___scoreText_4; public: inline static int32_t get_offset_of_scoreText_4() { return static_cast<int32_t>(offsetof(GameOverScreen_t66B7C93D73D16C603457FEA3A5424F7DDB6B68A7, ___scoreText_4)); } inline Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1 * get_scoreText_4() const { return ___scoreText_4; } inline Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1 ** get_address_of_scoreText_4() { return &___scoreText_4; } inline void set_scoreText_4(Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1 * value) { ___scoreText_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___scoreText_4), (void*)value); } }; // MainMenu struct MainMenu_tEB11F5A993C42E93B585FBB65C9E92EC91C5707C : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: public: }; // ObstacleMove struct ObstacleMove_tCA8BCDF4E1470FF52591F02A0E20D6091EB614DC : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // System.Single ObstacleMove::movingSpeed float ___movingSpeed_4; public: inline static int32_t get_offset_of_movingSpeed_4() { return static_cast<int32_t>(offsetof(ObstacleMove_tCA8BCDF4E1470FF52591F02A0E20D6091EB614DC, ___movingSpeed_4)); } inline float get_movingSpeed_4() const { return ___movingSpeed_4; } inline float* get_address_of_movingSpeed_4() { return &___movingSpeed_4; } inline void set_movingSpeed_4(float value) { ___movingSpeed_4 = value; } }; // ObstacleSpawner struct ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // UnityEngine.GameObject ObstacleSpawner::obstacle GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * ___obstacle_4; // System.Single ObstacleSpawner::waitSecondsMin float ___waitSecondsMin_5; // System.Single ObstacleSpawner::waitSecondsMax float ___waitSecondsMax_6; public: inline static int32_t get_offset_of_obstacle_4() { return static_cast<int32_t>(offsetof(ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC, ___obstacle_4)); } inline GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * get_obstacle_4() const { return ___obstacle_4; } inline GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 ** get_address_of_obstacle_4() { return &___obstacle_4; } inline void set_obstacle_4(GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * value) { ___obstacle_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___obstacle_4), (void*)value); } inline static int32_t get_offset_of_waitSecondsMin_5() { return static_cast<int32_t>(offsetof(ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC, ___waitSecondsMin_5)); } inline float get_waitSecondsMin_5() const { return ___waitSecondsMin_5; } inline float* get_address_of_waitSecondsMin_5() { return &___waitSecondsMin_5; } inline void set_waitSecondsMin_5(float value) { ___waitSecondsMin_5 = value; } inline static int32_t get_offset_of_waitSecondsMax_6() { return static_cast<int32_t>(offsetof(ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC, ___waitSecondsMax_6)); } inline float get_waitSecondsMax_6() const { return ___waitSecondsMax_6; } inline float* get_address_of_waitSecondsMax_6() { return &___waitSecondsMax_6; } inline void set_waitSecondsMax_6(float value) { ___waitSecondsMax_6 = value; } }; // PlayVideo struct PlayVideo_tD3F8CE49495C7017FEF089C05BC6D56CA20A3E98 : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // UnityEngine.Video.VideoPlayer PlayVideo::videoPlayer VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * ___videoPlayer_4; // System.String PlayVideo::nomVideo String_t* ___nomVideo_5; public: inline static int32_t get_offset_of_videoPlayer_4() { return static_cast<int32_t>(offsetof(PlayVideo_tD3F8CE49495C7017FEF089C05BC6D56CA20A3E98, ___videoPlayer_4)); } inline VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * get_videoPlayer_4() const { return ___videoPlayer_4; } inline VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 ** get_address_of_videoPlayer_4() { return &___videoPlayer_4; } inline void set_videoPlayer_4(VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * value) { ___videoPlayer_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___videoPlayer_4), (void*)value); } inline static int32_t get_offset_of_nomVideo_5() { return static_cast<int32_t>(offsetof(PlayVideo_tD3F8CE49495C7017FEF089C05BC6D56CA20A3E98, ___nomVideo_5)); } inline String_t* get_nomVideo_5() const { return ___nomVideo_5; } inline String_t** get_address_of_nomVideo_5() { return &___nomVideo_5; } inline void set_nomVideo_5(String_t* value) { ___nomVideo_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___nomVideo_5), (void*)value); } }; // Player struct Player_t5689617909B48F7640EA0892D85C92C13CC22C6F : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // System.Single Player::gravity float ___gravity_4; // System.Single Player::jumpHeight float ___jumpHeight_5; // System.Single Player::movementSpeed float ___movementSpeed_6; // UnityEngine.Rigidbody Player::rb Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * ___rb_7; // System.Boolean Player::grounded bool ___grounded_8; // UnityEngine.Vector3 Player::defaultScale Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___defaultScale_9; public: inline static int32_t get_offset_of_gravity_4() { return static_cast<int32_t>(offsetof(Player_t5689617909B48F7640EA0892D85C92C13CC22C6F, ___gravity_4)); } inline float get_gravity_4() const { return ___gravity_4; } inline float* get_address_of_gravity_4() { return &___gravity_4; } inline void set_gravity_4(float value) { ___gravity_4 = value; } inline static int32_t get_offset_of_jumpHeight_5() { return static_cast<int32_t>(offsetof(Player_t5689617909B48F7640EA0892D85C92C13CC22C6F, ___jumpHeight_5)); } inline float get_jumpHeight_5() const { return ___jumpHeight_5; } inline float* get_address_of_jumpHeight_5() { return &___jumpHeight_5; } inline void set_jumpHeight_5(float value) { ___jumpHeight_5 = value; } inline static int32_t get_offset_of_movementSpeed_6() { return static_cast<int32_t>(offsetof(Player_t5689617909B48F7640EA0892D85C92C13CC22C6F, ___movementSpeed_6)); } inline float get_movementSpeed_6() const { return ___movementSpeed_6; } inline float* get_address_of_movementSpeed_6() { return &___movementSpeed_6; } inline void set_movementSpeed_6(float value) { ___movementSpeed_6 = value; } inline static int32_t get_offset_of_rb_7() { return static_cast<int32_t>(offsetof(Player_t5689617909B48F7640EA0892D85C92C13CC22C6F, ___rb_7)); } inline Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * get_rb_7() const { return ___rb_7; } inline Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A ** get_address_of_rb_7() { return &___rb_7; } inline void set_rb_7(Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * value) { ___rb_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___rb_7), (void*)value); } inline static int32_t get_offset_of_grounded_8() { return static_cast<int32_t>(offsetof(Player_t5689617909B48F7640EA0892D85C92C13CC22C6F, ___grounded_8)); } inline bool get_grounded_8() const { return ___grounded_8; } inline bool* get_address_of_grounded_8() { return &___grounded_8; } inline void set_grounded_8(bool value) { ___grounded_8 = value; } inline static int32_t get_offset_of_defaultScale_9() { return static_cast<int32_t>(offsetof(Player_t5689617909B48F7640EA0892D85C92C13CC22C6F, ___defaultScale_9)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_defaultScale_9() const { return ___defaultScale_9; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_defaultScale_9() { return &___defaultScale_9; } inline void set_defaultScale_9(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___defaultScale_9 = value; } }; // PlayerMotor struct PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52 : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: // UnityEngine.CharacterController PlayerMotor::controller CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * ___controller_4; // UnityEngine.Vector3 PlayerMotor::moveVector Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___moveVector_5; // System.Single PlayerMotor::speed float ___speed_6; // System.Single PlayerMotor::verticalVelocity float ___verticalVelocity_7; // System.Single PlayerMotor::gravity float ___gravity_8; public: inline static int32_t get_offset_of_controller_4() { return static_cast<int32_t>(offsetof(PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52, ___controller_4)); } inline CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * get_controller_4() const { return ___controller_4; } inline CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E ** get_address_of_controller_4() { return &___controller_4; } inline void set_controller_4(CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * value) { ___controller_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___controller_4), (void*)value); } inline static int32_t get_offset_of_moveVector_5() { return static_cast<int32_t>(offsetof(PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52, ___moveVector_5)); } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_moveVector_5() const { return ___moveVector_5; } inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_moveVector_5() { return &___moveVector_5; } inline void set_moveVector_5(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value) { ___moveVector_5 = value; } inline static int32_t get_offset_of_speed_6() { return static_cast<int32_t>(offsetof(PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52, ___speed_6)); } inline float get_speed_6() const { return ___speed_6; } inline float* get_address_of_speed_6() { return &___speed_6; } inline void set_speed_6(float value) { ___speed_6 = value; } inline static int32_t get_offset_of_verticalVelocity_7() { return static_cast<int32_t>(offsetof(PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52, ___verticalVelocity_7)); } inline float get_verticalVelocity_7() const { return ___verticalVelocity_7; } inline float* get_address_of_verticalVelocity_7() { return &___verticalVelocity_7; } inline void set_verticalVelocity_7(float value) { ___verticalVelocity_7 = value; } inline static int32_t get_offset_of_gravity_8() { return static_cast<int32_t>(offsetof(PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52, ___gravity_8)); } inline float get_gravity_8() const { return ___gravity_8; } inline float* get_address_of_gravity_8() { return &___gravity_8; } inline void set_gravity_8(float value) { ___gravity_8 = value; } }; // UnityEngine.EventSystems.UIBehaviour struct UIBehaviour_tD1C6E2D542222546D68510ECE74036EFBC3C3B0E : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A { public: public: }; // UnityEngine.UI.Graphic struct Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24 : public UIBehaviour_tD1C6E2D542222546D68510ECE74036EFBC3C3B0E { public: // UnityEngine.Material UnityEngine.UI.Graphic::m_Material Material_t8927C00353A72755313F046D0CE85178AE8218EE * ___m_Material_6; // UnityEngine.Color UnityEngine.UI.Graphic::m_Color Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659 ___m_Color_7; // System.Boolean UnityEngine.UI.Graphic::m_SkipLayoutUpdate bool ___m_SkipLayoutUpdate_8; // System.Boolean UnityEngine.UI.Graphic::m_SkipMaterialUpdate bool ___m_SkipMaterialUpdate_9; // System.Boolean UnityEngine.UI.Graphic::m_RaycastTarget bool ___m_RaycastTarget_10; // UnityEngine.Vector4 UnityEngine.UI.Graphic::m_RaycastPadding Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 ___m_RaycastPadding_11; // UnityEngine.RectTransform UnityEngine.UI.Graphic::m_RectTransform RectTransform_t8A6A306FB29A6C8C22010CF9040E319753571072 * ___m_RectTransform_12; // UnityEngine.CanvasRenderer UnityEngine.UI.Graphic::m_CanvasRenderer CanvasRenderer_tCF8ABE659F7C3A6ED0D99A988D0BDFB651310F0E * ___m_CanvasRenderer_13; // UnityEngine.Canvas UnityEngine.UI.Graphic::m_Canvas Canvas_t2B7E56B7BDC287962E092755372E214ACB6393EA * ___m_Canvas_14; // System.Boolean UnityEngine.UI.Graphic::m_VertsDirty bool ___m_VertsDirty_15; // System.Boolean UnityEngine.UI.Graphic::m_MaterialDirty bool ___m_MaterialDirty_16; // UnityEngine.Events.UnityAction UnityEngine.UI.Graphic::m_OnDirtyLayoutCallback UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 * ___m_OnDirtyLayoutCallback_17; // UnityEngine.Events.UnityAction UnityEngine.UI.Graphic::m_OnDirtyVertsCallback UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 * ___m_OnDirtyVertsCallback_18; // UnityEngine.Events.UnityAction UnityEngine.UI.Graphic::m_OnDirtyMaterialCallback UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 * ___m_OnDirtyMaterialCallback_19; // UnityEngine.Mesh UnityEngine.UI.Graphic::m_CachedMesh Mesh_t2F5992DBA650D5862B43D3823ACD997132A57DA6 * ___m_CachedMesh_22; // UnityEngine.Vector2[] UnityEngine.UI.Graphic::m_CachedUvs Vector2U5BU5D_tE0F58A2D6D8592B5EC37D9CDEF09103A02E5D7FA* ___m_CachedUvs_23; // UnityEngine.UI.CoroutineTween.TweenRunner`1<UnityEngine.UI.CoroutineTween.ColorTween> UnityEngine.UI.Graphic::m_ColorTweenRunner TweenRunner_1_tD84B9953874682FCC36990AF2C54D748293908F3 * ___m_ColorTweenRunner_24; // System.Boolean UnityEngine.UI.Graphic::<useLegacyMeshGeneration>k__BackingField bool ___U3CuseLegacyMeshGenerationU3Ek__BackingField_25; public: inline static int32_t get_offset_of_m_Material_6() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_Material_6)); } inline Material_t8927C00353A72755313F046D0CE85178AE8218EE * get_m_Material_6() const { return ___m_Material_6; } inline Material_t8927C00353A72755313F046D0CE85178AE8218EE ** get_address_of_m_Material_6() { return &___m_Material_6; } inline void set_m_Material_6(Material_t8927C00353A72755313F046D0CE85178AE8218EE * value) { ___m_Material_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Material_6), (void*)value); } inline static int32_t get_offset_of_m_Color_7() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_Color_7)); } inline Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659 get_m_Color_7() const { return ___m_Color_7; } inline Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659 * get_address_of_m_Color_7() { return &___m_Color_7; } inline void set_m_Color_7(Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659 value) { ___m_Color_7 = value; } inline static int32_t get_offset_of_m_SkipLayoutUpdate_8() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_SkipLayoutUpdate_8)); } inline bool get_m_SkipLayoutUpdate_8() const { return ___m_SkipLayoutUpdate_8; } inline bool* get_address_of_m_SkipLayoutUpdate_8() { return &___m_SkipLayoutUpdate_8; } inline void set_m_SkipLayoutUpdate_8(bool value) { ___m_SkipLayoutUpdate_8 = value; } inline static int32_t get_offset_of_m_SkipMaterialUpdate_9() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_SkipMaterialUpdate_9)); } inline bool get_m_SkipMaterialUpdate_9() const { return ___m_SkipMaterialUpdate_9; } inline bool* get_address_of_m_SkipMaterialUpdate_9() { return &___m_SkipMaterialUpdate_9; } inline void set_m_SkipMaterialUpdate_9(bool value) { ___m_SkipMaterialUpdate_9 = value; } inline static int32_t get_offset_of_m_RaycastTarget_10() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_RaycastTarget_10)); } inline bool get_m_RaycastTarget_10() const { return ___m_RaycastTarget_10; } inline bool* get_address_of_m_RaycastTarget_10() { return &___m_RaycastTarget_10; } inline void set_m_RaycastTarget_10(bool value) { ___m_RaycastTarget_10 = value; } inline static int32_t get_offset_of_m_RaycastPadding_11() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_RaycastPadding_11)); } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 get_m_RaycastPadding_11() const { return ___m_RaycastPadding_11; } inline Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 * get_address_of_m_RaycastPadding_11() { return &___m_RaycastPadding_11; } inline void set_m_RaycastPadding_11(Vector4_tA56A37FC5661BCC89C3DDC24BE12BA5BCB6A02C7 value) { ___m_RaycastPadding_11 = value; } inline static int32_t get_offset_of_m_RectTransform_12() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_RectTransform_12)); } inline RectTransform_t8A6A306FB29A6C8C22010CF9040E319753571072 * get_m_RectTransform_12() const { return ___m_RectTransform_12; } inline RectTransform_t8A6A306FB29A6C8C22010CF9040E319753571072 ** get_address_of_m_RectTransform_12() { return &___m_RectTransform_12; } inline void set_m_RectTransform_12(RectTransform_t8A6A306FB29A6C8C22010CF9040E319753571072 * value) { ___m_RectTransform_12 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_RectTransform_12), (void*)value); } inline static int32_t get_offset_of_m_CanvasRenderer_13() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_CanvasRenderer_13)); } inline CanvasRenderer_tCF8ABE659F7C3A6ED0D99A988D0BDFB651310F0E * get_m_CanvasRenderer_13() const { return ___m_CanvasRenderer_13; } inline CanvasRenderer_tCF8ABE659F7C3A6ED0D99A988D0BDFB651310F0E ** get_address_of_m_CanvasRenderer_13() { return &___m_CanvasRenderer_13; } inline void set_m_CanvasRenderer_13(CanvasRenderer_tCF8ABE659F7C3A6ED0D99A988D0BDFB651310F0E * value) { ___m_CanvasRenderer_13 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_CanvasRenderer_13), (void*)value); } inline static int32_t get_offset_of_m_Canvas_14() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_Canvas_14)); } inline Canvas_t2B7E56B7BDC287962E092755372E214ACB6393EA * get_m_Canvas_14() const { return ___m_Canvas_14; } inline Canvas_t2B7E56B7BDC287962E092755372E214ACB6393EA ** get_address_of_m_Canvas_14() { return &___m_Canvas_14; } inline void set_m_Canvas_14(Canvas_t2B7E56B7BDC287962E092755372E214ACB6393EA * value) { ___m_Canvas_14 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Canvas_14), (void*)value); } inline static int32_t get_offset_of_m_VertsDirty_15() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_VertsDirty_15)); } inline bool get_m_VertsDirty_15() const { return ___m_VertsDirty_15; } inline bool* get_address_of_m_VertsDirty_15() { return &___m_VertsDirty_15; } inline void set_m_VertsDirty_15(bool value) { ___m_VertsDirty_15 = value; } inline static int32_t get_offset_of_m_MaterialDirty_16() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_MaterialDirty_16)); } inline bool get_m_MaterialDirty_16() const { return ___m_MaterialDirty_16; } inline bool* get_address_of_m_MaterialDirty_16() { return &___m_MaterialDirty_16; } inline void set_m_MaterialDirty_16(bool value) { ___m_MaterialDirty_16 = value; } inline static int32_t get_offset_of_m_OnDirtyLayoutCallback_17() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_OnDirtyLayoutCallback_17)); } inline UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 * get_m_OnDirtyLayoutCallback_17() const { return ___m_OnDirtyLayoutCallback_17; } inline UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 ** get_address_of_m_OnDirtyLayoutCallback_17() { return &___m_OnDirtyLayoutCallback_17; } inline void set_m_OnDirtyLayoutCallback_17(UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 * value) { ___m_OnDirtyLayoutCallback_17 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_OnDirtyLayoutCallback_17), (void*)value); } inline static int32_t get_offset_of_m_OnDirtyVertsCallback_18() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_OnDirtyVertsCallback_18)); } inline UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 * get_m_OnDirtyVertsCallback_18() const { return ___m_OnDirtyVertsCallback_18; } inline UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 ** get_address_of_m_OnDirtyVertsCallback_18() { return &___m_OnDirtyVertsCallback_18; } inline void set_m_OnDirtyVertsCallback_18(UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 * value) { ___m_OnDirtyVertsCallback_18 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_OnDirtyVertsCallback_18), (void*)value); } inline static int32_t get_offset_of_m_OnDirtyMaterialCallback_19() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_OnDirtyMaterialCallback_19)); } inline UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 * get_m_OnDirtyMaterialCallback_19() const { return ___m_OnDirtyMaterialCallback_19; } inline UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 ** get_address_of_m_OnDirtyMaterialCallback_19() { return &___m_OnDirtyMaterialCallback_19; } inline void set_m_OnDirtyMaterialCallback_19(UnityAction_t22E545F8BE0A62EE051C6A83E209587A0DB1C099 * value) { ___m_OnDirtyMaterialCallback_19 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_OnDirtyMaterialCallback_19), (void*)value); } inline static int32_t get_offset_of_m_CachedMesh_22() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_CachedMesh_22)); } inline Mesh_t2F5992DBA650D5862B43D3823ACD997132A57DA6 * get_m_CachedMesh_22() const { return ___m_CachedMesh_22; } inline Mesh_t2F5992DBA650D5862B43D3823ACD997132A57DA6 ** get_address_of_m_CachedMesh_22() { return &___m_CachedMesh_22; } inline void set_m_CachedMesh_22(Mesh_t2F5992DBA650D5862B43D3823ACD997132A57DA6 * value) { ___m_CachedMesh_22 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_CachedMesh_22), (void*)value); } inline static int32_t get_offset_of_m_CachedUvs_23() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_CachedUvs_23)); } inline Vector2U5BU5D_tE0F58A2D6D8592B5EC37D9CDEF09103A02E5D7FA* get_m_CachedUvs_23() const { return ___m_CachedUvs_23; } inline Vector2U5BU5D_tE0F58A2D6D8592B5EC37D9CDEF09103A02E5D7FA** get_address_of_m_CachedUvs_23() { return &___m_CachedUvs_23; } inline void set_m_CachedUvs_23(Vector2U5BU5D_tE0F58A2D6D8592B5EC37D9CDEF09103A02E5D7FA* value) { ___m_CachedUvs_23 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_CachedUvs_23), (void*)value); } inline static int32_t get_offset_of_m_ColorTweenRunner_24() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___m_ColorTweenRunner_24)); } inline TweenRunner_1_tD84B9953874682FCC36990AF2C54D748293908F3 * get_m_ColorTweenRunner_24() const { return ___m_ColorTweenRunner_24; } inline TweenRunner_1_tD84B9953874682FCC36990AF2C54D748293908F3 ** get_address_of_m_ColorTweenRunner_24() { return &___m_ColorTweenRunner_24; } inline void set_m_ColorTweenRunner_24(TweenRunner_1_tD84B9953874682FCC36990AF2C54D748293908F3 * value) { ___m_ColorTweenRunner_24 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_ColorTweenRunner_24), (void*)value); } inline static int32_t get_offset_of_U3CuseLegacyMeshGenerationU3Ek__BackingField_25() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24, ___U3CuseLegacyMeshGenerationU3Ek__BackingField_25)); } inline bool get_U3CuseLegacyMeshGenerationU3Ek__BackingField_25() const { return ___U3CuseLegacyMeshGenerationU3Ek__BackingField_25; } inline bool* get_address_of_U3CuseLegacyMeshGenerationU3Ek__BackingField_25() { return &___U3CuseLegacyMeshGenerationU3Ek__BackingField_25; } inline void set_U3CuseLegacyMeshGenerationU3Ek__BackingField_25(bool value) { ___U3CuseLegacyMeshGenerationU3Ek__BackingField_25 = value; } }; struct Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24_StaticFields { public: // UnityEngine.Material UnityEngine.UI.Graphic::s_DefaultUI Material_t8927C00353A72755313F046D0CE85178AE8218EE * ___s_DefaultUI_4; // UnityEngine.Texture2D UnityEngine.UI.Graphic::s_WhiteTexture Texture2D_t9B604D0D8E28032123641A7E7338FA872E2698BF * ___s_WhiteTexture_5; // UnityEngine.Mesh UnityEngine.UI.Graphic::s_Mesh Mesh_t2F5992DBA650D5862B43D3823ACD997132A57DA6 * ___s_Mesh_20; // UnityEngine.UI.VertexHelper UnityEngine.UI.Graphic::s_VertexHelper VertexHelper_tDE8B67D3B076061C4F8DF325B0D63ED2E5367E55 * ___s_VertexHelper_21; public: inline static int32_t get_offset_of_s_DefaultUI_4() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24_StaticFields, ___s_DefaultUI_4)); } inline Material_t8927C00353A72755313F046D0CE85178AE8218EE * get_s_DefaultUI_4() const { return ___s_DefaultUI_4; } inline Material_t8927C00353A72755313F046D0CE85178AE8218EE ** get_address_of_s_DefaultUI_4() { return &___s_DefaultUI_4; } inline void set_s_DefaultUI_4(Material_t8927C00353A72755313F046D0CE85178AE8218EE * value) { ___s_DefaultUI_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_DefaultUI_4), (void*)value); } inline static int32_t get_offset_of_s_WhiteTexture_5() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24_StaticFields, ___s_WhiteTexture_5)); } inline Texture2D_t9B604D0D8E28032123641A7E7338FA872E2698BF * get_s_WhiteTexture_5() const { return ___s_WhiteTexture_5; } inline Texture2D_t9B604D0D8E28032123641A7E7338FA872E2698BF ** get_address_of_s_WhiteTexture_5() { return &___s_WhiteTexture_5; } inline void set_s_WhiteTexture_5(Texture2D_t9B604D0D8E28032123641A7E7338FA872E2698BF * value) { ___s_WhiteTexture_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_WhiteTexture_5), (void*)value); } inline static int32_t get_offset_of_s_Mesh_20() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24_StaticFields, ___s_Mesh_20)); } inline Mesh_t2F5992DBA650D5862B43D3823ACD997132A57DA6 * get_s_Mesh_20() const { return ___s_Mesh_20; } inline Mesh_t2F5992DBA650D5862B43D3823ACD997132A57DA6 ** get_address_of_s_Mesh_20() { return &___s_Mesh_20; } inline void set_s_Mesh_20(Mesh_t2F5992DBA650D5862B43D3823ACD997132A57DA6 * value) { ___s_Mesh_20 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_Mesh_20), (void*)value); } inline static int32_t get_offset_of_s_VertexHelper_21() { return static_cast<int32_t>(offsetof(Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24_StaticFields, ___s_VertexHelper_21)); } inline VertexHelper_tDE8B67D3B076061C4F8DF325B0D63ED2E5367E55 * get_s_VertexHelper_21() const { return ___s_VertexHelper_21; } inline VertexHelper_tDE8B67D3B076061C4F8DF325B0D63ED2E5367E55 ** get_address_of_s_VertexHelper_21() { return &___s_VertexHelper_21; } inline void set_s_VertexHelper_21(VertexHelper_tDE8B67D3B076061C4F8DF325B0D63ED2E5367E55 * value) { ___s_VertexHelper_21 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_VertexHelper_21), (void*)value); } }; // UnityEngine.UI.MaskableGraphic struct MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE : public Graphic_tF07D777035055CF93BA5F46F77ED5EDFEFF9AE24 { public: // System.Boolean UnityEngine.UI.MaskableGraphic::m_ShouldRecalculateStencil bool ___m_ShouldRecalculateStencil_26; // UnityEngine.Material UnityEngine.UI.MaskableGraphic::m_MaskMaterial Material_t8927C00353A72755313F046D0CE85178AE8218EE * ___m_MaskMaterial_27; // UnityEngine.UI.RectMask2D UnityEngine.UI.MaskableGraphic::m_ParentMask RectMask2D_tD909811991B341D752E4C978C89EFB80FA7A2B15 * ___m_ParentMask_28; // System.Boolean UnityEngine.UI.MaskableGraphic::m_Maskable bool ___m_Maskable_29; // System.Boolean UnityEngine.UI.MaskableGraphic::m_IsMaskingGraphic bool ___m_IsMaskingGraphic_30; // System.Boolean UnityEngine.UI.MaskableGraphic::m_IncludeForMasking bool ___m_IncludeForMasking_31; // UnityEngine.UI.MaskableGraphic/CullStateChangedEvent UnityEngine.UI.MaskableGraphic::m_OnCullStateChanged CullStateChangedEvent_t9B69755DEBEF041C3CC15C3604610BDD72856BD4 * ___m_OnCullStateChanged_32; // System.Boolean UnityEngine.UI.MaskableGraphic::m_ShouldRecalculate bool ___m_ShouldRecalculate_33; // System.Int32 UnityEngine.UI.MaskableGraphic::m_StencilValue int32_t ___m_StencilValue_34; // UnityEngine.Vector3[] UnityEngine.UI.MaskableGraphic::m_Corners Vector3U5BU5D_t5FB88EAA33E46838BDC2ABDAEA3E8727491CB9E4* ___m_Corners_35; public: inline static int32_t get_offset_of_m_ShouldRecalculateStencil_26() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_ShouldRecalculateStencil_26)); } inline bool get_m_ShouldRecalculateStencil_26() const { return ___m_ShouldRecalculateStencil_26; } inline bool* get_address_of_m_ShouldRecalculateStencil_26() { return &___m_ShouldRecalculateStencil_26; } inline void set_m_ShouldRecalculateStencil_26(bool value) { ___m_ShouldRecalculateStencil_26 = value; } inline static int32_t get_offset_of_m_MaskMaterial_27() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_MaskMaterial_27)); } inline Material_t8927C00353A72755313F046D0CE85178AE8218EE * get_m_MaskMaterial_27() const { return ___m_MaskMaterial_27; } inline Material_t8927C00353A72755313F046D0CE85178AE8218EE ** get_address_of_m_MaskMaterial_27() { return &___m_MaskMaterial_27; } inline void set_m_MaskMaterial_27(Material_t8927C00353A72755313F046D0CE85178AE8218EE * value) { ___m_MaskMaterial_27 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_MaskMaterial_27), (void*)value); } inline static int32_t get_offset_of_m_ParentMask_28() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_ParentMask_28)); } inline RectMask2D_tD909811991B341D752E4C978C89EFB80FA7A2B15 * get_m_ParentMask_28() const { return ___m_ParentMask_28; } inline RectMask2D_tD909811991B341D752E4C978C89EFB80FA7A2B15 ** get_address_of_m_ParentMask_28() { return &___m_ParentMask_28; } inline void set_m_ParentMask_28(RectMask2D_tD909811991B341D752E4C978C89EFB80FA7A2B15 * value) { ___m_ParentMask_28 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_ParentMask_28), (void*)value); } inline static int32_t get_offset_of_m_Maskable_29() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_Maskable_29)); } inline bool get_m_Maskable_29() const { return ___m_Maskable_29; } inline bool* get_address_of_m_Maskable_29() { return &___m_Maskable_29; } inline void set_m_Maskable_29(bool value) { ___m_Maskable_29 = value; } inline static int32_t get_offset_of_m_IsMaskingGraphic_30() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_IsMaskingGraphic_30)); } inline bool get_m_IsMaskingGraphic_30() const { return ___m_IsMaskingGraphic_30; } inline bool* get_address_of_m_IsMaskingGraphic_30() { return &___m_IsMaskingGraphic_30; } inline void set_m_IsMaskingGraphic_30(bool value) { ___m_IsMaskingGraphic_30 = value; } inline static int32_t get_offset_of_m_IncludeForMasking_31() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_IncludeForMasking_31)); } inline bool get_m_IncludeForMasking_31() const { return ___m_IncludeForMasking_31; } inline bool* get_address_of_m_IncludeForMasking_31() { return &___m_IncludeForMasking_31; } inline void set_m_IncludeForMasking_31(bool value) { ___m_IncludeForMasking_31 = value; } inline static int32_t get_offset_of_m_OnCullStateChanged_32() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_OnCullStateChanged_32)); } inline CullStateChangedEvent_t9B69755DEBEF041C3CC15C3604610BDD72856BD4 * get_m_OnCullStateChanged_32() const { return ___m_OnCullStateChanged_32; } inline CullStateChangedEvent_t9B69755DEBEF041C3CC15C3604610BDD72856BD4 ** get_address_of_m_OnCullStateChanged_32() { return &___m_OnCullStateChanged_32; } inline void set_m_OnCullStateChanged_32(CullStateChangedEvent_t9B69755DEBEF041C3CC15C3604610BDD72856BD4 * value) { ___m_OnCullStateChanged_32 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_OnCullStateChanged_32), (void*)value); } inline static int32_t get_offset_of_m_ShouldRecalculate_33() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_ShouldRecalculate_33)); } inline bool get_m_ShouldRecalculate_33() const { return ___m_ShouldRecalculate_33; } inline bool* get_address_of_m_ShouldRecalculate_33() { return &___m_ShouldRecalculate_33; } inline void set_m_ShouldRecalculate_33(bool value) { ___m_ShouldRecalculate_33 = value; } inline static int32_t get_offset_of_m_StencilValue_34() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_StencilValue_34)); } inline int32_t get_m_StencilValue_34() const { return ___m_StencilValue_34; } inline int32_t* get_address_of_m_StencilValue_34() { return &___m_StencilValue_34; } inline void set_m_StencilValue_34(int32_t value) { ___m_StencilValue_34 = value; } inline static int32_t get_offset_of_m_Corners_35() { return static_cast<int32_t>(offsetof(MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE, ___m_Corners_35)); } inline Vector3U5BU5D_t5FB88EAA33E46838BDC2ABDAEA3E8727491CB9E4* get_m_Corners_35() const { return ___m_Corners_35; } inline Vector3U5BU5D_t5FB88EAA33E46838BDC2ABDAEA3E8727491CB9E4** get_address_of_m_Corners_35() { return &___m_Corners_35; } inline void set_m_Corners_35(Vector3U5BU5D_t5FB88EAA33E46838BDC2ABDAEA3E8727491CB9E4* value) { ___m_Corners_35 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Corners_35), (void*)value); } }; // UnityEngine.UI.Text struct Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1 : public MaskableGraphic_t0DB59E37E3C8AD2F5A4FB7FB091630CB21370CCE { public: // UnityEngine.UI.FontData UnityEngine.UI.Text::m_FontData FontData_t0F1E9B3ED8136CD40782AC9A6AFB69CAD127C738 * ___m_FontData_36; // System.String UnityEngine.UI.Text::m_Text String_t* ___m_Text_37; // UnityEngine.TextGenerator UnityEngine.UI.Text::m_TextCache TextGenerator_t893F256D3587633108E00E5731CDC5A77AFF1B70 * ___m_TextCache_38; // UnityEngine.TextGenerator UnityEngine.UI.Text::m_TextCacheForLayout TextGenerator_t893F256D3587633108E00E5731CDC5A77AFF1B70 * ___m_TextCacheForLayout_39; // System.Boolean UnityEngine.UI.Text::m_DisableFontTextureRebuiltCallback bool ___m_DisableFontTextureRebuiltCallback_41; // UnityEngine.UIVertex[] UnityEngine.UI.Text::m_TempVerts UIVertexU5BU5D_tE3D523C48DFEBC775876720DE2539A79FB7E5E5A* ___m_TempVerts_42; public: inline static int32_t get_offset_of_m_FontData_36() { return static_cast<int32_t>(offsetof(Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1, ___m_FontData_36)); } inline FontData_t0F1E9B3ED8136CD40782AC9A6AFB69CAD127C738 * get_m_FontData_36() const { return ___m_FontData_36; } inline FontData_t0F1E9B3ED8136CD40782AC9A6AFB69CAD127C738 ** get_address_of_m_FontData_36() { return &___m_FontData_36; } inline void set_m_FontData_36(FontData_t0F1E9B3ED8136CD40782AC9A6AFB69CAD127C738 * value) { ___m_FontData_36 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_FontData_36), (void*)value); } inline static int32_t get_offset_of_m_Text_37() { return static_cast<int32_t>(offsetof(Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1, ___m_Text_37)); } inline String_t* get_m_Text_37() const { return ___m_Text_37; } inline String_t** get_address_of_m_Text_37() { return &___m_Text_37; } inline void set_m_Text_37(String_t* value) { ___m_Text_37 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_Text_37), (void*)value); } inline static int32_t get_offset_of_m_TextCache_38() { return static_cast<int32_t>(offsetof(Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1, ___m_TextCache_38)); } inline TextGenerator_t893F256D3587633108E00E5731CDC5A77AFF1B70 * get_m_TextCache_38() const { return ___m_TextCache_38; } inline TextGenerator_t893F256D3587633108E00E5731CDC5A77AFF1B70 ** get_address_of_m_TextCache_38() { return &___m_TextCache_38; } inline void set_m_TextCache_38(TextGenerator_t893F256D3587633108E00E5731CDC5A77AFF1B70 * value) { ___m_TextCache_38 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_TextCache_38), (void*)value); } inline static int32_t get_offset_of_m_TextCacheForLayout_39() { return static_cast<int32_t>(offsetof(Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1, ___m_TextCacheForLayout_39)); } inline TextGenerator_t893F256D3587633108E00E5731CDC5A77AFF1B70 * get_m_TextCacheForLayout_39() const { return ___m_TextCacheForLayout_39; } inline TextGenerator_t893F256D3587633108E00E5731CDC5A77AFF1B70 ** get_address_of_m_TextCacheForLayout_39() { return &___m_TextCacheForLayout_39; } inline void set_m_TextCacheForLayout_39(TextGenerator_t893F256D3587633108E00E5731CDC5A77AFF1B70 * value) { ___m_TextCacheForLayout_39 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_TextCacheForLayout_39), (void*)value); } inline static int32_t get_offset_of_m_DisableFontTextureRebuiltCallback_41() { return static_cast<int32_t>(offsetof(Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1, ___m_DisableFontTextureRebuiltCallback_41)); } inline bool get_m_DisableFontTextureRebuiltCallback_41() const { return ___m_DisableFontTextureRebuiltCallback_41; } inline bool* get_address_of_m_DisableFontTextureRebuiltCallback_41() { return &___m_DisableFontTextureRebuiltCallback_41; } inline void set_m_DisableFontTextureRebuiltCallback_41(bool value) { ___m_DisableFontTextureRebuiltCallback_41 = value; } inline static int32_t get_offset_of_m_TempVerts_42() { return static_cast<int32_t>(offsetof(Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1, ___m_TempVerts_42)); } inline UIVertexU5BU5D_tE3D523C48DFEBC775876720DE2539A79FB7E5E5A* get_m_TempVerts_42() const { return ___m_TempVerts_42; } inline UIVertexU5BU5D_tE3D523C48DFEBC775876720DE2539A79FB7E5E5A** get_address_of_m_TempVerts_42() { return &___m_TempVerts_42; } inline void set_m_TempVerts_42(UIVertexU5BU5D_tE3D523C48DFEBC775876720DE2539A79FB7E5E5A* value) { ___m_TempVerts_42 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_TempVerts_42), (void*)value); } }; struct Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1_StaticFields { public: // UnityEngine.Material UnityEngine.UI.Text::s_DefaultText Material_t8927C00353A72755313F046D0CE85178AE8218EE * ___s_DefaultText_40; public: inline static int32_t get_offset_of_s_DefaultText_40() { return static_cast<int32_t>(offsetof(Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1_StaticFields, ___s_DefaultText_40)); } inline Material_t8927C00353A72755313F046D0CE85178AE8218EE * get_s_DefaultText_40() const { return ___s_DefaultText_40; } inline Material_t8927C00353A72755313F046D0CE85178AE8218EE ** get_address_of_s_DefaultText_40() { return &___s_DefaultText_40; } inline void set_s_DefaultText_40(Material_t8927C00353A72755313F046D0CE85178AE8218EE * value) { ___s_DefaultText_40 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_DefaultText_40), (void*)value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // UnityEngine.GameObject[] struct GameObjectU5BU5D_tA88FC1A1FC9D4D73D0B3984D4B0ECE88F4C47642 : public RuntimeArray { public: ALIGN_FIELD (8) GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * m_Items[1]; public: inline GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } inline GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } }; // System.Object[] struct ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE : public RuntimeArray { public: ALIGN_FIELD (8) RuntimeObject * m_Items[1]; public: inline RuntimeObject * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline RuntimeObject ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, RuntimeObject * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } inline RuntimeObject * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline RuntimeObject ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, RuntimeObject * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier((void**)m_Items + index, (void*)value); } }; // !!0 UnityEngine.Object::Instantiate<System.Object>(!!0,UnityEngine.Vector3,UnityEngine.Quaternion) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * Object_Instantiate_TisRuntimeObject_mB05DEC51C29EF5BB8BD17D055E80217F11E571AA_gshared (RuntimeObject * ___original0, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___position1, Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 ___rotation2, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<System.Object>::Add(!0) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1_Add_mE5B3CBB3A625606D9BC4337FEAAF1D66BCB6F96E_gshared (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, RuntimeObject * ___item0, const RuntimeMethod* method); // !0 System.Collections.Generic.List`1<System.Object>::get_Item(System.Int32) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR RuntimeObject * List_1_get_Item_mF00B574E58FB078BB753B05A3B86DD0A7A266B63_gshared_inline (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, int32_t ___index0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<System.Object>::RemoveAt(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1_RemoveAt_m66148860899ECCAE9B323372032BFC1C255393D2_gshared (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, int32_t ___index0, const RuntimeMethod* method); // System.Int32 System.Collections.Generic.List`1<System.Object>::get_Count() IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR int32_t List_1_get_Count_m5D847939ABB9A78203B062CAFFE975792174D00F_gshared_inline (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<System.Object>::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1__ctor_m0F0E00088CF56FEACC9E32D8B7D91B93D91DAA3B_gshared (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, const RuntimeMethod* method); // !!0 UnityEngine.GameObject::GetComponent<System.Object>() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * GameObject_GetComponent_TisRuntimeObject_mCE43118393A796C759AC5D43257AB2330881767D_gshared (GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * __this, const RuntimeMethod* method); // !!0 UnityEngine.Component::GetComponent<System.Object>() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * Component_GetComponent_TisRuntimeObject_m69D9C576D6DD024C709E29EEADBC8041299A3AA7_gshared (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * __this, const RuntimeMethod* method); // UnityEngine.GameObject UnityEngine.Component::get_gameObject() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * Component_get_gameObject_m55DC35B149AFB9157582755383BA954655FE0C5B (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * __this, const RuntimeMethod* method); // System.Void UnityEngine.Object::Destroy(UnityEngine.Object,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Object_Destroy_mAAAA103F4911E9FA18634BF9605C28559F5E2AC7 (Object_tF2F3778131EFF286AF62B7B013A170F95A91571A * ___obj0, float ___t1, const RuntimeMethod* method); // UnityEngine.Transform UnityEngine.Component::get_transform() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::get_back() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_get_back_mD521DF1A2C26E145578E07D618E1E4D08A1C6220 (const RuntimeMethod* method); // System.Single UnityEngine.Time::get_deltaTime() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Time_get_deltaTime_mCC15F147DA67F38C74CE408FB5D7FF4A87DA2290 (const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::op_Multiply(UnityEngine.Vector3,System.Single) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, float ___d1, const RuntimeMethod* method); // System.Void UnityEngine.Transform::Translate(UnityEngine.Vector3,UnityEngine.Space) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Transform_Translate_mFB58CBF3FA00BD0EE09EC67457608F62564D0DDE (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___translation0, int32_t ___relativeTo1, const RuntimeMethod* method); // System.Void UnityEngine.MonoBehaviour::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED (MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A * __this, const RuntimeMethod* method); // System.Collections.IEnumerator DoorGenerator::SpawnerCoroutine1() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject* DoorGenerator_SpawnerCoroutine1_m491C8AAB3DC3A33DE2CD28DF5DDB6905402DA760 (DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * __this, const RuntimeMethod* method); // UnityEngine.Coroutine UnityEngine.MonoBehaviour::StartCoroutine(System.Collections.IEnumerator) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Coroutine_t899D5232EF542CB8BA70AF9ECEECA494FAA9CCB7 * MonoBehaviour_StartCoroutine_m3E33706D38B23CDD179E99BAD61E32303E9CC719 (MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A * __this, RuntimeObject* ___routine0, const RuntimeMethod* method); // System.Void DoorGenerator/<SpawnerCoroutine1>d__4::.ctor(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CSpawnerCoroutine1U3Ed__4__ctor_mF876BFA52EBF1DBCBBEF1A73AC898ECE915EE7EB (U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A * __this, int32_t ___U3CU3E1__state0, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Transform::get_position() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341 (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Transform::get_localPosition() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Transform_get_localPosition_m527B8B5B625DA9A61E551E0FBCD3BE8CA4539FC2 (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::op_Subtraction(UnityEngine.Vector3,UnityEngine.Vector3) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_Subtraction_m2725C96965D5C0B1F9715797E51762B13A5FED58_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___b1, const RuntimeMethod* method); // UnityEngine.Quaternion UnityEngine.Quaternion::get_identity() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 Quaternion_get_identity_mF2E565DBCE793A1AE6208056D42CA7C59D83A702 (const RuntimeMethod* method); // !!0 UnityEngine.Object::Instantiate<EnvironmentTiling>(!!0,UnityEngine.Vector3,UnityEngine.Quaternion) inline EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * Object_Instantiate_TisEnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE_m71CB2DF77D915C7F7A0FE4F736AF7CCB0AAFF788 (EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * ___original0, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___position1, Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 ___rotation2, const RuntimeMethod* method) { return (( EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * (*) (EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE *, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E , Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 , const RuntimeMethod*))Object_Instantiate_TisRuntimeObject_mB05DEC51C29EF5BB8BD17D055E80217F11E571AA_gshared)(___original0, ___position1, ___rotation2, method); } // System.Void EnvironmentTiling::ActivateCorridor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EnvironmentTiling_ActivateCorridor_m4A158ED61356D3521485976518BA96A4B134CC60 (EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * __this, const RuntimeMethod* method); // System.Void UnityEngine.Transform::SetParent(UnityEngine.Transform) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Transform_SetParent_m24E34EBEF76528C99AFA017F157EE8B3E3116B1E (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * ___p0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<EnvironmentTiling>::Add(!0) inline void List_1_Add_m9DD38E1D935506058FC2E3F3760DB0717097CEDB (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * __this, EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * ___item0, const RuntimeMethod* method) { (( void (*) (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB *, EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE *, const RuntimeMethod*))List_1_Add_mE5B3CBB3A625606D9BC4337FEAAF1D66BCB6F96E_gshared)(__this, ___item0, method); } // !0 System.Collections.Generic.List`1<EnvironmentTiling>::get_Item(System.Int32) inline EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_inline (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * __this, int32_t ___index0, const RuntimeMethod* method) { return (( EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * (*) (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB *, int32_t, const RuntimeMethod*))List_1_get_Item_mF00B574E58FB078BB753B05A3B86DD0A7A266B63_gshared_inline)(__this, ___index0, method); } // UnityEngine.Vector3 UnityEngine.Transform::get_forward() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Transform_get_forward_mD850B9ECF892009E3485408DC0D375165B7BF053 (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::op_UnaryNegation(UnityEngine.Vector3) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_UnaryNegation_m362EA356F4CADEDB39F965A0DBDED6EA890925F7_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Camera::WorldToViewportPoint(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Camera_WorldToViewportPoint_m656CDAE26AAC040A4A47DAFF8EEDB0A941BE051D (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___position0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<EnvironmentTiling>::RemoveAt(System.Int32) inline void List_1_RemoveAt_m6839717CCA2768D5DF8850CF9C896D0D4B223F3B (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * __this, int32_t ___index0, const RuntimeMethod* method) { (( void (*) (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB *, int32_t, const RuntimeMethod*))List_1_RemoveAt_m66148860899ECCAE9B323372032BFC1C255393D2_gshared)(__this, ___index0, method); } // System.Int32 System.Collections.Generic.List`1<EnvironmentTiling>::get_Count() inline int32_t List_1_get_Count_mC0B6C3963C8EDEC72D02B324F705A66C9C6BB19C_inline (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * __this, const RuntimeMethod* method) { return (( int32_t (*) (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB *, const RuntimeMethod*))List_1_get_Count_m5D847939ABB9A78203B062CAFFE975792174D00F_gshared_inline)(__this, method); } // System.Void UnityEngine.Transform::set_position(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Transform_set_position_mB169E52D57EEAC1E3F22C5395968714E4F00AC91 (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___value0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<EnvironmentTiling>::.ctor() inline void List_1__ctor_m92E7452A54F62BF12651BB65E9ABFCE56433C579 (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * __this, const RuntimeMethod* method) { (( void (*) (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB *, const RuntimeMethod*))List_1__ctor_m0F0E00088CF56FEACC9E32D8B7D91B93D91DAA3B_gshared)(__this, method); } // System.Void System.Random::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Random__ctor_mF40AD1812BABC06235B661CCE513E4F74EEE9F05 (Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118 * __this, const RuntimeMethod* method); // System.Void UnityEngine.GameObject::SetActive(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void GameObject_SetActive_mCF1EEF2A314F3AE85DA581FF52EB06ACEF2FFF86 (GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * __this, bool ___value0, const RuntimeMethod* method); // System.String System.Int32::ToString() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* Int32_ToString_m340C0A14D16799421EFDF8A81C8A16FA76D48411 (int32_t* __this, const RuntimeMethod* method); // System.String System.String::Concat(System.String,System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* String_Concat_m4B4AB72618348C5DFBFBA8DED84B9E2EBDB55E1B (String_t* ___str00, String_t* ___str11, const RuntimeMethod* method); // System.Void UnityEngine.SceneManagement.SceneManager::LoadScene(System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SceneManager_LoadScene_m7DAF30213E99396ECBDB1BD40CC34CCF36902092 (String_t* ___sceneName0, const RuntimeMethod* method); // System.Void UnityEngine.Application::Quit() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Application_Quit_m8D720E5092786C2EE32310D85FE61C253D3B1F2A (const RuntimeMethod* method); // System.Collections.IEnumerator ObstacleSpawner::SpawnerCoroutine() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject* ObstacleSpawner_SpawnerCoroutine_m4DFA5FB411ADFAF0AC803A49901A8725D75641F8 (ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * __this, const RuntimeMethod* method); // System.Void ObstacleSpawner/<SpawnerCoroutine>d__4::.ctor(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CSpawnerCoroutineU3Ed__4__ctor_m00AB12936ACCDE67EAED4471CD2C5A91D17BF5CF (U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 * __this, int32_t ___U3CU3E1__state0, const RuntimeMethod* method); // !!0 UnityEngine.GameObject::GetComponent<UnityEngine.Video.VideoPlayer>() inline VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * GameObject_GetComponent_TisVideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86_mE0279031C6B378280F6E848C495D87D03F1647B2 (GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * __this, const RuntimeMethod* method) { return (( VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * (*) (GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 *, const RuntimeMethod*))GameObject_GetComponent_TisRuntimeObject_mCE43118393A796C759AC5D43257AB2330881767D_gshared)(__this, method); } // System.String UnityEngine.Application::get_streamingAssetsPath() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* Application_get_streamingAssetsPath_mA1FBABB08D7A4590A468C7CD940CD442B58C91E1 (const RuntimeMethod* method); // System.String System.IO.Path::Combine(System.String,System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* Path_Combine_mC22E47A9BB232F02ED3B6B5F6DD53338D37782EF (String_t* ___path10, String_t* ___path21, const RuntimeMethod* method); // System.Void UnityEngine.Video.VideoPlayer::set_url(System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void VideoPlayer_set_url_m9C9942D6C54D50F6255A2AA1646D9F40E551BF13 (VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * __this, String_t* ___value0, const RuntimeMethod* method); // System.Void UnityEngine.Video.VideoPlayer::Play() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void VideoPlayer_Play_m2AD0D39D70055A5AADCF63430D3D9CEC7DCB0516 (VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * __this, const RuntimeMethod* method); // !!0 UnityEngine.Component::GetComponent<UnityEngine.Rigidbody>() inline Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * Component_GetComponent_TisRigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A_m9DC24AA806B0B65E917751F7A3AFDB58861157CE (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * __this, const RuntimeMethod* method) { return (( Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * (*) (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m69D9C576D6DD024C709E29EEADBC8041299A3AA7_gshared)(__this, method); } // System.Void UnityEngine.Rigidbody::set_constraints(UnityEngine.RigidbodyConstraints) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rigidbody_set_constraints_mA76F562D16D3BE8889E095D0309C8FE38DA914F1 (Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * __this, int32_t ___value0, const RuntimeMethod* method); // System.Void UnityEngine.Rigidbody::set_freezeRotation(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rigidbody_set_freezeRotation_mE08A39E98D46F82D6DD86CC389D86D242C694D52 (Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * __this, bool ___value0, const RuntimeMethod* method); // System.Void UnityEngine.Rigidbody::set_useGravity(System.Boolean) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rigidbody_set_useGravity_m1057292FB3199E87664F40B8BCBA7A7E64D1A096 (Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * __this, bool ___value0, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Transform::get_localScale() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Transform_get_localScale_mD9DF6CA81108C2A6002B5EA2BE25A6CD2723D046 (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, const RuntimeMethod* method); // System.Boolean UnityEngine.Input::GetKeyDown(UnityEngine.KeyCode) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Input_GetKeyDown_m476116696E71771641BBECBAB1A4C55E69018220 (int32_t ___key0, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Rigidbody::get_velocity() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Rigidbody_get_velocity_mCFB033F3BD14C2BA68E797DFA4950F9307EC8E2C (Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * __this, const RuntimeMethod* method); // System.Single Player::CalculateJumpVerticalSpeed() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Player_CalculateJumpVerticalSpeed_mA671C584D141496A5A4E71A3294CE34FCCC44AD5 (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, const RuntimeMethod* method); // System.Void UnityEngine.Vector3::.ctor(System.Single,System.Single,System.Single) IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * __this, float ___x0, float ___y1, float ___z2, const RuntimeMethod* method); // System.Void UnityEngine.Rigidbody::set_velocity(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rigidbody_set_velocity_m8DC0988916EB38DFD7D4584830B41D79140BF18D (Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * __this, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___value0, const RuntimeMethod* method); // System.Boolean UnityEngine.Input::GetKey(System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Input_GetKey_m77E2F3719EC63690632731872A691FF6A27C589C (String_t* ___name0, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::get_left() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_get_left_mDAB848C352B9D30E2DDDA7F56308ABC32A4315A5 (const RuntimeMethod* method); // System.Void UnityEngine.Transform::Translate(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Transform_Translate_m24A8CB13E2AAB0C17EE8FE593266CF463E0B02D0 (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___translation0, const RuntimeMethod* method); // UnityEngine.Vector3 UnityEngine.Vector3::get_right() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_get_right_mF5A51F81961474E0A7A31C2757FD00921FB79C44 (const RuntimeMethod* method); // System.Single UnityEngine.Mathf::Clamp(System.Single,System.Single,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Mathf_Clamp_m2416F3B785C8F135863E3D17E5B0CB4174797B87 (float ___value0, float ___min1, float ___max2, const RuntimeMethod* method); // System.Single UnityEngine.Rigidbody::get_mass() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Rigidbody_get_mass_mB7B19406DAC6336A8244E98BE271BDA8B5C26223 (Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * __this, const RuntimeMethod* method); // System.Void UnityEngine.Rigidbody::AddForce(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rigidbody_AddForce_mDFB0D57C25682B826999B0074F5C0FD399C6401D (Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * __this, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___force0, const RuntimeMethod* method); // UnityEngine.GameObject UnityEngine.Collision::get_gameObject() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * Collision_get_gameObject_m5682F872FD28419AA36F0651CE8B19825A21859D (Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0 * __this, const RuntimeMethod* method); // System.Boolean UnityEngine.GameObject::CompareTag(System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool GameObject_CompareTag_mA692D8508984DBE4A2FEFD19E29CB1C9D5CDE001 (GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * __this, String_t* ___tag0, const RuntimeMethod* method); // System.Void Player::Die() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Player_Die_m16A200929DBDF9FF88C8191A26327C2CCCC80C19 (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, const RuntimeMethod* method); // !!0 UnityEngine.Component::GetComponent<UnityEngine.CharacterController>() inline CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * Component_GetComponent_TisCharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E_m3DB1DD5819F96D7C7F6F19C12138AC48D21DBBF2 (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * __this, const RuntimeMethod* method) { return (( CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * (*) (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m69D9C576D6DD024C709E29EEADBC8041299A3AA7_gshared)(__this, method); } // UnityEngine.Vector3 UnityEngine.Vector3::get_zero() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_get_zero_m1A8F7993167785F750B6B01762D22C2597C84EF6 (const RuntimeMethod* method); // System.Boolean UnityEngine.CharacterController::get_isGrounded() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool CharacterController_get_isGrounded_m327A1A1940F225FE81E751F255316BB0D8698CBC (CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * __this, const RuntimeMethod* method); // System.Single UnityEngine.Input::GetAxisRaw(System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Input_GetAxisRaw_mC07AC23FD8D04A69CDB07C6399C93FFFAEB0FC5B (String_t* ___axisName0, const RuntimeMethod* method); // UnityEngine.CollisionFlags UnityEngine.CharacterController::Move(UnityEngine.Vector3) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t CharacterController_Move_mE0EBC32C72A0BEC18EDEBE748D44309A4BA32E60 (CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * __this, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___motion0, const RuntimeMethod* method); // System.Void System.Object::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405 (RuntimeObject * __this, const RuntimeMethod* method); // System.Single UnityEngine.Random::Range(System.Single,System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Random_Range_mC15372D42A9ABDCAC3DE82E114D60A40C9C311D2 (float ___minInclusive0, float ___maxInclusive1, const RuntimeMethod* method); // System.Void UnityEngine.WaitForSeconds::.ctor(System.Single) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void WaitForSeconds__ctor_mD298C4CB9532BBBDE172FC40F3397E30504038D4 (WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013 * __this, float ___seconds0, const RuntimeMethod* method); // UnityEngine.Quaternion UnityEngine.Transform::get_rotation() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 Transform_get_rotation_m4AA3858C00DF4C9614B80352558C4C37D08D2200 (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, const RuntimeMethod* method); // !!0 UnityEngine.Object::Instantiate<UnityEngine.GameObject>(!!0,UnityEngine.Vector3,UnityEngine.Quaternion) inline GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B (GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * ___original0, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___position1, Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 ___rotation2, const RuntimeMethod* method) { return (( GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * (*) (GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 *, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E , Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 , const RuntimeMethod*))Object_Instantiate_TisRuntimeObject_mB05DEC51C29EF5BB8BD17D055E80217F11E571AA_gshared)(___original0, ___position1, ___rotation2, method); } // System.Boolean UnityEngine.Behaviour::get_enabled() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Behaviour_get_enabled_m08077AB79934634E1EAE909C2B482BEF4C15A800 (Behaviour_t1A3DDDCF73B4627928FBFE02ED52B7251777DBD9 * __this, const RuntimeMethod* method); // System.Void System.NotSupportedException::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void NotSupportedException__ctor_m3EA81A5B209A87C3ADA47443F2AFFF735E5256EE (NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339 * __this, const RuntimeMethod* method); // System.Void System.ThrowHelper::ThrowArgumentOutOfRangeException() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ThrowHelper_ThrowArgumentOutOfRangeException_m4841366ABC2B2AFA37C10900551D7E07522C0929 (const RuntimeMethod* method); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void Door::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Door_Start_mA9CDA5E1EC4C187EAC0FD892B42D65A4BA874637 (Door_t7B1F8C89F7CCF5EBECA830A8D7799005C9EE44F6 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { // Destroy(gameObject, 6f); GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_0; L_0 = Component_get_gameObject_m55DC35B149AFB9157582755383BA954655FE0C5B(__this, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); Object_Destroy_mAAAA103F4911E9FA18634BF9605C28559F5E2AC7(L_0, (6.0f), /*hidden argument*/NULL); // } return; } } // System.Void Door::Update() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Door_Update_m4D88DB18FEC8010A04BDD6317A04C821A9DE83C9 (Door_t7B1F8C89F7CCF5EBECA830A8D7799005C9EE44F6 * __this, const RuntimeMethod* method) { { // transform.Translate(Vector3.back * Time.deltaTime * movingSpeed, Space.World); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_0; L_0 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_1; L_1 = Vector3_get_back_mD521DF1A2C26E145578E07D618E1E4D08A1C6220(/*hidden argument*/NULL); float L_2; L_2 = Time_get_deltaTime_mCC15F147DA67F38C74CE408FB5D7FF4A87DA2290(/*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_3; L_3 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_1, L_2, /*hidden argument*/NULL); float L_4 = __this->get_movingSpeed_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_5; L_5 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_3, L_4, /*hidden argument*/NULL); Transform_Translate_mFB58CBF3FA00BD0EE09EC67457608F62564D0DDE(L_0, L_5, 0, /*hidden argument*/NULL); // } return; } } // System.Void Door::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Door__ctor_m233920680DCEDAF41D0AE736031A0D1AB5C99773 (Door_t7B1F8C89F7CCF5EBECA830A8D7799005C9EE44F6 * __this, const RuntimeMethod* method) { { // public float movingSpeed = 8; __this->set_movingSpeed_4((8.0f)); MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void DoorGenerator::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void DoorGenerator_Start_mBDC8D72274B85CA8E4E55B193612CE974C81F77E (DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * __this, const RuntimeMethod* method) { { // StartCoroutine(SpawnerCoroutine1()); RuntimeObject* L_0; L_0 = DoorGenerator_SpawnerCoroutine1_m491C8AAB3DC3A33DE2CD28DF5DDB6905402DA760(__this, /*hidden argument*/NULL); Coroutine_t899D5232EF542CB8BA70AF9ECEECA494FAA9CCB7 * L_1; L_1 = MonoBehaviour_StartCoroutine_m3E33706D38B23CDD179E99BAD61E32303E9CC719(__this, L_0, /*hidden argument*/NULL); // } return; } } // System.Collections.IEnumerator DoorGenerator::SpawnerCoroutine1() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject* DoorGenerator_SpawnerCoroutine1_m491C8AAB3DC3A33DE2CD28DF5DDB6905402DA760 (DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A * L_0 = (U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A *)il2cpp_codegen_object_new(U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A_il2cpp_TypeInfo_var); U3CSpawnerCoroutine1U3Ed__4__ctor_mF876BFA52EBF1DBCBBEF1A73AC898ECE915EE7EB(L_0, 0, /*hidden argument*/NULL); U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A * L_1 = L_0; L_1->set_U3CU3E4__this_2(__this); return L_1; } } // System.Void DoorGenerator::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void DoorGenerator__ctor_mBC5083E33A9E19ACCB5E642392D3A72B494023F1 (DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * __this, const RuntimeMethod* method) { { MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void EnvironmentGenerator::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EnvironmentGenerator_Start_m3183461E261FB43204230D3FC9E7D59E8BC08D9D (EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_Add_m9DD38E1D935506058FC2E3F3760DB0717097CEDB_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_Instantiate_TisEnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE_m71CB2DF77D915C7F7A0FE4F736AF7CCB0AAFF788_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E V_0; memset((&V_0), 0, sizeof(V_0)); int32_t V_1 = 0; EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * V_2 = NULL; { // instance = this; ((EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D_StaticFields*)il2cpp_codegen_static_fields_for(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D_il2cpp_TypeInfo_var))->set_instance_11(__this); // Vector3 spawnPosition = startPoint.position; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_0 = __this->get_startPoint_5(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_1; L_1 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_0, /*hidden argument*/NULL); V_0 = L_1; // for (int i = 0; i < tilesToPreSpawn; i++) V_1 = 0; goto IL_0072; } IL_0016: { // spawnPosition -= tilePrefab.startPoint.localPosition; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_2 = V_0; EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_3 = __this->get_tilePrefab_6(); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_4 = L_3->get_startPoint_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_5; L_5 = Transform_get_localPosition_m527B8B5B625DA9A61E551E0FBCD3BE8CA4539FC2(L_4, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_6; L_6 = Vector3_op_Subtraction_m2725C96965D5C0B1F9715797E51762B13A5FED58_inline(L_2, L_5, /*hidden argument*/NULL); V_0 = L_6; // EnvironmentTiling spawnedTile = Instantiate(tilePrefab, spawnPosition, Quaternion.identity) as EnvironmentTiling; EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_7 = __this->get_tilePrefab_6(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_8 = V_0; Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 L_9; L_9 = Quaternion_get_identity_mF2E565DBCE793A1AE6208056D42CA7C59D83A702(/*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_10; L_10 = Object_Instantiate_TisEnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE_m71CB2DF77D915C7F7A0FE4F736AF7CCB0AAFF788(L_7, L_8, L_9, /*hidden argument*/Object_Instantiate_TisEnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE_m71CB2DF77D915C7F7A0FE4F736AF7CCB0AAFF788_RuntimeMethod_var); V_2 = L_10; // spawnedTile.ActivateCorridor(); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_11 = V_2; EnvironmentTiling_ActivateCorridor_m4A158ED61356D3521485976518BA96A4B134CC60(L_11, /*hidden argument*/NULL); // spawnPosition = spawnedTile.endPoint.position; EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_12 = V_2; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_13 = L_12->get_endPoint_5(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_14; L_14 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_13, /*hidden argument*/NULL); V_0 = L_14; // spawnedTile.transform.SetParent(transform); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_15 = V_2; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_16; L_16 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_15, /*hidden argument*/NULL); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_17; L_17 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); Transform_SetParent_m24E34EBEF76528C99AFA017F157EE8B3E3116B1E(L_16, L_17, /*hidden argument*/NULL); // spawnedTiles.Add(spawnedTile); List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * L_18 = __this->get_spawnedTiles_10(); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_19 = V_2; List_1_Add_m9DD38E1D935506058FC2E3F3760DB0717097CEDB(L_18, L_19, /*hidden argument*/List_1_Add_m9DD38E1D935506058FC2E3F3760DB0717097CEDB_RuntimeMethod_var); // for (int i = 0; i < tilesToPreSpawn; i++) int32_t L_20 = V_1; V_1 = ((int32_t)il2cpp_codegen_add((int32_t)L_20, (int32_t)1)); } IL_0072: { // for (int i = 0; i < tilesToPreSpawn; i++) int32_t L_21 = V_1; int32_t L_22 = __this->get_tilesToPreSpawn_8(); if ((((int32_t)L_21) < ((int32_t)L_22))) { goto IL_0016; } } { // score = 0; __this->set_score_9(0); // } return; } } // System.Void EnvironmentGenerator::Update() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EnvironmentGenerator_Update_mC43E5A427F7568BD6904177C8638C9E4D19C7725 (EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_Add_m9DD38E1D935506058FC2E3F3760DB0717097CEDB_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_RemoveAt_m6839717CCA2768D5DF8850CF9C896D0D4B223F3B_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_get_Count_mC0B6C3963C8EDEC72D02B324F705A66C9C6BB19C_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_RuntimeMethod_var); s_Il2CppMethodInitialized = true; } EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * V_0 = NULL; { // transform.Translate(-spawnedTiles[0].transform.forward * Time.deltaTime * movingSpeed, Space.World); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_0; L_0 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * L_1 = __this->get_spawnedTiles_10(); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_2; L_2 = List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_inline(L_1, 0, /*hidden argument*/List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_RuntimeMethod_var); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_3; L_3 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_2, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_4; L_4 = Transform_get_forward_mD850B9ECF892009E3485408DC0D375165B7BF053(L_3, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_5; L_5 = Vector3_op_UnaryNegation_m362EA356F4CADEDB39F965A0DBDED6EA890925F7_inline(L_4, /*hidden argument*/NULL); float L_6; L_6 = Time_get_deltaTime_mCC15F147DA67F38C74CE408FB5D7FF4A87DA2290(/*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_7; L_7 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_5, L_6, /*hidden argument*/NULL); float L_8 = __this->get_movingSpeed_7(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_9; L_9 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_7, L_8, /*hidden argument*/NULL); Transform_Translate_mFB58CBF3FA00BD0EE09EC67457608F62564D0DDE(L_0, L_9, 0, /*hidden argument*/NULL); // score += 1; int32_t L_10 = __this->get_score_9(); __this->set_score_9(((int32_t)il2cpp_codegen_add((int32_t)L_10, (int32_t)1))); // if (mainCamera.WorldToViewportPoint(spawnedTiles[0].endPoint.position).z < 0) Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_11 = __this->get_mainCamera_4(); List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * L_12 = __this->get_spawnedTiles_10(); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_13; L_13 = List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_inline(L_12, 0, /*hidden argument*/List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_RuntimeMethod_var); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_14 = L_13->get_endPoint_5(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_15; L_15 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_14, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_16; L_16 = Camera_WorldToViewportPoint_m656CDAE26AAC040A4A47DAFF8EEDB0A941BE051D(L_11, L_15, /*hidden argument*/NULL); float L_17 = L_16.get_z_4(); if ((!(((float)L_17) < ((float)(0.0f))))) { goto IL_00df; } } { // EnvironmentTiling tileTmp = spawnedTiles[0]; List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * L_18 = __this->get_spawnedTiles_10(); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_19; L_19 = List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_inline(L_18, 0, /*hidden argument*/List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_RuntimeMethod_var); V_0 = L_19; // spawnedTiles.RemoveAt(0); List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * L_20 = __this->get_spawnedTiles_10(); List_1_RemoveAt_m6839717CCA2768D5DF8850CF9C896D0D4B223F3B(L_20, 0, /*hidden argument*/List_1_RemoveAt_m6839717CCA2768D5DF8850CF9C896D0D4B223F3B_RuntimeMethod_var); // tileTmp.transform.position = spawnedTiles[spawnedTiles.Count - 1].endPoint.position - tileTmp.startPoint.localPosition; EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_21 = V_0; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_22; L_22 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_21, /*hidden argument*/NULL); List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * L_23 = __this->get_spawnedTiles_10(); List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * L_24 = __this->get_spawnedTiles_10(); int32_t L_25; L_25 = List_1_get_Count_mC0B6C3963C8EDEC72D02B324F705A66C9C6BB19C_inline(L_24, /*hidden argument*/List_1_get_Count_mC0B6C3963C8EDEC72D02B324F705A66C9C6BB19C_RuntimeMethod_var); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_26; L_26 = List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_inline(L_23, ((int32_t)il2cpp_codegen_subtract((int32_t)L_25, (int32_t)1)), /*hidden argument*/List_1_get_Item_m6BA5281C5A888FC63308B58405EE991E729B1E16_RuntimeMethod_var); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_27 = L_26->get_endPoint_5(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_28; L_28 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_27, /*hidden argument*/NULL); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_29 = V_0; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_30 = L_29->get_startPoint_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_31; L_31 = Transform_get_localPosition_m527B8B5B625DA9A61E551E0FBCD3BE8CA4539FC2(L_30, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_32; L_32 = Vector3_op_Subtraction_m2725C96965D5C0B1F9715797E51762B13A5FED58_inline(L_28, L_31, /*hidden argument*/NULL); Transform_set_position_mB169E52D57EEAC1E3F22C5395968714E4F00AC91(L_22, L_32, /*hidden argument*/NULL); // tileTmp.ActivateCorridor(); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_33 = V_0; EnvironmentTiling_ActivateCorridor_m4A158ED61356D3521485976518BA96A4B134CC60(L_33, /*hidden argument*/NULL); // spawnedTiles.Add(tileTmp); List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * L_34 = __this->get_spawnedTiles_10(); EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * L_35 = V_0; List_1_Add_m9DD38E1D935506058FC2E3F3760DB0717097CEDB(L_34, L_35, /*hidden argument*/List_1_Add_m9DD38E1D935506058FC2E3F3760DB0717097CEDB_RuntimeMethod_var); } IL_00df: { // } return; } } // System.Void EnvironmentGenerator::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EnvironmentGenerator__ctor_mA22EA18C2912700B1986350200F4E073A2ECD256 (EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_m92E7452A54F62BF12651BB65E9ABFCE56433C579_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { // public float movingSpeed = 10; __this->set_movingSpeed_7((10.0f)); // List<EnvironmentTiling> spawnedTiles = new List<EnvironmentTiling>(); List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB * L_0 = (List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB *)il2cpp_codegen_object_new(List_1_tFCFD4AC2773BB1280BAC72F74430625A222F7ADB_il2cpp_TypeInfo_var); List_1__ctor_m92E7452A54F62BF12651BB65E9ABFCE56433C579(L_0, /*hidden argument*/List_1__ctor_m92E7452A54F62BF12651BB65E9ABFCE56433C579_RuntimeMethod_var); __this->set_spawnedTiles_10(L_0); MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void EnvironmentTiling::ActivateCorridor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EnvironmentTiling_ActivateCorridor_m4A158ED61356D3521485976518BA96A4B134CC60 (EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; { // System.Random random = new System.Random(); Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118 * L_0 = (Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118 *)il2cpp_codegen_object_new(Random_t6C9E9775A149D0ADCFEB4B252C408F03EE870118_il2cpp_TypeInfo_var); Random__ctor_mF40AD1812BABC06235B661CCE513E4F74EEE9F05(L_0, /*hidden argument*/NULL); // int randomNumber = random.Next(0, corridor.Length); GameObjectU5BU5D_tA88FC1A1FC9D4D73D0B3984D4B0ECE88F4C47642* L_1 = __this->get_corridor_6(); int32_t L_2; L_2 = VirtFuncInvoker2< int32_t, int32_t, int32_t >::Invoke(5 /* System.Int32 System.Random::Next(System.Int32,System.Int32) */, L_0, 0, ((int32_t)((int32_t)(((RuntimeArray*)L_1)->max_length)))); V_0 = L_2; // corridor[randomNumber].SetActive(true); GameObjectU5BU5D_tA88FC1A1FC9D4D73D0B3984D4B0ECE88F4C47642* L_3 = __this->get_corridor_6(); int32_t L_4 = V_0; int32_t L_5 = L_4; GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_6 = (L_3)->GetAtUnchecked(static_cast<il2cpp_array_size_t>(L_5)); GameObject_SetActive_mCF1EEF2A314F3AE85DA581FF52EB06ACEF2FFF86(L_6, (bool)1, /*hidden argument*/NULL); // } return; } } // System.Void EnvironmentTiling::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void EnvironmentTiling__ctor_m3BADD9213125A58F90C19BF5ABE3D570488D765B (EnvironmentTiling_t4B31CCBDB791588DC10F889D1F63E6351961F3CE * __this, const RuntimeMethod* method) { { MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void GameOverScreen::ScoreSetup(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void GameOverScreen_ScoreSetup_m77E8D24D02B018BB207656638DF3EFBF237A768F (GameOverScreen_t66B7C93D73D16C603457FEA3A5424F7DDB6B68A7 * __this, int32_t ___score0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralED35FF3F063D29A026AE09F18392D9C7537823F2); s_Il2CppMethodInitialized = true; } { // scoreText.text = "SCORE: " + EnvironmentGenerator.instance.score.ToString(); Text_t6A2339DA6C05AE2646FC1A6C8FCC127391BE7FA1 * L_0 = __this->get_scoreText_4(); EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D * L_1 = ((EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D_StaticFields*)il2cpp_codegen_static_fields_for(EnvironmentGenerator_t2E16799A6AEC0877E11CE92427E258F6691CC17D_il2cpp_TypeInfo_var))->get_instance_11(); int32_t* L_2 = L_1->get_address_of_score_9(); String_t* L_3; L_3 = Int32_ToString_m340C0A14D16799421EFDF8A81C8A16FA76D48411((int32_t*)L_2, /*hidden argument*/NULL); String_t* L_4; L_4 = String_Concat_m4B4AB72618348C5DFBFBA8DED84B9E2EBDB55E1B(_stringLiteralED35FF3F063D29A026AE09F18392D9C7537823F2, L_3, /*hidden argument*/NULL); VirtActionInvoker1< String_t* >::Invoke(75 /* System.Void UnityEngine.UI.Text::set_text(System.String) */, L_0, L_4); // } return; } } // System.Void GameOverScreen::Restart() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void GameOverScreen_Restart_m2986624D742F5C4456A3F6013AF115FE88FA0660 (GameOverScreen_t66B7C93D73D16C603457FEA3A5424F7DDB6B68A7 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralC83B6926DE498999BC7E3D5467A98CDE9B139901); s_Il2CppMethodInitialized = true; } { // SceneManager.LoadScene("Level1"); IL2CPP_RUNTIME_CLASS_INIT(SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); SceneManager_LoadScene_m7DAF30213E99396ECBDB1BD40CC34CCF36902092(_stringLiteralC83B6926DE498999BC7E3D5467A98CDE9B139901, /*hidden argument*/NULL); // } return; } } // System.Void GameOverScreen::MainMenu() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void GameOverScreen_MainMenu_m86003623895F8ABC194E55B614EFCD4E561D06DA (GameOverScreen_t66B7C93D73D16C603457FEA3A5424F7DDB6B68A7 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral000E6F488C4BFBAD929A9ED558662797D830E719); s_Il2CppMethodInitialized = true; } { // SceneManager.LoadScene("MainMenu"); IL2CPP_RUNTIME_CLASS_INIT(SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); SceneManager_LoadScene_m7DAF30213E99396ECBDB1BD40CC34CCF36902092(_stringLiteral000E6F488C4BFBAD929A9ED558662797D830E719, /*hidden argument*/NULL); // } return; } } // System.Void GameOverScreen::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void GameOverScreen__ctor_mE9F89EF0E4A9BFE845256528F4FDE19F075BCD95 (GameOverScreen_t66B7C93D73D16C603457FEA3A5424F7DDB6B68A7 * __this, const RuntimeMethod* method) { { MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void MainMenu::Play() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainMenu_Play_m2149EC8228ACC7B581B979DB27BCE127F5EBD2B9 (MainMenu_tEB11F5A993C42E93B585FBB65C9E92EC91C5707C * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralC83B6926DE498999BC7E3D5467A98CDE9B139901); s_Il2CppMethodInitialized = true; } { // SceneManager.LoadScene("Level1"); IL2CPP_RUNTIME_CLASS_INIT(SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); SceneManager_LoadScene_m7DAF30213E99396ECBDB1BD40CC34CCF36902092(_stringLiteralC83B6926DE498999BC7E3D5467A98CDE9B139901, /*hidden argument*/NULL); // } return; } } // System.Void MainMenu::Credits() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainMenu_Credits_m9C985FEF5E2D0CB5C1E31BB67665B4A15ABBF963 (MainMenu_tEB11F5A993C42E93B585FBB65C9E92EC91C5707C * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral5C058FE20FD7652D620A17B5F9D6AE4EEFA76795); s_Il2CppMethodInitialized = true; } { // SceneManager.LoadScene("Credits"); IL2CPP_RUNTIME_CLASS_INIT(SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); SceneManager_LoadScene_m7DAF30213E99396ECBDB1BD40CC34CCF36902092(_stringLiteral5C058FE20FD7652D620A17B5F9D6AE4EEFA76795, /*hidden argument*/NULL); // } return; } } // System.Void MainMenu::Quit() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainMenu_Quit_m65E045D8746B583667D2641184783FDD7796758A (MainMenu_tEB11F5A993C42E93B585FBB65C9E92EC91C5707C * __this, const RuntimeMethod* method) { { // Application.Quit(); Application_Quit_m8D720E5092786C2EE32310D85FE61C253D3B1F2A(/*hidden argument*/NULL); // } return; } } // System.Void MainMenu::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MainMenu__ctor_m4D77CEC8F91682A2D9492AE815F89B178BF9717D (MainMenu_tEB11F5A993C42E93B585FBB65C9E92EC91C5707C * __this, const RuntimeMethod* method) { { MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void ObstacleMove::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ObstacleMove_Start_mE77C89D9B2FE4AF554FF4F30FA779DC3E2482636 (ObstacleMove_tCA8BCDF4E1470FF52591F02A0E20D6091EB614DC * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { // Destroy(gameObject, 6f); GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_0; L_0 = Component_get_gameObject_m55DC35B149AFB9157582755383BA954655FE0C5B(__this, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); Object_Destroy_mAAAA103F4911E9FA18634BF9605C28559F5E2AC7(L_0, (6.0f), /*hidden argument*/NULL); // } return; } } // System.Void ObstacleMove::Update() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ObstacleMove_Update_mE4B79D78456499B3A27CA980B09D995F557C0EF5 (ObstacleMove_tCA8BCDF4E1470FF52591F02A0E20D6091EB614DC * __this, const RuntimeMethod* method) { { // transform.Translate(Vector3.back * Time.deltaTime * movingSpeed, Space.World); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_0; L_0 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_1; L_1 = Vector3_get_back_mD521DF1A2C26E145578E07D618E1E4D08A1C6220(/*hidden argument*/NULL); float L_2; L_2 = Time_get_deltaTime_mCC15F147DA67F38C74CE408FB5D7FF4A87DA2290(/*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_3; L_3 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_1, L_2, /*hidden argument*/NULL); float L_4 = __this->get_movingSpeed_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_5; L_5 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_3, L_4, /*hidden argument*/NULL); Transform_Translate_mFB58CBF3FA00BD0EE09EC67457608F62564D0DDE(L_0, L_5, 0, /*hidden argument*/NULL); // } return; } } // System.Void ObstacleMove::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ObstacleMove__ctor_m9ABAFED61C7CF65CA4BDE79F6B7606B1B0E38309 (ObstacleMove_tCA8BCDF4E1470FF52591F02A0E20D6091EB614DC * __this, const RuntimeMethod* method) { { // public float movingSpeed = 10; __this->set_movingSpeed_4((10.0f)); MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void ObstacleSpawner::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ObstacleSpawner_Start_mBD8A272A8EEAD54E0988D0AE0D7663548DA0C745 (ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * __this, const RuntimeMethod* method) { { // StartCoroutine(SpawnerCoroutine()); RuntimeObject* L_0; L_0 = ObstacleSpawner_SpawnerCoroutine_m4DFA5FB411ADFAF0AC803A49901A8725D75641F8(__this, /*hidden argument*/NULL); Coroutine_t899D5232EF542CB8BA70AF9ECEECA494FAA9CCB7 * L_1; L_1 = MonoBehaviour_StartCoroutine_m3E33706D38B23CDD179E99BAD61E32303E9CC719(__this, L_0, /*hidden argument*/NULL); // } return; } } // System.Collections.IEnumerator ObstacleSpawner::SpawnerCoroutine() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject* ObstacleSpawner_SpawnerCoroutine_m4DFA5FB411ADFAF0AC803A49901A8725D75641F8 (ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 * L_0 = (U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 *)il2cpp_codegen_object_new(U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75_il2cpp_TypeInfo_var); U3CSpawnerCoroutineU3Ed__4__ctor_m00AB12936ACCDE67EAED4471CD2C5A91D17BF5CF(L_0, 0, /*hidden argument*/NULL); U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 * L_1 = L_0; L_1->set_U3CU3E4__this_2(__this); return L_1; } } // System.Void ObstacleSpawner::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void ObstacleSpawner__ctor_m347D7FB8C7FAEB149F02F9A147EE7E51A28F57ED (ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * __this, const RuntimeMethod* method) { { MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void PlayVideo::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PlayVideo_Start_m96145A3223FEC1254BD1D542C64BCA11B2969F22 (PlayVideo_tD3F8CE49495C7017FEF089C05BC6D56CA20A3E98 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&GameObject_GetComponent_TisVideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86_mE0279031C6B378280F6E848C495D87D03F1647B2_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Path_tF1D95B78D57C1C1211BA6633FF2AC22FD6C48921_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { // videoPlayer = gameObject.GetComponent<VideoPlayer>(); GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_0; L_0 = Component_get_gameObject_m55DC35B149AFB9157582755383BA954655FE0C5B(__this, /*hidden argument*/NULL); VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * L_1; L_1 = GameObject_GetComponent_TisVideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86_mE0279031C6B378280F6E848C495D87D03F1647B2(L_0, /*hidden argument*/GameObject_GetComponent_TisVideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86_mE0279031C6B378280F6E848C495D87D03F1647B2_RuntimeMethod_var); __this->set_videoPlayer_4(L_1); // videoPlayer.url = System.IO.Path.Combine(Application.streamingAssetsPath, nomVideo); VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * L_2 = __this->get_videoPlayer_4(); String_t* L_3; L_3 = Application_get_streamingAssetsPath_mA1FBABB08D7A4590A468C7CD940CD442B58C91E1(/*hidden argument*/NULL); String_t* L_4 = __this->get_nomVideo_5(); IL2CPP_RUNTIME_CLASS_INIT(Path_tF1D95B78D57C1C1211BA6633FF2AC22FD6C48921_il2cpp_TypeInfo_var); String_t* L_5; L_5 = Path_Combine_mC22E47A9BB232F02ED3B6B5F6DD53338D37782EF(L_3, L_4, /*hidden argument*/NULL); VideoPlayer_set_url_m9C9942D6C54D50F6255A2AA1646D9F40E551BF13(L_2, L_5, /*hidden argument*/NULL); // videoPlayer.Play(); VideoPlayer_t47DCC396CBA28512CF97C6CC4F55878E8D62FE86 * L_6 = __this->get_videoPlayer_4(); VideoPlayer_Play_m2AD0D39D70055A5AADCF63430D3D9CEC7DCB0516(L_6, /*hidden argument*/NULL); // } return; } } // System.Void PlayVideo::Update() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PlayVideo_Update_m3548AFDC6F608BEEBCE2B732BBB5A24DAD098F6B (PlayVideo_tD3F8CE49495C7017FEF089C05BC6D56CA20A3E98 * __this, const RuntimeMethod* method) { { // } return; } } // System.Void PlayVideo::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PlayVideo__ctor_mBAE85B15D751315571F6A0E1A677257B6E728C50 (PlayVideo_tD3F8CE49495C7017FEF089C05BC6D56CA20A3E98 * __this, const RuntimeMethod* method) { { MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void Player::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Player_Start_mBD692B64AAC791B93A589E7D3596F36787EAF021 (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Component_GetComponent_TisRigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A_m9DC24AA806B0B65E917751F7A3AFDB58861157CE_RuntimeMethod_var); s_Il2CppMethodInitialized = true; } { // rb = GetComponent<Rigidbody>(); Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * L_0; L_0 = Component_GetComponent_TisRigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A_m9DC24AA806B0B65E917751F7A3AFDB58861157CE(__this, /*hidden argument*/Component_GetComponent_TisRigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A_m9DC24AA806B0B65E917751F7A3AFDB58861157CE_RuntimeMethod_var); __this->set_rb_7(L_0); // rb.constraints = RigidbodyConstraints.FreezePositionZ; Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * L_1 = __this->get_rb_7(); Rigidbody_set_constraints_mA76F562D16D3BE8889E095D0309C8FE38DA914F1(L_1, 8, /*hidden argument*/NULL); // rb.freezeRotation = true; Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * L_2 = __this->get_rb_7(); Rigidbody_set_freezeRotation_mE08A39E98D46F82D6DD86CC389D86D242C694D52(L_2, (bool)1, /*hidden argument*/NULL); // rb.useGravity = false; Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * L_3 = __this->get_rb_7(); Rigidbody_set_useGravity_m1057292FB3199E87664F40B8BCBA7A7E64D1A096(L_3, (bool)0, /*hidden argument*/NULL); // defaultScale = transform.localScale; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_4; L_4 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_5; L_5 = Transform_get_localScale_mD9DF6CA81108C2A6002B5EA2BE25A6CD2723D046(L_4, /*hidden argument*/NULL); __this->set_defaultScale_9(L_5); // } return; } } // System.Void Player::Update() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Player_Update_mBA04F1D6FE3C18037EA95DFAEEAA9977BFD49CD3 (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral0A04B971B03DA607CE6C455184037B660CA89F78); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral8739227E8E687EF781DA0D923452C2686CFF10A2); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralA02431CF7C501A5B368C91E41283419D8FA9FB03); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralB1E5119D36EC43B340C0A0DDC99F1156546EA9DF); s_Il2CppMethodInitialized = true; } { // if (Input.GetKeyDown(KeyCode.Space) && grounded) bool L_0; L_0 = Input_GetKeyDown_m476116696E71771641BBECBAB1A4C55E69018220(((int32_t)32), /*hidden argument*/NULL); if (!L_0) { goto IL_004e; } } { bool L_1 = __this->get_grounded_8(); if (!L_1) { goto IL_004e; } } { // rb.velocity = new Vector3(rb.velocity.x, CalculateJumpVerticalSpeed(), rb.velocity.z); Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * L_2 = __this->get_rb_7(); Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * L_3 = __this->get_rb_7(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_4; L_4 = Rigidbody_get_velocity_mCFB033F3BD14C2BA68E797DFA4950F9307EC8E2C(L_3, /*hidden argument*/NULL); float L_5 = L_4.get_x_2(); float L_6; L_6 = Player_CalculateJumpVerticalSpeed_mA671C584D141496A5A4E71A3294CE34FCCC44AD5(__this, /*hidden argument*/NULL); Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * L_7 = __this->get_rb_7(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_8; L_8 = Rigidbody_get_velocity_mCFB033F3BD14C2BA68E797DFA4950F9307EC8E2C(L_7, /*hidden argument*/NULL); float L_9 = L_8.get_z_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_10; memset((&L_10), 0, sizeof(L_10)); Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_10), L_5, L_6, L_9, /*hidden argument*/NULL); Rigidbody_set_velocity_m8DC0988916EB38DFD7D4584830B41D79140BF18D(L_2, L_10, /*hidden argument*/NULL); // grounded = false; __this->set_grounded_8((bool)0); } IL_004e: { // if (Input.GetKey("left") || Input.GetKey("a")) bool L_11; L_11 = Input_GetKey_m77E2F3719EC63690632731872A691FF6A27C589C(_stringLiteral8739227E8E687EF781DA0D923452C2686CFF10A2, /*hidden argument*/NULL); if (L_11) { goto IL_0066; } } { bool L_12; L_12 = Input_GetKey_m77E2F3719EC63690632731872A691FF6A27C589C(_stringLiteral0A04B971B03DA607CE6C455184037B660CA89F78, /*hidden argument*/NULL); if (!L_12) { goto IL_008b; } } IL_0066: { // transform.Translate(Vector3.left * Time.deltaTime * movementSpeed); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_13; L_13 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_14; L_14 = Vector3_get_left_mDAB848C352B9D30E2DDDA7F56308ABC32A4315A5(/*hidden argument*/NULL); float L_15; L_15 = Time_get_deltaTime_mCC15F147DA67F38C74CE408FB5D7FF4A87DA2290(/*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_16; L_16 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_14, L_15, /*hidden argument*/NULL); float L_17 = __this->get_movementSpeed_6(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_18; L_18 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_16, L_17, /*hidden argument*/NULL); Transform_Translate_m24A8CB13E2AAB0C17EE8FE593266CF463E0B02D0(L_13, L_18, /*hidden argument*/NULL); } IL_008b: { // if (Input.GetKey("right") || Input.GetKey("d")) bool L_19; L_19 = Input_GetKey_m77E2F3719EC63690632731872A691FF6A27C589C(_stringLiteralB1E5119D36EC43B340C0A0DDC99F1156546EA9DF, /*hidden argument*/NULL); if (L_19) { goto IL_00a3; } } { bool L_20; L_20 = Input_GetKey_m77E2F3719EC63690632731872A691FF6A27C589C(_stringLiteralA02431CF7C501A5B368C91E41283419D8FA9FB03, /*hidden argument*/NULL); if (!L_20) { goto IL_00c8; } } IL_00a3: { // transform.Translate(Vector3.right * Time.deltaTime * movementSpeed); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_21; L_21 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_22; L_22 = Vector3_get_right_mF5A51F81961474E0A7A31C2757FD00921FB79C44(/*hidden argument*/NULL); float L_23; L_23 = Time_get_deltaTime_mCC15F147DA67F38C74CE408FB5D7FF4A87DA2290(/*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_24; L_24 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_22, L_23, /*hidden argument*/NULL); float L_25 = __this->get_movementSpeed_6(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_26; L_26 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_24, L_25, /*hidden argument*/NULL); Transform_Translate_m24A8CB13E2AAB0C17EE8FE593266CF463E0B02D0(L_21, L_26, /*hidden argument*/NULL); } IL_00c8: { // transform.position = new Vector3(Mathf.Clamp(transform.position.x, -1.5f, 1.5f), transform.position.y, 0); //rajottaa sivuttaisliikkeen m��r�� ettei mee kent�n "yli" Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_27; L_27 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_28; L_28 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_29; L_29 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_28, /*hidden argument*/NULL); float L_30 = L_29.get_x_2(); float L_31; L_31 = Mathf_Clamp_m2416F3B785C8F135863E3D17E5B0CB4174797B87(L_30, (-1.5f), (1.5f), /*hidden argument*/NULL); Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_32; L_32 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(__this, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_33; L_33 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_32, /*hidden argument*/NULL); float L_34 = L_33.get_y_3(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_35; memset((&L_35), 0, sizeof(L_35)); Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_35), L_31, L_34, (0.0f), /*hidden argument*/NULL); Transform_set_position_mB169E52D57EEAC1E3F22C5395968714E4F00AC91(L_27, L_35, /*hidden argument*/NULL); // } return; } } // System.Void Player::FixedUpdate() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Player_FixedUpdate_mD7447EDFC86F29A3E5FBDEF7E0139535BD4C5088 (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, const RuntimeMethod* method) { { // rb.AddForce(new Vector3(0, -gravity * rb.mass, 0)); Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * L_0 = __this->get_rb_7(); float L_1 = __this->get_gravity_4(); Rigidbody_t101F2E2F9F16E765A77429B2DE4527D2047A887A * L_2 = __this->get_rb_7(); float L_3; L_3 = Rigidbody_get_mass_mB7B19406DAC6336A8244E98BE271BDA8B5C26223(L_2, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_4; memset((&L_4), 0, sizeof(L_4)); Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_4), (0.0f), ((float)il2cpp_codegen_multiply((float)((-L_1)), (float)L_3)), (0.0f), /*hidden argument*/NULL); Rigidbody_AddForce_mDFB0D57C25682B826999B0074F5C0FD399C6401D(L_0, L_4, /*hidden argument*/NULL); // grounded = false; __this->set_grounded_8((bool)0); // } return; } } // System.Void Player::OnCollisionStay() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Player_OnCollisionStay_mB00D04AB497C62711DECF8803DE77F16C4E007B0 (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, const RuntimeMethod* method) { { // grounded = true; __this->set_grounded_8((bool)1); // } return; } } // System.Single Player::CalculateJumpVerticalSpeed() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Player_CalculateJumpVerticalSpeed_mA671C584D141496A5A4E71A3294CE34FCCC44AD5 (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, const RuntimeMethod* method) { { // return Mathf.Sqrt(2 * jumpHeight * gravity); float L_0 = __this->get_jumpHeight_5(); float L_1 = __this->get_gravity_4(); float L_2; L_2 = sqrtf(((float)il2cpp_codegen_multiply((float)((float)il2cpp_codegen_multiply((float)(2.0f), (float)L_0)), (float)L_1))); return L_2; } } // System.Void Player::OnCollisionEnter(UnityEngine.Collision) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Player_OnCollisionEnter_mC2785602469BC029A5E804A22D83459ECE1C42BE (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0 * ___collision0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralF59B8D72542CE7CA46EF3732C2A3A46BB5B8EF20); s_Il2CppMethodInitialized = true; } { // if (collision.gameObject.CompareTag("Table")) Collision_tDC11F9B3834FD25DEB8C7DD1C51B635D240BBBF0 * L_0 = ___collision0; GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_1; L_1 = Collision_get_gameObject_m5682F872FD28419AA36F0651CE8B19825A21859D(L_0, /*hidden argument*/NULL); bool L_2; L_2 = GameObject_CompareTag_mA692D8508984DBE4A2FEFD19E29CB1C9D5CDE001(L_1, _stringLiteralF59B8D72542CE7CA46EF3732C2A3A46BB5B8EF20, /*hidden argument*/NULL); if (!L_2) { goto IL_0018; } } { // Die(); Player_Die_m16A200929DBDF9FF88C8191A26327C2CCCC80C19(__this, /*hidden argument*/NULL); } IL_0018: { // } return; } } // System.Void Player::Die() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Player_Die_m16A200929DBDF9FF88C8191A26327C2CCCC80C19 (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteralC62B61BC27E509D700023566A09D2AE606BE85A7); s_Il2CppMethodInitialized = true; } { // SceneManager.LoadScene("GameOver"); IL2CPP_RUNTIME_CLASS_INIT(SceneManager_tEC9D10ECC0377F8AE5AEEB5A789FFD24364440FA_il2cpp_TypeInfo_var); SceneManager_LoadScene_m7DAF30213E99396ECBDB1BD40CC34CCF36902092(_stringLiteralC62B61BC27E509D700023566A09D2AE606BE85A7, /*hidden argument*/NULL); // } return; } } // System.Void Player::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Player__ctor_mDE8EB5B351975D4E7E24DE341B8B49B8A29CC2B7 (Player_t5689617909B48F7640EA0892D85C92C13CC22C6F * __this, const RuntimeMethod* method) { { // public float gravity = 20.0f; __this->set_gravity_4((20.0f)); // public float jumpHeight = 2.5f; __this->set_jumpHeight_5((2.5f)); MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void PlayerMotor::Start() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PlayerMotor_Start_mE33AFBCA4469F39BAD92F136838FAC1970470FD6 (PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Component_GetComponent_TisCharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E_m3DB1DD5819F96D7C7F6F19C12138AC48D21DBBF2_RuntimeMethod_var); s_Il2CppMethodInitialized = true; } { // controller = GetComponent<CharacterController>(); CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * L_0; L_0 = Component_GetComponent_TisCharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E_m3DB1DD5819F96D7C7F6F19C12138AC48D21DBBF2(__this, /*hidden argument*/Component_GetComponent_TisCharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E_m3DB1DD5819F96D7C7F6F19C12138AC48D21DBBF2_RuntimeMethod_var); __this->set_controller_4(L_0); // } return; } } // System.Void PlayerMotor::Update() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PlayerMotor_Update_m2B85C51BB405823DBA4EF969244010E1CF7D3349 (PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral7F8C014BD4810CC276D0F9F81A1E759C7B098B1E); s_Il2CppMethodInitialized = true; } { // moveVector = Vector3.zero; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_0; L_0 = Vector3_get_zero_m1A8F7993167785F750B6B01762D22C2597C84EF6(/*hidden argument*/NULL); __this->set_moveVector_5(L_0); // if (controller.isGrounded) CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * L_1 = __this->get_controller_4(); bool L_2; L_2 = CharacterController_get_isGrounded_m327A1A1940F225FE81E751F255316BB0D8698CBC(L_1, /*hidden argument*/NULL); if (!L_2) { goto IL_0025; } } { // verticalVelocity = -0.5f; __this->set_verticalVelocity_7((-0.5f)); // } goto IL_003e; } IL_0025: { // verticalVelocity -= gravity * Time.deltaTime; float L_3 = __this->get_verticalVelocity_7(); float L_4 = __this->get_gravity_8(); float L_5; L_5 = Time_get_deltaTime_mCC15F147DA67F38C74CE408FB5D7FF4A87DA2290(/*hidden argument*/NULL); __this->set_verticalVelocity_7(((float)il2cpp_codegen_subtract((float)L_3, (float)((float)il2cpp_codegen_multiply((float)L_4, (float)L_5))))); } IL_003e: { // moveVector.x = Input.GetAxisRaw("Horizontal") * speed; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * L_6 = __this->get_address_of_moveVector_5(); float L_7; L_7 = Input_GetAxisRaw_mC07AC23FD8D04A69CDB07C6399C93FFFAEB0FC5B(_stringLiteral7F8C014BD4810CC276D0F9F81A1E759C7B098B1E, /*hidden argument*/NULL); float L_8 = __this->get_speed_6(); L_6->set_x_2(((float)il2cpp_codegen_multiply((float)L_7, (float)L_8))); // moveVector.y = verticalVelocity; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * L_9 = __this->get_address_of_moveVector_5(); float L_10 = __this->get_verticalVelocity_7(); L_9->set_y_3(L_10); // moveVector.z = speed; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * L_11 = __this->get_address_of_moveVector_5(); float L_12 = __this->get_speed_6(); L_11->set_z_4(L_12); // controller.Move(moveVector * Time.deltaTime); CharacterController_tCCF68621C784CCB3391E0C66FE134F6F93DD6C2E * L_13 = __this->get_controller_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_14 = __this->get_moveVector_5(); float L_15; L_15 = Time_get_deltaTime_mCC15F147DA67F38C74CE408FB5D7FF4A87DA2290(/*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_16; L_16 = Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline(L_14, L_15, /*hidden argument*/NULL); int32_t L_17; L_17 = CharacterController_Move_mE0EBC32C72A0BEC18EDEBE748D44309A4BA32E60(L_13, L_16, /*hidden argument*/NULL); // } return; } } // System.Void PlayerMotor::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PlayerMotor__ctor_m69F6DC58548EA8671F5A04801ADAB3D5F22D5E7E (PlayerMotor_t039BA96D1334B84759F4CF89C1845D324B181B52 * __this, const RuntimeMethod* method) { { // private float speed = 5.0f; __this->set_speed_6((5.0f)); // private float gravity = 12.0f; __this->set_gravity_8((12.0f)); MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void DoorGenerator/<SpawnerCoroutine1>d__4::.ctor(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CSpawnerCoroutine1U3Ed__4__ctor_mF876BFA52EBF1DBCBBEF1A73AC898ECE915EE7EB (U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A * __this, int32_t ___U3CU3E1__state0, const RuntimeMethod* method) { { Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405(__this, /*hidden argument*/NULL); int32_t L_0 = ___U3CU3E1__state0; __this->set_U3CU3E1__state_0(L_0); return; } } // System.Void DoorGenerator/<SpawnerCoroutine1>d__4::System.IDisposable.Dispose() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CSpawnerCoroutine1U3Ed__4_System_IDisposable_Dispose_mF3CC80BC28E1B5ADB05A1F24EDF1B4B2944C1D54 (U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A * __this, const RuntimeMethod* method) { { return; } } // System.Boolean DoorGenerator/<SpawnerCoroutine1>d__4::MoveNext() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool U3CSpawnerCoroutine1U3Ed__4_MoveNext_m2BD59AC0FB7960F05823B6BEC9E6505916FEACBF (U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * V_1 = NULL; { int32_t L_0 = __this->get_U3CU3E1__state_0(); V_0 = L_0; DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_1 = __this->get_U3CU3E4__this_2(); V_1 = L_1; int32_t L_2 = V_0; switch (L_2) { case 0: { goto IL_0022; } case 1: { goto IL_0053; } case 2: { goto IL_00c0; } } } { return (bool)0; } IL_0022: { __this->set_U3CU3E1__state_0((-1)); goto IL_0108; } IL_002e: { // yield return new WaitForSeconds(Random.Range(waitSecondsMin, waitSecondsMax)); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_3 = V_1; float L_4 = L_3->get_waitSecondsMin_5(); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_5 = V_1; float L_6 = L_5->get_waitSecondsMax_6(); float L_7; L_7 = Random_Range_mC15372D42A9ABDCAC3DE82E114D60A40C9C311D2(L_4, L_6, /*hidden argument*/NULL); WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013 * L_8 = (WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013 *)il2cpp_codegen_object_new(WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013_il2cpp_TypeInfo_var); WaitForSeconds__ctor_mD298C4CB9532BBBDE172FC40F3397E30504038D4(L_8, L_7, /*hidden argument*/NULL); __this->set_U3CU3E2__current_1(L_8); __this->set_U3CU3E1__state_0(1); return (bool)1; } IL_0053: { __this->set_U3CU3E1__state_0((-1)); // Instantiate(door, new Vector3(2f, transform.position.y, transform.position.z), transform.rotation); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_9 = V_1; GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_10 = L_9->get_door_4(); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_11 = V_1; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_12; L_12 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_11, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_13; L_13 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_12, /*hidden argument*/NULL); float L_14 = L_13.get_y_3(); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_15 = V_1; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_16; L_16 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_15, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_17; L_17 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_16, /*hidden argument*/NULL); float L_18 = L_17.get_z_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_19; memset((&L_19), 0, sizeof(L_19)); Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_19), (2.0f), L_14, L_18, /*hidden argument*/NULL); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_20 = V_1; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_21; L_21 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_20, /*hidden argument*/NULL); Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 L_22; L_22 = Transform_get_rotation_m4AA3858C00DF4C9614B80352558C4C37D08D2200(L_21, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_23; L_23 = Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B(L_10, L_19, L_22, /*hidden argument*/Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B_RuntimeMethod_var); // yield return new WaitForSeconds(Random.Range(waitSecondsMin, waitSecondsMax)); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_24 = V_1; float L_25 = L_24->get_waitSecondsMin_5(); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_26 = V_1; float L_27 = L_26->get_waitSecondsMax_6(); float L_28; L_28 = Random_Range_mC15372D42A9ABDCAC3DE82E114D60A40C9C311D2(L_25, L_27, /*hidden argument*/NULL); WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013 * L_29 = (WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013 *)il2cpp_codegen_object_new(WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013_il2cpp_TypeInfo_var); WaitForSeconds__ctor_mD298C4CB9532BBBDE172FC40F3397E30504038D4(L_29, L_28, /*hidden argument*/NULL); __this->set_U3CU3E2__current_1(L_29); __this->set_U3CU3E1__state_0(2); return (bool)1; } IL_00c0: { __this->set_U3CU3E1__state_0((-1)); // Instantiate(door, new Vector3(-2f, transform.position.y, transform.position.z), transform.rotation); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_30 = V_1; GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_31 = L_30->get_door_4(); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_32 = V_1; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_33; L_33 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_32, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_34; L_34 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_33, /*hidden argument*/NULL); float L_35 = L_34.get_y_3(); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_36 = V_1; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_37; L_37 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_36, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_38; L_38 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_37, /*hidden argument*/NULL); float L_39 = L_38.get_z_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_40; memset((&L_40), 0, sizeof(L_40)); Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_40), (-2.0f), L_35, L_39, /*hidden argument*/NULL); DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_41 = V_1; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_42; L_42 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_41, /*hidden argument*/NULL); Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 L_43; L_43 = Transform_get_rotation_m4AA3858C00DF4C9614B80352558C4C37D08D2200(L_42, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_44; L_44 = Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B(L_31, L_40, L_43, /*hidden argument*/Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B_RuntimeMethod_var); } IL_0108: { // while (enabled) DoorGenerator_t1AD1986ED1FAA3F082E4B29168064ECBA8C27136 * L_45 = V_1; bool L_46; L_46 = Behaviour_get_enabled_m08077AB79934634E1EAE909C2B482BEF4C15A800(L_45, /*hidden argument*/NULL); if (L_46) { goto IL_002e; } } { // } return (bool)0; } } // System.Object DoorGenerator/<SpawnerCoroutine1>d__4::System.Collections.Generic.IEnumerator<System.Object>.get_Current() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * U3CSpawnerCoroutine1U3Ed__4_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m53440945F615B9FD629A17723AE00B3285569A78 (U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = __this->get_U3CU3E2__current_1(); return L_0; } } // System.Void DoorGenerator/<SpawnerCoroutine1>d__4::System.Collections.IEnumerator.Reset() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CSpawnerCoroutine1U3Ed__4_System_Collections_IEnumerator_Reset_mC693C89E69AB6F0008DCCFD9CFBA6B89215EA69E (U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A * __this, const RuntimeMethod* method) { { NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339 * L_0 = (NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339 *)il2cpp_codegen_object_new(((RuntimeClass*)il2cpp_codegen_initialize_runtime_metadata_inline((uintptr_t*)&NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339_il2cpp_TypeInfo_var))); NotSupportedException__ctor_m3EA81A5B209A87C3ADA47443F2AFFF735E5256EE(L_0, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_0, ((RuntimeMethod*)il2cpp_codegen_initialize_runtime_metadata_inline((uintptr_t*)&U3CSpawnerCoroutine1U3Ed__4_System_Collections_IEnumerator_Reset_mC693C89E69AB6F0008DCCFD9CFBA6B89215EA69E_RuntimeMethod_var))); } } // System.Object DoorGenerator/<SpawnerCoroutine1>d__4::System.Collections.IEnumerator.get_Current() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * U3CSpawnerCoroutine1U3Ed__4_System_Collections_IEnumerator_get_Current_m387A94449BD691F5509AC7CFA752FA65B94C7B02 (U3CSpawnerCoroutine1U3Ed__4_t1C0C73273458F609E493AAD1E670E843C652973A * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = __this->get_U3CU3E2__current_1(); return L_0; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void ObstacleSpawner/<SpawnerCoroutine>d__4::.ctor(System.Int32) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CSpawnerCoroutineU3Ed__4__ctor_m00AB12936ACCDE67EAED4471CD2C5A91D17BF5CF (U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 * __this, int32_t ___U3CU3E1__state0, const RuntimeMethod* method) { { Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405(__this, /*hidden argument*/NULL); int32_t L_0 = ___U3CU3E1__state0; __this->set_U3CU3E1__state_0(L_0); return; } } // System.Void ObstacleSpawner/<SpawnerCoroutine>d__4::System.IDisposable.Dispose() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CSpawnerCoroutineU3Ed__4_System_IDisposable_Dispose_m12EC7C2B7C04ACB12DECBD40720DEFD20E6FBF65 (U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 * __this, const RuntimeMethod* method) { { return; } } // System.Boolean ObstacleSpawner/<SpawnerCoroutine>d__4::MoveNext() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool U3CSpawnerCoroutineU3Ed__4_MoveNext_m863FE26CD5AE24AC6FD826B675F6B8C03B684784 (U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * V_1 = NULL; { int32_t L_0 = __this->get_U3CU3E1__state_0(); V_0 = L_0; ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * L_1 = __this->get_U3CU3E4__this_2(); V_1 = L_1; int32_t L_2 = V_0; if (!L_2) { goto IL_0017; } } { int32_t L_3 = V_0; if ((((int32_t)L_3) == ((int32_t)1))) { goto IL_0045; } } { return (bool)0; } IL_0017: { __this->set_U3CU3E1__state_0((-1)); goto IL_0097; } IL_0020: { // yield return new WaitForSeconds(Random.Range(waitSecondsMin, waitSecondsMax)); ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * L_4 = V_1; float L_5 = L_4->get_waitSecondsMin_5(); ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * L_6 = V_1; float L_7 = L_6->get_waitSecondsMax_6(); float L_8; L_8 = Random_Range_mC15372D42A9ABDCAC3DE82E114D60A40C9C311D2(L_5, L_7, /*hidden argument*/NULL); WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013 * L_9 = (WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013 *)il2cpp_codegen_object_new(WaitForSeconds_t8F9189BE6E467C98C99177038881F8982E0E4013_il2cpp_TypeInfo_var); WaitForSeconds__ctor_mD298C4CB9532BBBDE172FC40F3397E30504038D4(L_9, L_8, /*hidden argument*/NULL); __this->set_U3CU3E2__current_1(L_9); __this->set_U3CU3E1__state_0(1); return (bool)1; } IL_0045: { __this->set_U3CU3E1__state_0((-1)); // Instantiate(obstacle, new Vector3(Random.Range(-1.5f, 1.5f), transform.position.y, transform.position.z), transform.rotation); ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * L_10 = V_1; GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_11 = L_10->get_obstacle_4(); float L_12; L_12 = Random_Range_mC15372D42A9ABDCAC3DE82E114D60A40C9C311D2((-1.5f), (1.5f), /*hidden argument*/NULL); ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * L_13 = V_1; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_14; L_14 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_13, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_15; L_15 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_14, /*hidden argument*/NULL); float L_16 = L_15.get_y_3(); ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * L_17 = V_1; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_18; L_18 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_17, /*hidden argument*/NULL); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_19; L_19 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_18, /*hidden argument*/NULL); float L_20 = L_19.get_z_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_21; memset((&L_21), 0, sizeof(L_21)); Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_21), L_12, L_16, L_20, /*hidden argument*/NULL); ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * L_22 = V_1; Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_23; L_23 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_22, /*hidden argument*/NULL); Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 L_24; L_24 = Transform_get_rotation_m4AA3858C00DF4C9614B80352558C4C37D08D2200(L_23, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var); GameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319 * L_25; L_25 = Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B(L_11, L_21, L_24, /*hidden argument*/Object_Instantiate_TisGameObject_tC000A2E1A7CF1E10FD7BA08863287C072207C319_m81B599A0051F8F4543E5C73A11585E96E940943B_RuntimeMethod_var); } IL_0097: { // while (enabled) ObstacleSpawner_tBD19CB16C5E4A6BE8372D427B3A409FEB8E8DDFC * L_26 = V_1; bool L_27; L_27 = Behaviour_get_enabled_m08077AB79934634E1EAE909C2B482BEF4C15A800(L_26, /*hidden argument*/NULL); if (L_27) { goto IL_0020; } } { // } return (bool)0; } } // System.Object ObstacleSpawner/<SpawnerCoroutine>d__4::System.Collections.Generic.IEnumerator<System.Object>.get_Current() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * U3CSpawnerCoroutineU3Ed__4_System_Collections_Generic_IEnumeratorU3CSystem_ObjectU3E_get_Current_m99720DEC25BBD332E960804E83445B3F04EE585F (U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = __this->get_U3CU3E2__current_1(); return L_0; } } // System.Void ObstacleSpawner/<SpawnerCoroutine>d__4::System.Collections.IEnumerator.Reset() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void U3CSpawnerCoroutineU3Ed__4_System_Collections_IEnumerator_Reset_m16149D060D481F2BD31D3C231DA8A5F3C711D0C5 (U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 * __this, const RuntimeMethod* method) { { NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339 * L_0 = (NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339 *)il2cpp_codegen_object_new(((RuntimeClass*)il2cpp_codegen_initialize_runtime_metadata_inline((uintptr_t*)&NotSupportedException_tB9D89F0E9470A2C423D239D7C68EE0CFD77F9339_il2cpp_TypeInfo_var))); NotSupportedException__ctor_m3EA81A5B209A87C3ADA47443F2AFFF735E5256EE(L_0, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_0, ((RuntimeMethod*)il2cpp_codegen_initialize_runtime_metadata_inline((uintptr_t*)&U3CSpawnerCoroutineU3Ed__4_System_Collections_IEnumerator_Reset_m16149D060D481F2BD31D3C231DA8A5F3C711D0C5_RuntimeMethod_var))); } } // System.Object ObstacleSpawner/<SpawnerCoroutine>d__4::System.Collections.IEnumerator.get_Current() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * U3CSpawnerCoroutineU3Ed__4_System_Collections_IEnumerator_get_Current_mE5C36A38AA0F1728DFBC8859FAAD5C8934AC08CD (U3CSpawnerCoroutineU3Ed__4_t67CE1362604BF32CC36232219B9B92071C736A75 * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = __this->get_U3CU3E2__current_1(); return L_0; } } #ifdef __clang__ #pragma clang diagnostic pop #endif IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_Multiply_m9EA3D18290418D7B410C7D11C4788C13BFD2C30A_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, float ___d1, const RuntimeMethod* method) { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E V_0; memset((&V_0), 0, sizeof(V_0)); { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_0 = ___a0; float L_1 = L_0.get_x_2(); float L_2 = ___d1; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_3 = ___a0; float L_4 = L_3.get_y_3(); float L_5 = ___d1; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_6 = ___a0; float L_7 = L_6.get_z_4(); float L_8 = ___d1; Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_9; memset((&L_9), 0, sizeof(L_9)); Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_9), ((float)il2cpp_codegen_multiply((float)L_1, (float)L_2)), ((float)il2cpp_codegen_multiply((float)L_4, (float)L_5)), ((float)il2cpp_codegen_multiply((float)L_7, (float)L_8)), /*hidden argument*/NULL); V_0 = L_9; goto IL_0021; } IL_0021: { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_10 = V_0; return L_10; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_Subtraction_m2725C96965D5C0B1F9715797E51762B13A5FED58_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___b1, const RuntimeMethod* method) { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E V_0; memset((&V_0), 0, sizeof(V_0)); { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_0 = ___a0; float L_1 = L_0.get_x_2(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_2 = ___b1; float L_3 = L_2.get_x_2(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_4 = ___a0; float L_5 = L_4.get_y_3(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_6 = ___b1; float L_7 = L_6.get_y_3(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_8 = ___a0; float L_9 = L_8.get_z_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_10 = ___b1; float L_11 = L_10.get_z_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_12; memset((&L_12), 0, sizeof(L_12)); Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_12), ((float)il2cpp_codegen_subtract((float)L_1, (float)L_3)), ((float)il2cpp_codegen_subtract((float)L_5, (float)L_7)), ((float)il2cpp_codegen_subtract((float)L_9, (float)L_11)), /*hidden argument*/NULL); V_0 = L_12; goto IL_0030; } IL_0030: { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_13 = V_0; return L_13; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_UnaryNegation_m362EA356F4CADEDB39F965A0DBDED6EA890925F7_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, const RuntimeMethod* method) { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E V_0; memset((&V_0), 0, sizeof(V_0)); { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_0 = ___a0; float L_1 = L_0.get_x_2(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_2 = ___a0; float L_3 = L_2.get_y_3(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_4 = ___a0; float L_5 = L_4.get_z_4(); Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_6; memset((&L_6), 0, sizeof(L_6)); Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_6), ((-L_1)), ((-L_3)), ((-L_5)), /*hidden argument*/NULL); V_0 = L_6; goto IL_001e; } IL_001e: { Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_7 = V_0; return L_7; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * __this, float ___x0, float ___y1, float ___z2, const RuntimeMethod* method) { { float L_0 = ___x0; __this->set_x_2(L_0); float L_1 = ___y1; __this->set_y_3(L_1); float L_2 = ___z2; __this->set_z_4(L_2); return; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR RuntimeObject * List_1_get_Item_mF00B574E58FB078BB753B05A3B86DD0A7A266B63_gshared_inline (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, int32_t ___index0, const RuntimeMethod* method) { { int32_t L_0 = ___index0; int32_t L_1 = (int32_t)__this->get__size_2(); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_000e; } } { ThrowHelper_ThrowArgumentOutOfRangeException_m4841366ABC2B2AFA37C10900551D7E07522C0929(/*hidden argument*/NULL); } IL_000e: { ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE* L_2 = (ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE*)__this->get__items_1(); int32_t L_3 = ___index0; RuntimeObject * L_4; L_4 = IL2CPP_ARRAY_UNSAFE_LOAD((ObjectU5BU5D_tC1F4EE0DB0B7300255F5FD4AF64FE4C585CF5ADE*)L_2, (int32_t)L_3); return (RuntimeObject *)L_4; } } IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR int32_t List_1_get_Count_m5D847939ABB9A78203B062CAFFE975792174D00F_gshared_inline (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, const RuntimeMethod* method) { { int32_t L_0 = (int32_t)__this->get__size_2(); return (int32_t)L_0; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Collectible : MonoBehaviour { public float movingSpeed = 10; // Start is called before the first frame update void Start() { Destroy(gameObject, 6f); } // Update is called once per frame void Update() { transform.Translate(Vector3.back * Time.deltaTime * movingSpeed, Space.World); } private void OnTriggerEnter(Collider collision) { if (collision.gameObject.CompareTag("Table")) { Destroy(gameObject); } if (collision.gameObject.CompareTag("Player")) { Destroy(gameObject); } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class EnvironmentGenerator : MonoBehaviour { public Camera mainCamera; public Transform startPoint; public EnvironmentTiling tilePrefab; public float movingSpeed = 10; public int tilesToPreSpawn; public int tilesWithoutObstacles = 1; public int score; public int highScore; List<EnvironmentTiling> spawnedTiles = new List<EnvironmentTiling>(); public static EnvironmentGenerator instance; // Start is called before the first frame update void Start() //spawnaa skenen alussa heti jonoon sopivan määrän prefabeja { instance = this; int tilesWithoutDoorsTmp = tilesWithoutObstacles; Vector3 spawnPosition = startPoint.position; for (int i = 0; i < tilesToPreSpawn; i++) { spawnPosition -= tilePrefab.startPoint.localPosition; EnvironmentTiling spawnedTile = Instantiate(tilePrefab, spawnPosition, Quaternion.identity) as EnvironmentTiling; if (tilesWithoutDoorsTmp > 0) { spawnedTile.DeactivateAllObstacles(); tilesWithoutDoorsTmp--; } else { spawnedTile.ActivateRandomCorridor(); } spawnPosition = spawnedTile.endPoint.position; spawnedTile.transform.SetParent(transform); spawnedTiles.Add(spawnedTile); } highScore = PlayerPrefs.GetInt("HighScore", 0); } // Update is called once per frame void Update() //prefabien liikkuminen { transform.Translate(-spawnedTiles[0].transform.forward * Time.deltaTime * movingSpeed, Space.World); score += 1; PlayerPrefs.SetInt("Score", score); if (score > highScore) { highScore = score; PlayerPrefs.SetInt("HighScore", highScore); PlayerPrefs.Save(); } if (mainCamera.WorldToViewportPoint(spawnedTiles[0].endPoint.position).z < 0) { // Despawnaa ns. kameran taakse jäävät prefabit ja spawnaa ne uudestaan startpointtiin EnvironmentTiling tileTmp = spawnedTiles[0]; spawnedTiles.RemoveAt(0); tileTmp.transform.position = spawnedTiles[spawnedTiles.Count - 1].endPoint.position - tileTmp.startPoint.localPosition; tileTmp.ActivateRandomCorridor(); spawnedTiles.Add(tileTmp); } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; [RequireComponent(typeof(Rigidbody))] public class Player : MonoBehaviour { public float gravity = 20.0f; public float movementSpeed; public PlayerLight playerLight; public AudioSource CollectSound; Rigidbody rb; Vector3 defaultScale; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody>(); rb.constraints = RigidbodyConstraints.FreezePositionZ; rb.freezeRotation = true; rb.useGravity = false; defaultScale = transform.localScale; } void Update() { if (Input.GetKey("left") || Input.GetKey("a")) //vasen { transform.Translate(Vector3.left * Time.deltaTime * movementSpeed); } if (Input.GetKey("right") || Input.GetKey("d")) //oikee { transform.Translate(Vector3.right * Time.deltaTime * movementSpeed); } if (Input.GetKeyUp(KeyCode.Escape)) //takas valikkoon { SceneManager.LoadScene("MainMenu"); } transform.position = new Vector3(Mathf.Clamp(transform.position.x, -1.5f, 1.5f), transform.position.y, 0); //rajottaa sivuttaisliikkeen määrää ettei mee kentän "yli" } // Update is called once per frame void FixedUpdate() { rb.AddForce(new Vector3(0, -gravity * rb.mass, 0)); } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Table")) //osu pöytään, kuole { Die(); } } private void OnTriggerEnter(Collider collision) //kun pelaaja osuu kynttilään, kasvatetaan lampun kirkkautta { if (collision.gameObject.CompareTag("Collectible")) { playerLight.IncreaseIntensity(); CollectSound.Play(); } } public void Die() //pitääks tää ny selittää eriksee? { SceneManager.LoadScene("GameOver"); } }
ac2f44366e59b16ebfeb13ff7632ebaac85c9f79
[ "C#", "C", "C++" ]
16
C++
makkomise/spooky_endlessrunner
7a00769b981ffaa764d187246c6c0a37e29c411a
01b0d3c016ff73f2150f95aaae8289627488bc36
refs/heads/master
<repo_name>isabella232/cocalc-xpra<file_sep>/src/connection/worker.js /*! * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> * @preserve */ import { createReceiveQueue, createSendQueue } from "../protocol.js"; const createWebsocket = (uri, callback) => { const socket = new WebSocket(uri, "binary"); socket.binaryType = "arraybuffer"; socket.onopen = ev => callback("ws:open", ev); socket.onclose = ev => callback("ws:close", ev); socket.onerror = ev => callback("ws:error", ev); socket.onmessage = ev => { const data = new Uint8Array(ev.data); callback("ws:data", ev, data); }; return socket; }; const createConnection = bus => { let socket; const sendQueue = createSendQueue(); const send = (...packet) => sendQueue.push(packet, socket); const receiveQueue = createReceiveQueue((...args) => { postMessage({ event: "data", args }); }); const flush = () => { sendQueue.clear(); receiveQueue.clear(); }; const open = config => { socket = createWebsocket(config.uri, (name, ev, data) => { if (name === "ws:data") { receiveQueue.push(data); } else { postMessage({ event: name, args: [] }); } }); }; const close = () => { if (socket) { socket.close(); } socket = null; }; return { send, close, open, flush }; }; const client = createConnection(); self.addEventListener( "message", ({ data }) => { switch (data.command) { case "send": client.send(...data.packet); break; case "open": client.open(data.config); break; case "close": client.close(); break; case "flush": client.flush(); break; default: console.warn("Invalid", data); break; } }, false ); client.send("ready"); <file_sep>/src/util.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ import forge from "node-forge"; import { CHUNK_SZ, DEFAULT_DPI } from "./constants.js"; export const ord = s => s.charCodeAt(0); export const browserLanguage = (defaultLanguage = "en") => { const properties = [ "language", "browserLanguage", "systemLanguage", "userLanguage" ]; const found = properties.map(prop => navigator[prop]).filter(str => !!str); const list = (navigator.languages || [found || defaultLanguage]).map( str => str.split(/-|_/)[0] ); return list[0]; }; export const calculateDPI = () => { if ("deviceXDPI" in screen) { return (screen.systemXDPI + screen.systemYDPI) / 2; } /* FIXME try { const el = document.createElement('div'); el.style.visibility = 'hidden'; document.body.appendChild(el); if (el.offsetWidth > 0 && el.offsetHeight > 0) { const dpi = Math.round((el.offsetWidth + el.offsetHeight) / 2.0); document.body.removeChild(el); return dpi; } } catch (e) { console.warn(e); } */ return DEFAULT_DPI; }; export const calculateColorGamut = () => { const map = { rec2020: "(color-gamut: rec2020)", P3: "(color-gamut: p3)", srgb: "(color-gamut: srgb)" }; let found; if (typeof window.matchMedia === "function") { found = Object.keys(map).find(k => window.matchMedia(map[k]).matches); } return found ? found : ""; }; export const supportsWebp = () => { try { const el = document.createElement("canvas"); const ctx = el.getContext("2d"); if (ctx) { return el.toDataURL("image/webp").indexOf("data:image/webp") == 0; } } catch (e) { console.warn(e); } return false; }; export const timestamp = () => performance ? Math.round(performance.now()) : Date.now(); // apply in chunks of 10400 to avoid call stack overflow // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply export const arraybufferBase64 = (uintArray, skip = 10400) => { let s = ""; if (uintArray.subarray) { for (let i = 0, len = uintArray.length; i < len; i += skip) { s += String.fromCharCode.apply( null, uintArray.subarray(i, Math.min(i + skip, len)) ); } } else { for (let i = 0, len = uintArray.length; i < len; i += skip) { s += String.fromCharCode.apply( null, uintArray.slice(i, Math.min(i + skip, len)) ); } } return window.btoa(s); }; // python-lz4 inserts the length of the uncompressed data as an int // at the start of the stream export function lz4decode(data) { throw Error("lz4decode: not implemented"); } /* export const lz4decode = data => { const d = data.subarray(0, 4); // output buffer length is stored as little endian const length = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24); // decode the LZ4 block const inflated = new Uint8Array(length); const uncompressedSize = lz4.decodeBlock(data, inflated, 4); return { uncompressedSize, inflated }; }; */ export const strToUint8 = str => { let u8a = new Uint8Array(str.length); for (let i = 0, j = str.length; i < j; ++i) { u8a[i] = str.charCodeAt(i); } return u8a; }; export const uint8ToStr = u8a => { let c = []; for (let i = 0; i < u8a.length; i += CHUNK_SZ) { c.push(String.fromCharCode.apply(null, u8a.subarray(i, i + CHUNK_SZ))); } return c.join(""); }; export const xorString = (str1, str2) => { let result = ""; if (str1.length !== str2.length) { throw new Error("strings must be equal length"); } for (let i = 0; i < str1.length; i++) { result += String.fromCharCode( str1[i].charCodeAt(0) ^ str2[i].charCodeAt(0) ); } return result; }; export const hexUUID = () => { let s = []; const hexDigits = "0123456789abcdef"; for (let i = 0; i < 36; i++) { s[i] = i === 8 || i === 13 || i === 18 || i === 23 ? "-" : hexDigits.substr(Math.floor(Math.random() * 0x10), 1); } return s.join(""); }; export const calculateScreens = (width, height, dpi) => { const wmm = Math.round((width * 25.4) / dpi); const hmm = Math.round((height * 25.4) / dpi); const monitor = ["Canvas", 0, 0, width, height, wmm, hmm]; const screen = [ "HTML", width, height, wmm, hmm, [monitor], 0, 0, width, height ]; return [screen]; // just a single screen }; export const generateSalt = (saltDigest, serverSalt) => { const l = saltDigest === "xor" ? serverSalt.length : 32; if (l < 16 || l > 256) { throw new Error("Invalid salt length of", l); } let s = ""; while (s.length < l) { s += hexUUID(); } return s.slice(0, l); }; export const generateDigest = (digest, password, salt) => { if (digest.startsWith("hmac")) { let hash = "md5"; if (digest.indexOf("+") > 0) { hash = digest.split("+")[1]; } const hmac = forge.hmac.create(); hmac.start(hash, password); hmac.update(salt); return hmac.digest().toHex(); } else if (digest === "xor") { const trimmed = salt.slice(0, password.length); return xorString(trimmed, password); } return null; }; <file_sep>/src/client.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ import { EventHandler } from "./eventhandler.js"; import { getCapabilities } from "./capabilities.js"; import { createRenderer } from "./renderer.js"; import { createKeyboard } from "./keyboard.js"; import { createMouse } from "./mouse.js"; //import {createSound, enumSoundCodecs} from './sound.js'; import { createConnection } from "./connection/null.js"; import { iconRenderer } from "./renderer/icon.js"; import { PING_FREQUENCY } from "./constants.js"; import { hexUUID, calculateDPI, calculateScreens, timestamp, generateSalt, generateDigest } from "./util.js"; /** * Creates a configuration */ const createConfiguration = (defaults = {}, append = {}) => Object.assign( { uuid: hexUUID(), uri: "ws://localhost:10000", /* audio_framework: null, */ audio_codec_blacklist: [], audio_codecs: [], image_codecs: [], screen: [window.innerWidth, window.innerHeight], dpi: calculateDPI(), compression_level: 1, reconnect: true, notifications: true, clipboard: false, //sound: true, bell: true, printing: false, // FIXME transfer: false, // FIXME keyboard: true, share: true, steal: true, language: null, // auto username: "", password: "", zlib: true, lz4: true }, defaults, append ); /** * Creates a render surface */ const createSurface = (parent, wid, x, y, w, h, metadata, properties, send) => { const overlay = !!parent; const canvas = document.createElement("canvas"); canvas.width = w; canvas.height = h; const context = canvas.getContext("2d"); const renderer = createRenderer({ wid, canvas, context }, send); const draw = (...args) => renderer.push(...args); const updateMetadata = meta => Object.assign(metadata, meta); const destroy = () => renderer.stop(); return { wid, x, y, w, h, parent, overlay, canvas, context, metadata, properties, draw, updateMetadata, destroy }; }; const createConnectionGate = (bus, env) => { if (window.Worker) { const worker = new Worker(env.worker); worker.onmessage = ({ data }) => { if (data.event === "data") { bus.emit(...data.args); } else { bus.emit(data.event, ...data.args); } }; return { send: (...packet) => worker.postMessage({ command: "send", packet }), close: () => worker.postMessage({ command: "close" }), open: config => worker.postMessage({ command: "open", config }), flush: () => worker.postMessage({ command: "flush" }) }; } return createConnection(bus); }; /** * Creates a new Xpra client */ export const createClient = (defaultConfig = {}, env = {}) => { env = Object.assign( { worker: "worker.js" }, env ); const bus = new EventHandler("XpraClient"); // TODO: for now skip using webworker, since need to be clear about where worker.js actually *is*.... //const connection = createConnectionGate(bus, env); const connection = createConnection(bus); const { send } = connection; const ping = () => send("ping", timestamp()); const keyboard = createKeyboard(send); const mouse = createMouse(send, keyboard); //const sound = createSound(send); let config; let connected = false; let connecting = false; let reconnecting = false; let clientCapabilities; let serverCapabilities; let surfaces = []; let activeWindow = 0; let lastActiveWindow = 0; let audioCodecs = { codecs: [] }; const states = { reconnecting: () => reconnecting, connecting: () => connecting, connected: () => connected }; const getState = () => Object.keys(states).find(key => states[key]() === true) || "disconnected"; const emitState = () => bus.emit("ws:status", getState()); const findSurface = wid => surfaces.find(s => s.wid === wid); const focus = wid => { const found = findSurface(wid); if (found) { if (activeWindow !== wid) { send("focus", wid, []); } activeWindow = wid; bus.emit("window:focus", { wid }); } else { activeWindow = 0; } }; // Closes connection const disconnect = closing => { connected = false; connecting = false; if (!closing) { connection.close(); } emitState(); surfaces = []; //sound.destroy(); connection.flush(); }; // Opens connection const connect = (cfg = {}) => { config = createConfiguration(defaultConfig, cfg); if (connection) { disconnect(); } connecting = true; emitState(); connection.open(config); }; // Injects a key browser event const key_inject = (ev, wid) => { if (!connected) { return false; } if (typeof wid === "undefined") { wid = activeWindow; } const surface = findSurface(wid); keyboard.process(ev, surface); return false; }; // Injects a mouse browser event const mouse_inject = (ev, wid) => { if (!connected) { return; } if (typeof wid === "undefined") { wid = activeWindow; } const surface = findSurface(wid); return mouse.process(ev, surface); }; // Kills a window/surface const kill = wid => { if (findSurface(wid)) { send("close-window", wid); } }; // Sends a draw event to surface const render = ( wid, x, y, w, h, coding, data, sequence, rowstride, options = {} ) => { const found = findSurface(wid); if (found) { found.draw(x, y, w, h, coding, data, sequence, rowstride, options); } }; const log = (name, level) => (...args) => { if ( connected && serverCapabilities && serverCapabilities["remote-logging.multi-line"] ) { send( "logging", level, args.map(str => { return unescape(encodeURIComponent(String(str))); }) ); } else { console[name](...args); } }; const resize = (() => { let debounce; return (w, h) => { clearTimeout(debounce); debounce = setTimeout(() => { const sizes = calculateScreens(w, h, config.dpi); send("desktop_size", w, h, sizes); }, 100); }; })(); const serverConsole = { error: log("error", 40), warn: log("warn", 30), log: log("log", 20), info: log("info", 20), debug: log("debug", 10) }; // WebSocket actions bus.on("ws:open", () => { //audioCodecs = enumSoundCodecs(config); clientCapabilities = getCapabilities(config, audioCodecs.codecs); console.debug("!!!", { config, audioCodecs, clientCapabilities }); const capabilities = Object.assign({}, clientCapabilities); if (config.username || config.password) { capabilities.challenge = true; } send("hello", capabilities); }); bus.on("ws:close", () => disconnect(true)); // Xpra actions bus.on("disconnect", () => disconnect(true)); // TODO: Reconnect bus.on("hello", cap => (serverCapabilities = cap)); bus.on("ping", time => send("ping_echo", time, 0, 0, 0, 0)); bus.on("challenge", (serverSalt, foo, digest, saltDigest) => { // TODO: Proto // FIXME: Don't use xor on non-ssl saltDigest = saltDigest || "xor"; console.debug("--- challenge", { serverSalt, digest, saltDigest }); try { const clientSalt = generateSalt(saltDigest, serverSalt); const salt = generateDigest(saltDigest, clientSalt, serverSalt); if (!salt) { throw new Error("Invalid challenge salt digest: " + saltDigest); } const response = generateDigest(digest, config.password, salt); if (response) { const append = { challenge_response: response, challenge_client_salt: clientSalt }; const capabilities = Object.assign({}, clientCapabilities, append); send("hello", capabilities); } else { throw new Error("Invalid challenge digest: " + digest); } } catch (e) { console.error(e); disconnect(); } }); bus.on("window-metadata", (wid, metadata = {}) => { const surface = findSurface(wid); if (surface) { surface.updateMetadata(metadata); bus.emit("window:metadata", surface); } }); bus.on("new-window", (wid, x, y, w, h, metadata, properties) => { lastActiveWindow = 0; const props = Object.assign({}, properties || {}, { "encodings.rgb_formats": clientCapabilities["encodings.rgb_formats"] }); send("map-window", wid, x, y, w, h, props); send("focus", [], wid); const surface = createSurface( false, wid, x, y, w, h, metadata, properties, send ); surfaces.push(surface); bus.emit("window:create", surface); focus(wid); }); bus.on("new-override-redirect", (wid, x, y, w, h, metadata, properties) => { const parentWid = metadata["transient-for"]; const parent = parentWid ? findSurface(parentWid) : false; if (parent) { const surface = createSurface( parent, wid, x, y, w, h, metadata, properties, send ); bus.emit("overlay:create", { parent, wid, x, y, canvas: surface.canvas }); surfaces.push(surface); lastActiveWindow = parentWid; focus(wid); } }); bus.on("lost-window", wid => { const surface = findSurface(wid); if (surface) { if (surface.overlay) { bus.emit("overlay:destroy", surface); } else { if (activeWindow === wid) { bus.emit("window:blur", { wid }); } bus.emit("window:destroy", surface); } surface.destroy(); const index = surfaces.findIndex(s => s.wid === wid); surfaces.splice(index, 1); } if (activeWindow === wid) { activeWindow = lastActiveWindow; } }); bus.on("window-icon", (wid, w, h, coding, data) => { const src = iconRenderer({ coding, data }); if (src) { bus.emit("window:icon", { wid, src }); } }); bus.on("startup-complete", () => { bus.emit("system:started"); connected = true; connecting = false; serverConsole.info("Xpra HTML5 Client connected"); emitState(); /* if (config.sound) { sound.start(config.audio_framework, audioCodecs, clientCapabilities, serverCapabilities); }*/ }); bus.on("sound-data", (codec, buffer, options, metadata) => { //sound.process(codec, buffer, options, metadata); }); bus.on( "notify_show", ( busId, notificationId, replacesId, summary, body, timeout, icon, actions, hints ) => { bus.emit("notification:create", notificationId, { busId, replacesId, summary, body, timeout, icon, actions, hints }); } ); bus.on("notify_show", notificationId => { bus.emit("notification:destroy", notificationId); }); bus.on("send-file", (filename, mime, print, size, data) => { if (data.length !== size) { console.warn("Invalid file", filename, mime, size); return; } if (print) { bus.emit("system:print", { filename, mime, size }, data); } else { bus.emit("system:upload", { filename, mime, size }, data); } }); bus.on("open-url", () => bus.emit("system:url")); bus.on("bell", () => bus.emit("system:bell")); bus.on("eos", render); bus.on("draw", render); // Make sure to ping the server setInterval(() => { if (connected) { ping(); } }, PING_FREQUENCY); // Exported API return Object.freeze({ console: serverConsole, connect, disconnect, ping, send, key_inject, mouse_inject, status: () => getState(), on: (...args) => bus.on(...args), off: (name, callback) => { if (callback) { bus.off(name, callback); } }, screen: { resize }, surface: { focus, kill } }); }; <file_sep>/src/capabilities.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ import forge from "node-forge"; import { CHARCODE_TO_NAME } from "./constants.js"; import { browserLanguage, supportsWebp, calculateDPI, calculateColorGamut, calculateScreens } from "./util.js"; const platformMap = { Win: { type: "win32", name: "Microsoft Windows" }, Mac: { type: "darwin", name: "Mac OSX" }, Linux: { type: "linux", name: "Linux" }, X11: { type: "posix", name: "Posix" } }; const getPlatform = () => { const { appVersion, oscpu, cpuClass } = navigator; const found = Object.keys(platformMap).find(k => appVersion.includes(k)); return Object.assign( { type: "unknown", name: "unknown", processor: oscpu || cpuClass || "unknown", platform: appVersion }, found ? platformMap[found] : {} ); }; const getBrowser = () => { return { name: "Chrome", // TODO agent: navigator.userAgent }; }; const getEncodingCapabilities = (config, soundCodecs) => { const digest = [ "hmac", "hmac+md5", "xor", ...Object.keys(forge.md.algorithms).map(hash => `hmac+${hash}`) ]; const detectedEncodings = ["jpeg", "png", "rgb", "rgb32"]; // "h264", "vp8+webm", "h264+mp4", "mpeg4+mp4" if (supportsWebp()) { detectedEncodings.push("webp"); } const imageEncodings = config.image_codecs.length > 0 ? config.image_codecs : detectedEncodings; const audioEncodings = config.audio_codecs.length > 0 ? config.audio_codecs : soundCodecs; return { digest: digest, "salt-digest": digest, "generic-rgb-encodings": true, "sound.decoders": audioEncodings, encodings: imageEncodings, "encoding.generic": true, "encoding.rgb24zlib": true, "encoding.rgb_zlib": true, "encoding.icons.max_size": [30, 30], "encodings.core": imageEncodings, "encodings.rgb_formats": ["RGBX", "RGBA"], "encodings.window-icon": ["png"], "encodings.cursor": ["png"], "encoding.flush": true, "encoding.transparency": true, "encoding.client_options": true, "encoding.csc_atoms": true, "encoding.scrolling": true, "encoding.color-gamut": calculateColorGamut(), "encoding.video_scaling": true, "encoding.video_max_size": [1024, 768], "encoding.eos": true, "encoding.full_csc_modes": { mpeg1: ["YUV420P"], h264: ["YUV420P"], "mpeg4+mp4": ["YUV420P"], "h264+mp4": ["YUV420P"], "vp8+webm": ["YUV420P"], webp: ["BGRX", "BGRA"] }, "encoding.h264.YUV420P.profile": "baseline", "encoding.h264.YUV420P.level": "2.1", "encoding.h264.cabac": false, "encoding.h264.deblocking-filter": false, "encoding.h264.fast-decode": true, "encoding.h264+mp4.YUV420P.profile": "main", "encoding.h264+mp4.YUV420P.level": "3.0", // prefer native video in mp4/webm container to broadway plain h264: "encoding.h264.score-delta": -20, "encoding.h264+mp4.score-delta": 50, "encoding.mpeg4+mp4.score-delta": 50, "encoding.vp8+webm.score-delta": 50 // 'encoding.scrolling.min-percent' : 30, // 'encoding.min-speed': 80, // 'encoding.min-quality': 50, // 'encoding.non-scroll': ['rgb32', 'png', 'jpeg'], }; }; const getClientCapabilities = config => { const language = browserLanguage(); const keycodes = Object.keys(CHARCODE_TO_NAME).reduce( (result, c) => [ ...result, [parseInt(c, 10), CHARCODE_TO_NAME[c], parseInt(c, 10), 0, 0] ], [] ); return { share: config.share, steal: config.steal, windows: true, "file-transfer": config.transfer, printing: config.printing, "file-size-limit": 10, auto_refresh_delay: 500, randr_notify: true, raw_window_icons: true, cursors: true, bell: config.bell, system_tray: true, "server-window-resize": true, named_cursors: false, // NOTE: we cannot handle this (GTK only) "notify-startup-complete": true, // Windows "window.raise": true, "window.initiate-moveresize": true, "metadata.supported": [ "fullscreen", "maximized", "above", "below", // 'set-initial-position', 'group-leader', "title", "size-hints", "class-instance", "transient-for", "window-type", "has-alpha", "decorations", "override-redirect", "tray", "modal", "opacity" // 'shadow', 'desktop', ], // Sound "sound.receive": config.sound, "sound.send": false, "sound.server_driven": true, "sound.bundle-metadata": true, // encoding stuff keyboard: config.keyboard, xkbmap_layout: config.language || language, xkbmap_keycodes: keycodes, xkbmap_print: "", xkbmap_query: "", // Screen desktop_size: config.screen, desktop_mode_size: config.screen, screen_sizes: calculateScreens( config.screen[0], config.screen[1], config.dpi ), dpi: config.dpi, // Clipboard (not handled yet, but we will) clipboard_enabled: config.clipboard, "clipboard.want_targets": true, "clipboard.greedy": true, "clipboard.selections": ["CLIPBOARD", "PRIMARY"], // Notifications notifications: config.notifications, "notifications.close": true, "notifications.actions": true }; }; export const getCapabilities = (config, soundCodecs) => { const platform = getPlatform(); const browser = getBrowser(); const client = getClientCapabilities(config); const encoding = getEncodingCapabilities(config, soundCodecs); const extras = { /* challenge: false, 'bandwidth-limit': 0 "connection-data" : ci, "start-new-session" : this.start_new_session}); "cipher" : this.encryption, "cipher.iv" : Utilities.getHexUUID().slice(0, 16), "cipher.key_salt" : Utilities.getHexUUID()+Utilities.getHexUUID(), "cipher.key_stretch_iterations" : 1000, "cipher.padding.options" : ["PKCS#7"], */ }; return Object.assign( { version: "2.4", platform: platform.type, "platform.name": platform.name, "patform.processor": platform.processor, "platform.platform": platform.platform, "session-type": browser.name, "session-type.full": browser.agent, namespace: true, client_type: "HTML5", username: config.username, uuid: config.uuid, argv: [window.location.href], // Compression bits zlib: config.zlib, lzi: false, lz4: false, "encoding.rgb_lz4": false, //lz4: config.lz4, //"lz4.js.version": "0.2.0", // FIXME //"encoding.rgb_lz4": true, compression_level: config.compression_level, // Packet encoders rencode: false, bencode: true, yaml: false, "open-url": true }, client, encoding, extras ); }; <file_sep>/src/connection/null.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ import { createReceiveQueue, createSendQueue } from "../protocol.js"; const createWebsocket = (uri, bus) => { const socket = new WebSocket(uri, "binary"); socket.binaryType = "arraybuffer"; socket.onopen = ev => bus.emit("ws:open", ev); socket.onclose = ev => bus.emit("ws:close", ev); socket.onerror = ev => bus.emit("ws:error", ev); socket.onmessage = ev => { const data = new Uint8Array(ev.data); bus.emit("ws:data", ev, data); }; return socket; }; export const createConnection = bus => { let socket; const receiveQueue = createReceiveQueue((...args) => bus.emit(...args)); const sendQueue = createSendQueue(); const send = (...packet) => sendQueue.push(packet, socket); const flush = () => { sendQueue.clear(); receiveQueue.clear(); }; const open = config => { socket = createWebsocket(config.uri, bus); }; const close = () => { if (socket) { socket.close(); } socket = null; }; bus.on("ws:data", (ev, packet) => receiveQueue.push(packet, socket)); return { send, close, open, flush }; }; <file_sep>/src/constants.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ const { platform, userAgent } = navigator; export const IS_IE = userAgent.includes("MSIE"); export const IS_OPERA = userAgent.toLowerCase().includes("opera"); export const IS_FIREFOX = userAgent.toLowerCase().includes("firefox"); export const IS_SAFARI = userAgent.toLowerCase().includes("safari") && !userAgent.toLowerCase().includes("chrome"); export const IS_CHROME = !IS_IE && !IS_OPERA && !IS_FIREFOX && !IS_SAFARI; // FIXME export const IS_OSX = platform.includes("Mac"); export const IS_WIN32 = platform.includes("Win"); export const DEFAULT_DPI = 96; export const HEADER_SIZE = 8; export const PIXEL_STEP = 10; export const LINE_HEIGHT = 40; export const PAGE_HEIGHT = 800; export const PING_FREQUENCY = 5000; export const MIN_START_BUFFERS = 3; export const MAX_BUFFERS = 250; export const CHUNK_SZ = 0x8000; export const DOM_KEY_LOCATION_RIGHT = 2; export const CHARCODE_TO_NAME = (() => { const result = { 8: "BackSpace", 9: "Tab", 12: "KP_Begin", 13: "Return", 16: "Shift_L", 17: "Control_L", 18: "Alt_L", 19: "Pause", // pause/break 20: "Caps_Lock", 27: "Escape", 31: "Mode_switch", 32: "space", 33: "Prior", // Page Up 34: "Next", // Page Down 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 42: "Print", 45: "Insert", 46: "Delete", 58: "colon", 59: "semicolon", 60: "less", 61: "equal", 62: "greater", 63: "question", 64: "at", 91: "Menu", // Left Window Key 92: "Menu", // Right Window Key 93: "KP_Enter", // 'select key'? 106: "KP_Multiply", 107: "KP_Add", 109: "KP_Subtract", 110: "KP_Delete", 111: "KP_Divide", 144: "Num_Lock", 145: "Scroll_Lock", 160: "dead_circumflex", 167: "underscore", 161: "exclam", 162: "quotedbl", 163: "numbersign", 164: "dollar", 165: "percent", 166: "ampersand", 168: "parenleft", 169: "parenright", 170: "asterisk", 171: "plus", 172: "bar", 173: "minus", 174: "braceleft", 175: "braceright", 176: "asciitilde", 186: "semicolon", 187: "equal", 188: "comma", 189: "minus", 190: "period", 191: "slash", 192: "grave", 219: "bracketleft", 220: "backslash", 221: "bracketright", 222: "apostrophe" }; let i; for (i = 0; i < 26; i++) { result[65 + i] = "abcdefghijklmnopqrstuvwxyz"[i]; } for (i = 0; i < 10; i++) { result[48 + i] = "" + i; result[96 + i] = "" + i; // fix for OSX numpad? // CHARCODE_TO_NAME[96+i] = 'KP_'+i; } for (i = 1; i <= 24; i++) { result[111 + i] = "F" + i; } return result; })(); export const KEY_TO_NAME = (() => { const result = { Escape: "Escape", Tab: "Tab", CapsLock: "Caps_Lock", ShiftLeft: "Shift_L", ControlLeft: "Control_L", MetaLeft: "Meta_L", AltLeft: "Alt_L", Space: "space", AltRight: "Alt_R", MetaRight: "Meta_R", ContextMenu: "Menu_R", ControlRight: "Control_L", ShiftRight: "Shift_R", Enter: "Return", Backspace: "BackSpace", //special keys: ScrollLock: "Scroll_Lock", Pause: "Pause", NumLock: "Num_Lock", //Arrow pad: Insert: "Insert", Home: "Home", PageUp: "Prior", Delete: "Delete", End: "End", PageDown: "Next" }; for (let i = 0; i <= 9; i++) { result["Numpad" + i] = "" + i; result["KP" + i] = "KP" + i; } for (let i = 1; i <= 20; i++) { result["F" + i] = "F" + i; } return result; })(); export const NUMPAD_TO_NAME = { //Num pad: NumpadDivide: "KP_Divide", NumpadMultiply: "KP_Multiply", NumpadSubstract: "KP_Substract", NumpadAdd: "KP_Add", NumpadEnter: "KP_Enter", NumpadDecimal: "KP_Decimal", //TODO: send KP_Delete when Num_Lock is off //Num_Lock off: Insert: "KP_Insert", End: "KP_End", ArrowDown: "KP_Down", PageDown: "KP_Next", ArrowLeft: "KP_Left", Clear: "KP_Begin", ArrowRight: "KP_Right", Home: "KP_Home", ArrowUp: "KP_Up", PageUp: "KP_Prior" }; /** * This table was generated using: * grep "#define XKB_KEY_" /usr/include/xkbcommon/xkbcommon-keysyms.h | \ * grep "/* U+" | grep -v "A-Z" | \ * sed 's/#define XKB_KEY_//g; s/ *0x.*U+/ 0x/g' | \ * awk '{print "\""$1"\" : "$2","}' */ export const KEYSYM_TO_UNICODE = { space: 0x0020, exclam: 0x0021, quotedbl: 0x0022, numbersign: 0x0023, dollar: 0x0024, percent: 0x0025, ampersand: 0x0026, apostrophe: 0x0027, parenleft: 0x0028, parenright: 0x0029, asterisk: 0x002a, plus: 0x002b, comma: 0x002c, minus: 0x002d, period: 0x002e, slash: 0x002f, "0": 0x0030, "1": 0x0031, "2": 0x0032, "3": 0x0033, "4": 0x0034, "5": 0x0035, "6": 0x0036, "7": 0x0037, "8": 0x0038, "9": 0x0039, colon: 0x003a, semicolon: 0x003b, less: 0x003c, equal: 0x003d, greater: 0x003e, question: 0x003f, at: 0x0040, A: 0x0041, B: 0x0042, C: 0x0043, D: 0x0044, E: 0x0045, F: 0x0046, G: 0x0047, H: 0x0048, I: 0x0049, J: 0x004a, K: 0x004b, L: 0x004c, M: 0x004d, N: 0x004e, O: 0x004f, P: 0x0050, Q: 0x0051, R: 0x0052, S: 0x0053, T: 0x0054, U: 0x0055, V: 0x0056, W: 0x0057, X: 0x0058, Y: 0x0059, Z: 0x005a, bracketleft: 0x005b, backslash: 0x005c, bracketright: 0x005d, asciicircum: 0x005e, underscore: 0x005f, grave: 0x0060, a: 0x0061, b: 0x0062, c: 0x0063, d: 0x0064, e: 0x0065, f: 0x0066, g: 0x0067, h: 0x0068, i: 0x0069, j: 0x006a, k: 0x006b, l: 0x006c, m: 0x006d, n: 0x006e, o: 0x006f, p: 0x0070, q: 0x0071, r: 0x0072, s: 0x0073, t: 0x0074, u: 0x0075, v: 0x0076, w: 0x0077, x: 0x0078, y: 0x0079, z: 0x007a, braceleft: 0x007b, bar: 0x007c, braceright: 0x007d, asciitilde: 0x007e, nobreakspace: 0x00a0, exclamdown: 0x00a1, cent: 0x00a2, sterling: 0x00a3, currency: 0x00a4, yen: 0x00a5, brokenbar: 0x00a6, section: 0x00a7, diaeresis: 0x00a8, copyright: 0x00a9, ordfeminine: 0x00aa, guillemotleft: 0x00ab, notsign: 0x00ac, hyphen: 0x00ad, registered: 0x00ae, macron: 0x00af, degree: 0x00b0, plusminus: 0x00b1, twosuperior: 0x00b2, threesuperior: 0x00b3, acute: 0x00b4, mu: 0x00b5, paragraph: 0x00b6, periodcentered: 0x00b7, cedilla: 0x00b8, onesuperior: 0x00b9, masculine: 0x00ba, guillemotright: 0x00bb, onequarter: 0x00bc, onehalf: 0x00bd, threequarters: 0x00be, questiondown: 0x00bf, Agrave: 0x00c0, Aacute: 0x00c1, Acircumflex: 0x00c2, Atilde: 0x00c3, Adiaeresis: 0x00c4, Aring: 0x00c5, AE: 0x00c6, Ccedilla: 0x00c7, Egrave: 0x00c8, Eacute: 0x00c9, Ecircumflex: 0x00ca, Ediaeresis: 0x00cb, Igrave: 0x00cc, Iacute: 0x00cd, Icircumflex: 0x00ce, Idiaeresis: 0x00cf, ETH: 0x00d0, Ntilde: 0x00d1, Ograve: 0x00d2, Oacute: 0x00d3, Ocircumflex: 0x00d4, Otilde: 0x00d5, Odiaeresis: 0x00d6, multiply: 0x00d7, Oslash: 0x00d8, Ooblique: 0x00d8, Ugrave: 0x00d9, Uacute: 0x00da, Ucircumflex: 0x00db, Udiaeresis: 0x00dc, Yacute: 0x00dd, THORN: 0x00de, ssharp: 0x00df, agrave: 0x00e0, aacute: 0x00e1, acircumflex: 0x00e2, atilde: 0x00e3, adiaeresis: 0x00e4, aring: 0x00e5, ae: 0x00e6, ccedilla: 0x00e7, egrave: 0x00e8, eacute: 0x00e9, ecircumflex: 0x00ea, ediaeresis: 0x00eb, igrave: 0x00ec, iacute: 0x00ed, icircumflex: 0x00ee, idiaeresis: 0x00ef, eth: 0x00f0, ntilde: 0x00f1, ograve: 0x00f2, oacute: 0x00f3, ocircumflex: 0x00f4, otilde: 0x00f5, odiaeresis: 0x00f6, division: 0x00f7, oslash: 0x00f8, ooblique: 0x00f8, ugrave: 0x00f9, uacute: 0x00fa, ucircumflex: 0x00fb, udiaeresis: 0x00fc, yacute: 0x00fd, thorn: 0x00fe, ydiaeresis: 0x00ff, Aogonek: 0x0104, breve: 0x02d8, Lstroke: 0x0141, Lcaron: 0x013d, Sacute: 0x015a, Scaron: 0x0160, Scedilla: 0x015e, Tcaron: 0x0164, Zacute: 0x0179, Zcaron: 0x017d, Zabovedot: 0x017b, aogonek: 0x0105, ogonek: 0x02db, lstroke: 0x0142, lcaron: 0x013e, sacute: 0x015b, caron: 0x02c7, scaron: 0x0161, scedilla: 0x015f, tcaron: 0x0165, zacute: 0x017a, doubleacute: 0x02dd, zcaron: 0x017e, zabovedot: 0x017c, Racute: 0x0154, Abreve: 0x0102, Lacute: 0x0139, Cacute: 0x0106, Ccaron: 0x010c, Eogonek: 0x0118, Ecaron: 0x011a, Dcaron: 0x010e, Dstroke: 0x0110, Nacute: 0x0143, Ncaron: 0x0147, Odoubleacute: 0x0150, Rcaron: 0x0158, Uring: 0x016e, Udoubleacute: 0x0170, Tcedilla: 0x0162, racute: 0x0155, abreve: 0x0103, lacute: 0x013a, cacute: 0x0107, ccaron: 0x010d, eogonek: 0x0119, ecaron: 0x011b, dcaron: 0x010f, dstroke: 0x0111, nacute: 0x0144, ncaron: 0x0148, odoubleacute: 0x0151, rcaron: 0x0159, uring: 0x016f, udoubleacute: 0x0171, tcedilla: 0x0163, abovedot: 0x02d9, Hstroke: 0x0126, Hcircumflex: 0x0124, Iabovedot: 0x0130, Gbreve: 0x011e, Jcircumflex: 0x0134, hstroke: 0x0127, hcircumflex: 0x0125, idotless: 0x0131, gbreve: 0x011f, jcircumflex: 0x0135, Cabovedot: 0x010a, Ccircumflex: 0x0108, Gabovedot: 0x0120, Gcircumflex: 0x011c, Ubreve: 0x016c, Scircumflex: 0x015c, cabovedot: 0x010b, ccircumflex: 0x0109, gabovedot: 0x0121, gcircumflex: 0x011d, ubreve: 0x016d, scircumflex: 0x015d, kra: 0x0138, Rcedilla: 0x0156, Itilde: 0x0128, Lcedilla: 0x013b, Emacron: 0x0112, Gcedilla: 0x0122, Tslash: 0x0166, rcedilla: 0x0157, itilde: 0x0129, lcedilla: 0x013c, emacron: 0x0113, gcedilla: 0x0123, tslash: 0x0167, ENG: 0x014a, eng: 0x014b, Amacron: 0x0100, Iogonek: 0x012e, Eabovedot: 0x0116, Imacron: 0x012a, Ncedilla: 0x0145, Omacron: 0x014c, Kcedilla: 0x0136, Uogonek: 0x0172, Utilde: 0x0168, Umacron: 0x016a, amacron: 0x0101, iogonek: 0x012f, eabovedot: 0x0117, imacron: 0x012b, ncedilla: 0x0146, omacron: 0x014d, kcedilla: 0x0137, uogonek: 0x0173, utilde: 0x0169, umacron: 0x016b, Wcircumflex: 0x0174, wcircumflex: 0x0175, Ycircumflex: 0x0176, ycircumflex: 0x0177, Babovedot: 0x1e02, babovedot: 0x1e03, Dabovedot: 0x1e0a, dabovedot: 0x1e0b, Fabovedot: 0x1e1e, fabovedot: 0x1e1f, Mabovedot: 0x1e40, mabovedot: 0x1e41, Pabovedot: 0x1e56, pabovedot: 0x1e57, Sabovedot: 0x1e60, sabovedot: 0x1e61, Tabovedot: 0x1e6a, tabovedot: 0x1e6b, Wgrave: 0x1e80, wgrave: 0x1e81, Wacute: 0x1e82, wacute: 0x1e83, Wdiaeresis: 0x1e84, wdiaeresis: 0x1e85, Ygrave: 0x1ef2, ygrave: 0x1ef3, OE: 0x0152, oe: 0x0153, Ydiaeresis: 0x0178, overline: 0x203e, kana_fullstop: 0x3002, kana_openingbracket: 0x300c, kana_closingbracket: 0x300d, kana_comma: 0x3001, kana_conjunctive: 0x30fb, kana_WO: 0x30f2, kana_a: 0x30a1, kana_i: 0x30a3, kana_u: 0x30a5, kana_e: 0x30a7, kana_o: 0x30a9, kana_ya: 0x30e3, kana_yu: 0x30e5, kana_yo: 0x30e7, kana_tsu: 0x30c3, prolongedsound: 0x30fc, kana_A: 0x30a2, kana_I: 0x30a4, kana_U: 0x30a6, kana_E: 0x30a8, kana_O: 0x30aa, kana_KA: 0x30ab, kana_KI: 0x30ad, kana_KU: 0x30af, kana_KE: 0x30b1, kana_KO: 0x30b3, kana_SA: 0x30b5, kana_SHI: 0x30b7, kana_SU: 0x30b9, kana_SE: 0x30bb, kana_SO: 0x30bd, kana_TA: 0x30bf, kana_CHI: 0x30c1, kana_TSU: 0x30c4, kana_TE: 0x30c6, kana_TO: 0x30c8, kana_NA: 0x30ca, kana_NI: 0x30cb, kana_NU: 0x30cc, kana_NE: 0x30cd, kana_NO: 0x30ce, kana_HA: 0x30cf, kana_HI: 0x30d2, kana_FU: 0x30d5, kana_HE: 0x30d8, kana_HO: 0x30db, kana_MA: 0x30de, kana_MI: 0x30df, kana_MU: 0x30e0, kana_ME: 0x30e1, kana_MO: 0x30e2, kana_YA: 0x30e4, kana_YU: 0x30e6, kana_YO: 0x30e8, kana_RA: 0x30e9, kana_RI: 0x30ea, kana_RU: 0x30eb, kana_RE: 0x30ec, kana_RO: 0x30ed, kana_WA: 0x30ef, kana_N: 0x30f3, voicedsound: 0x309b, semivoicedsound: 0x309c, Farsi_0: 0x06f0, Farsi_1: 0x06f1, Farsi_2: 0x06f2, Farsi_3: 0x06f3, Farsi_4: 0x06f4, Farsi_5: 0x06f5, Farsi_6: 0x06f6, Farsi_7: 0x06f7, Farsi_8: 0x06f8, Farsi_9: 0x06f9, Arabic_percent: 0x066a, Arabic_superscript_alef: 0x0670, Arabic_tteh: 0x0679, Arabic_peh: 0x067e, Arabic_tcheh: 0x0686, Arabic_ddal: 0x0688, Arabic_rreh: 0x0691, Arabic_comma: 0x060c, Arabic_fullstop: 0x06d4, Arabic_0: 0x0660, Arabic_1: 0x0661, Arabic_2: 0x0662, Arabic_3: 0x0663, Arabic_4: 0x0664, Arabic_5: 0x0665, Arabic_6: 0x0666, Arabic_7: 0x0667, Arabic_8: 0x0668, Arabic_9: 0x0669, Arabic_semicolon: 0x061b, Arabic_question_mark: 0x061f, Arabic_hamza: 0x0621, Arabic_maddaonalef: 0x0622, Arabic_hamzaonalef: 0x0623, Arabic_hamzaonwaw: 0x0624, Arabic_hamzaunderalef: 0x0625, Arabic_hamzaonyeh: 0x0626, Arabic_alef: 0x0627, Arabic_beh: 0x0628, Arabic_tehmarbuta: 0x0629, Arabic_teh: 0x062a, Arabic_theh: 0x062b, Arabic_jeem: 0x062c, Arabic_hah: 0x062d, Arabic_khah: 0x062e, Arabic_dal: 0x062f, Arabic_thal: 0x0630, Arabic_ra: 0x0631, Arabic_zain: 0x0632, Arabic_seen: 0x0633, Arabic_sheen: 0x0634, Arabic_sad: 0x0635, Arabic_dad: 0x0636, Arabic_tah: 0x0637, Arabic_zah: 0x0638, Arabic_ain: 0x0639, Arabic_ghain: 0x063a, Arabic_tatweel: 0x0640, Arabic_feh: 0x0641, Arabic_qaf: 0x0642, Arabic_kaf: 0x0643, Arabic_lam: 0x0644, Arabic_meem: 0x0645, Arabic_noon: 0x0646, Arabic_ha: 0x0647, Arabic_waw: 0x0648, Arabic_alefmaksura: 0x0649, Arabic_yeh: 0x064a, Arabic_fathatan: 0x064b, Arabic_dammatan: 0x064c, Arabic_kasratan: 0x064d, Arabic_fatha: 0x064e, Arabic_damma: 0x064f, Arabic_kasra: 0x0650, Arabic_shadda: 0x0651, Arabic_sukun: 0x0652, Arabic_madda_above: 0x0653, Arabic_hamza_above: 0x0654, Arabic_hamza_below: 0x0655, Arabic_jeh: 0x0698, Arabic_veh: 0x06a4, Arabic_keheh: 0x06a9, Arabic_gaf: 0x06af, Arabic_noon_ghunna: 0x06ba, Arabic_heh_doachashmee: 0x06be, Farsi_yeh: 0x06cc, Arabic_farsi_yeh: 0x06cc, Arabic_yeh_baree: 0x06d2, Arabic_heh_goal: 0x06c1, Cyrillic_GHE_bar: 0x0492, Cyrillic_ghe_bar: 0x0493, Cyrillic_ZHE_descender: 0x0496, Cyrillic_zhe_descender: 0x0497, Cyrillic_KA_descender: 0x049a, Cyrillic_ka_descender: 0x049b, Cyrillic_KA_vertstroke: 0x049c, Cyrillic_ka_vertstroke: 0x049d, Cyrillic_EN_descender: 0x04a2, Cyrillic_en_descender: 0x04a3, Cyrillic_U_straight: 0x04ae, Cyrillic_u_straight: 0x04af, Cyrillic_U_straight_bar: 0x04b0, Cyrillic_u_straight_bar: 0x04b1, Cyrillic_HA_descender: 0x04b2, Cyrillic_ha_descender: 0x04b3, Cyrillic_CHE_descender: 0x04b6, Cyrillic_che_descender: 0x04b7, Cyrillic_CHE_vertstroke: 0x04b8, Cyrillic_che_vertstroke: 0x04b9, Cyrillic_SHHA: 0x04ba, Cyrillic_shha: 0x04bb, Cyrillic_SCHWA: 0x04d8, Cyrillic_schwa: 0x04d9, Cyrillic_I_macron: 0x04e2, Cyrillic_i_macron: 0x04e3, Cyrillic_O_bar: 0x04e8, Cyrillic_o_bar: 0x04e9, Cyrillic_U_macron: 0x04ee, Cyrillic_u_macron: 0x04ef, Serbian_dje: 0x0452, Macedonia_gje: 0x0453, Cyrillic_io: 0x0451, Ukrainian_ie: 0x0454, Macedonia_dse: 0x0455, Ukrainian_i: 0x0456, Ukrainian_yi: 0x0457, Cyrillic_je: 0x0458, Cyrillic_lje: 0x0459, Cyrillic_nje: 0x045a, Serbian_tshe: 0x045b, Macedonia_kje: 0x045c, Ukrainian_ghe_with_upturn: 0x0491, Byelorussian_shortu: 0x045e, Cyrillic_dzhe: 0x045f, numerosign: 0x2116, Serbian_DJE: 0x0402, Macedonia_GJE: 0x0403, Cyrillic_IO: 0x0401, Ukrainian_IE: 0x0404, Macedonia_DSE: 0x0405, Ukrainian_I: 0x0406, Ukrainian_YI: 0x0407, Cyrillic_JE: 0x0408, Cyrillic_LJE: 0x0409, Cyrillic_NJE: 0x040a, Serbian_TSHE: 0x040b, Macedonia_KJE: 0x040c, Ukrainian_GHE_WITH_UPTURN: 0x0490, Byelorussian_SHORTU: 0x040e, Cyrillic_DZHE: 0x040f, Cyrillic_yu: 0x044e, Cyrillic_a: 0x0430, Cyrillic_be: 0x0431, Cyrillic_tse: 0x0446, Cyrillic_de: 0x0434, Cyrillic_ie: 0x0435, Cyrillic_ef: 0x0444, Cyrillic_ghe: 0x0433, Cyrillic_ha: 0x0445, Cyrillic_i: 0x0438, Cyrillic_shorti: 0x0439, Cyrillic_ka: 0x043a, Cyrillic_el: 0x043b, Cyrillic_em: 0x043c, Cyrillic_en: 0x043d, Cyrillic_o: 0x043e, Cyrillic_pe: 0x043f, Cyrillic_ya: 0x044f, Cyrillic_er: 0x0440, Cyrillic_es: 0x0441, Cyrillic_te: 0x0442, Cyrillic_u: 0x0443, Cyrillic_zhe: 0x0436, Cyrillic_ve: 0x0432, Cyrillic_softsign: 0x044c, Cyrillic_yeru: 0x044b, Cyrillic_ze: 0x0437, Cyrillic_sha: 0x0448, Cyrillic_e: 0x044d, Cyrillic_shcha: 0x0449, Cyrillic_che: 0x0447, Cyrillic_hardsign: 0x044a, Cyrillic_YU: 0x042e, Cyrillic_A: 0x0410, Cyrillic_BE: 0x0411, Cyrillic_TSE: 0x0426, Cyrillic_DE: 0x0414, Cyrillic_IE: 0x0415, Cyrillic_EF: 0x0424, Cyrillic_GHE: 0x0413, Cyrillic_HA: 0x0425, Cyrillic_I: 0x0418, Cyrillic_SHORTI: 0x0419, Cyrillic_KA: 0x041a, Cyrillic_EL: 0x041b, Cyrillic_EM: 0x041c, Cyrillic_EN: 0x041d, Cyrillic_O: 0x041e, Cyrillic_PE: 0x041f, Cyrillic_YA: 0x042f, Cyrillic_ER: 0x0420, Cyrillic_ES: 0x0421, Cyrillic_TE: 0x0422, Cyrillic_U: 0x0423, Cyrillic_ZHE: 0x0416, Cyrillic_VE: 0x0412, Cyrillic_SOFTSIGN: 0x042c, Cyrillic_YERU: 0x042b, Cyrillic_ZE: 0x0417, Cyrillic_SHA: 0x0428, Cyrillic_E: 0x042d, Cyrillic_SHCHA: 0x0429, Cyrillic_CHE: 0x0427, Cyrillic_HARDSIGN: 0x042a, Greek_ALPHAaccent: 0x0386, Greek_EPSILONaccent: 0x0388, Greek_ETAaccent: 0x0389, Greek_IOTAaccent: 0x038a, Greek_IOTAdieresis: 0x03aa, Greek_OMICRONaccent: 0x038c, Greek_UPSILONaccent: 0x038e, Greek_UPSILONdieresis: 0x03ab, Greek_OMEGAaccent: 0x038f, Greek_accentdieresis: 0x0385, Greek_horizbar: 0x2015, Greek_alphaaccent: 0x03ac, Greek_epsilonaccent: 0x03ad, Greek_etaaccent: 0x03ae, Greek_iotaaccent: 0x03af, Greek_iotadieresis: 0x03ca, Greek_iotaaccentdieresis: 0x0390, Greek_omicronaccent: 0x03cc, Greek_upsilonaccent: 0x03cd, Greek_upsilondieresis: 0x03cb, Greek_upsilonaccentdieresis: 0x03b0, Greek_omegaaccent: 0x03ce, Greek_ALPHA: 0x0391, Greek_BETA: 0x0392, Greek_GAMMA: 0x0393, Greek_DELTA: 0x0394, Greek_EPSILON: 0x0395, Greek_ZETA: 0x0396, Greek_ETA: 0x0397, Greek_THETA: 0x0398, Greek_IOTA: 0x0399, Greek_KAPPA: 0x039a, Greek_LAMDA: 0x039b, Greek_LAMBDA: 0x039b, Greek_MU: 0x039c, Greek_NU: 0x039d, Greek_XI: 0x039e, Greek_OMICRON: 0x039f, Greek_PI: 0x03a0, Greek_RHO: 0x03a1, Greek_SIGMA: 0x03a3, Greek_TAU: 0x03a4, Greek_UPSILON: 0x03a5, Greek_PHI: 0x03a6, Greek_CHI: 0x03a7, Greek_PSI: 0x03a8, Greek_OMEGA: 0x03a9, Greek_alpha: 0x03b1, Greek_beta: 0x03b2, Greek_gamma: 0x03b3, Greek_delta: 0x03b4, Greek_epsilon: 0x03b5, Greek_zeta: 0x03b6, Greek_eta: 0x03b7, Greek_theta: 0x03b8, Greek_iota: 0x03b9, Greek_kappa: 0x03ba, Greek_lamda: 0x03bb, Greek_lambda: 0x03bb, Greek_mu: 0x03bc, Greek_nu: 0x03bd, Greek_xi: 0x03be, Greek_omicron: 0x03bf, Greek_pi: 0x03c0, Greek_rho: 0x03c1, Greek_sigma: 0x03c3, Greek_finalsmallsigma: 0x03c2, Greek_tau: 0x03c4, Greek_upsilon: 0x03c5, Greek_phi: 0x03c6, Greek_chi: 0x03c7, Greek_psi: 0x03c8, Greek_omega: 0x03c9, leftradical: 0x23b7, topintegral: 0x2320, botintegral: 0x2321, topleftsqbracket: 0x23a1, botleftsqbracket: 0x23a3, toprightsqbracket: 0x23a4, botrightsqbracket: 0x23a6, topleftparens: 0x239b, botleftparens: 0x239d, toprightparens: 0x239e, botrightparens: 0x23a0, leftmiddlecurlybrace: 0x23a8, rightmiddlecurlybrace: 0x23ac, lessthanequal: 0x2264, notequal: 0x2260, greaterthanequal: 0x2265, integral: 0x222b, therefore: 0x2234, variation: 0x221d, infinity: 0x221e, nabla: 0x2207, approximate: 0x223c, similarequal: 0x2243, ifonlyif: 0x21d4, implies: 0x21d2, identical: 0x2261, radical: 0x221a, includedin: 0x2282, includes: 0x2283, intersection: 0x2229, union: 0x222a, logicaland: 0x2227, logicalor: 0x2228, partialderivative: 0x2202, function: 0x0192, leftarrow: 0x2190, uparrow: 0x2191, rightarrow: 0x2192, downarrow: 0x2193, soliddiamond: 0x25c6, checkerboard: 0x2592, ht: 0x2409, ff: 0x240c, cr: 0x240d, lf: 0x240a, nl: 0x2424, vt: 0x240b, lowrightcorner: 0x2518, uprightcorner: 0x2510, upleftcorner: 0x250c, lowleftcorner: 0x2514, crossinglines: 0x253c, horizlinescan1: 0x23ba, horizlinescan3: 0x23bb, horizlinescan5: 0x2500, horizlinescan7: 0x23bc, horizlinescan9: 0x23bd, leftt: 0x251c, rightt: 0x2524, bott: 0x2534, topt: 0x252c, vertbar: 0x2502, emspace: 0x2003, enspace: 0x2002, em3space: 0x2004, em4space: 0x2005, digitspace: 0x2007, punctspace: 0x2008, thinspace: 0x2009, hairspace: 0x200a, emdash: 0x2014, endash: 0x2013, ellipsis: 0x2026, doubbaselinedot: 0x2025, onethird: 0x2153, twothirds: 0x2154, onefifth: 0x2155, twofifths: 0x2156, threefifths: 0x2157, fourfifths: 0x2158, onesixth: 0x2159, fivesixths: 0x215a, careof: 0x2105, figdash: 0x2012, oneeighth: 0x215b, threeeighths: 0x215c, fiveeighths: 0x215d, seveneighths: 0x215e, trademark: 0x2122, leftsinglequotemark: 0x2018, rightsinglequotemark: 0x2019, leftdoublequotemark: 0x201c, rightdoublequotemark: 0x201d, prescription: 0x211e, permille: 0x2030, minutes: 0x2032, seconds: 0x2033, latincross: 0x271d, club: 0x2663, diamond: 0x2666, heart: 0x2665, maltesecross: 0x2720, dagger: 0x2020, doubledagger: 0x2021, checkmark: 0x2713, ballotcross: 0x2717, musicalsharp: 0x266f, musicalflat: 0x266d, malesymbol: 0x2642, femalesymbol: 0x2640, telephone: 0x260e, telephonerecorder: 0x2315, phonographcopyright: 0x2117, caret: 0x2038, singlelowquotemark: 0x201a, doublelowquotemark: 0x201e, downtack: 0x22a4, downstile: 0x230a, jot: 0x2218, quad: 0x2395, uptack: 0x22a5, circle: 0x25cb, upstile: 0x2308, lefttack: 0x22a3, righttack: 0x22a2, hebrew_doublelowline: 0x2017, hebrew_aleph: 0x05d0, hebrew_bet: 0x05d1, hebrew_gimel: 0x05d2, hebrew_dalet: 0x05d3, hebrew_he: 0x05d4, hebrew_waw: 0x05d5, hebrew_zain: 0x05d6, hebrew_chet: 0x05d7, hebrew_tet: 0x05d8, hebrew_yod: 0x05d9, hebrew_finalkaph: 0x05da, hebrew_kaph: 0x05db, hebrew_lamed: 0x05dc, hebrew_finalmem: 0x05dd, hebrew_mem: 0x05de, hebrew_finalnun: 0x05df, hebrew_nun: 0x05e0, hebrew_samech: 0x05e1, hebrew_ayin: 0x05e2, hebrew_finalpe: 0x05e3, hebrew_pe: 0x05e4, hebrew_finalzade: 0x05e5, hebrew_zade: 0x05e6, hebrew_qoph: 0x05e7, hebrew_resh: 0x05e8, hebrew_shin: 0x05e9, hebrew_taw: 0x05ea, Thai_kokai: 0x0e01, Thai_khokhai: 0x0e02, Thai_khokhuat: 0x0e03, Thai_khokhwai: 0x0e04, Thai_khokhon: 0x0e05, Thai_khorakhang: 0x0e06, Thai_ngongu: 0x0e07, Thai_chochan: 0x0e08, Thai_choching: 0x0e09, Thai_chochang: 0x0e0a, Thai_soso: 0x0e0b, Thai_chochoe: 0x0e0c, Thai_yoying: 0x0e0d, Thai_dochada: 0x0e0e, Thai_topatak: 0x0e0f, Thai_thothan: 0x0e10, Thai_thonangmontho: 0x0e11, Thai_thophuthao: 0x0e12, Thai_nonen: 0x0e13, Thai_dodek: 0x0e14, Thai_totao: 0x0e15, Thai_thothung: 0x0e16, Thai_thothahan: 0x0e17, Thai_thothong: 0x0e18, Thai_nonu: 0x0e19, Thai_bobaimai: 0x0e1a, Thai_popla: 0x0e1b, Thai_phophung: 0x0e1c, Thai_fofa: 0x0e1d, Thai_phophan: 0x0e1e, Thai_fofan: 0x0e1f, Thai_phosamphao: 0x0e20, Thai_moma: 0x0e21, Thai_yoyak: 0x0e22, Thai_rorua: 0x0e23, Thai_ru: 0x0e24, Thai_loling: 0x0e25, Thai_lu: 0x0e26, Thai_wowaen: 0x0e27, Thai_sosala: 0x0e28, Thai_sorusi: 0x0e29, Thai_sosua: 0x0e2a, Thai_hohip: 0x0e2b, Thai_lochula: 0x0e2c, Thai_oang: 0x0e2d, Thai_honokhuk: 0x0e2e, Thai_paiyannoi: 0x0e2f, Thai_saraa: 0x0e30, Thai_maihanakat: 0x0e31, Thai_saraaa: 0x0e32, Thai_saraam: 0x0e33, Thai_sarai: 0x0e34, Thai_saraii: 0x0e35, Thai_saraue: 0x0e36, Thai_sarauee: 0x0e37, Thai_sarau: 0x0e38, Thai_sarauu: 0x0e39, Thai_phinthu: 0x0e3a, Thai_baht: 0x0e3f, Thai_sarae: 0x0e40, Thai_saraae: 0x0e41, Thai_sarao: 0x0e42, Thai_saraaimaimuan: 0x0e43, Thai_saraaimaimalai: 0x0e44, Thai_lakkhangyao: 0x0e45, Thai_maiyamok: 0x0e46, Thai_maitaikhu: 0x0e47, Thai_maiek: 0x0e48, Thai_maitho: 0x0e49, Thai_maitri: 0x0e4a, Thai_maichattawa: 0x0e4b, Thai_thanthakhat: 0x0e4c, Thai_nikhahit: 0x0e4d, Thai_leksun: 0x0e50, Thai_leknung: 0x0e51, Thai_leksong: 0x0e52, Thai_leksam: 0x0e53, Thai_leksi: 0x0e54, Thai_lekha: 0x0e55, Thai_lekhok: 0x0e56, Thai_lekchet: 0x0e57, Thai_lekpaet: 0x0e58, Thai_lekkao: 0x0e59, Armenian_ligature_ew: 0x0587, Armenian_full_stop: 0x0589, Armenian_verjaket: 0x0589, Armenian_separation_mark: 0x055d, Armenian_but: 0x055d, Armenian_hyphen: 0x058a, Armenian_yentamna: 0x058a, Armenian_exclam: 0x055c, Armenian_amanak: 0x055c, Armenian_accent: 0x055b, Armenian_shesht: 0x055b, Armenian_question: 0x055e, Armenian_paruyk: 0x055e, Armenian_AYB: 0x0531, Armenian_ayb: 0x0561, Armenian_BEN: 0x0532, Armenian_ben: 0x0562, Armenian_GIM: 0x0533, Armenian_gim: 0x0563, Armenian_DA: 0x0534, Armenian_da: 0x0564, Armenian_YECH: 0x0535, Armenian_yech: 0x0565, Armenian_ZA: 0x0536, Armenian_za: 0x0566, Armenian_E: 0x0537, Armenian_e: 0x0567, Armenian_AT: 0x0538, Armenian_at: 0x0568, Armenian_TO: 0x0539, Armenian_to: 0x0569, Armenian_ZHE: 0x053a, Armenian_zhe: 0x056a, Armenian_INI: 0x053b, Armenian_ini: 0x056b, Armenian_LYUN: 0x053c, Armenian_lyun: 0x056c, Armenian_KHE: 0x053d, Armenian_khe: 0x056d, Armenian_TSA: 0x053e, Armenian_tsa: 0x056e, Armenian_KEN: 0x053f, Armenian_ken: 0x056f, Armenian_HO: 0x0540, Armenian_ho: 0x0570, Armenian_DZA: 0x0541, Armenian_dza: 0x0571, Armenian_GHAT: 0x0542, Armenian_ghat: 0x0572, Armenian_TCHE: 0x0543, Armenian_tche: 0x0573, Armenian_MEN: 0x0544, Armenian_men: 0x0574, Armenian_HI: 0x0545, Armenian_hi: 0x0575, Armenian_NU: 0x0546, Armenian_nu: 0x0576, Armenian_SHA: 0x0547, Armenian_sha: 0x0577, Armenian_VO: 0x0548, Armenian_vo: 0x0578, Armenian_CHA: 0x0549, Armenian_cha: 0x0579, Armenian_PE: 0x054a, Armenian_pe: 0x057a, Armenian_JE: 0x054b, Armenian_je: 0x057b, Armenian_RA: 0x054c, Armenian_ra: 0x057c, Armenian_SE: 0x054d, Armenian_se: 0x057d, Armenian_VEV: 0x054e, Armenian_vev: 0x057e, Armenian_TYUN: 0x054f, Armenian_tyun: 0x057f, Armenian_RE: 0x0550, Armenian_re: 0x0580, Armenian_TSO: 0x0551, Armenian_tso: 0x0581, Armenian_VYUN: 0x0552, Armenian_vyun: 0x0582, Armenian_PYUR: 0x0553, Armenian_pyur: 0x0583, Armenian_KE: 0x0554, Armenian_ke: 0x0584, Armenian_O: 0x0555, Armenian_o: 0x0585, Armenian_FE: 0x0556, Armenian_fe: 0x0586, Armenian_apostrophe: 0x055a, Georgian_an: 0x10d0, Georgian_ban: 0x10d1, Georgian_gan: 0x10d2, Georgian_don: 0x10d3, Georgian_en: 0x10d4, Georgian_vin: 0x10d5, Georgian_zen: 0x10d6, Georgian_tan: 0x10d7, Georgian_in: 0x10d8, Georgian_kan: 0x10d9, Georgian_las: 0x10da, Georgian_man: 0x10db, Georgian_nar: 0x10dc, Georgian_on: 0x10dd, Georgian_par: 0x10de, Georgian_zhar: 0x10df, Georgian_rae: 0x10e0, Georgian_san: 0x10e1, Georgian_tar: 0x10e2, Georgian_un: 0x10e3, Georgian_phar: 0x10e4, Georgian_khar: 0x10e5, Georgian_ghan: 0x10e6, Georgian_qar: 0x10e7, Georgian_shin: 0x10e8, Georgian_chin: 0x10e9, Georgian_can: 0x10ea, Georgian_jil: 0x10eb, Georgian_cil: 0x10ec, Georgian_char: 0x10ed, Georgian_xan: 0x10ee, Georgian_jhan: 0x10ef, Georgian_hae: 0x10f0, Georgian_he: 0x10f1, Georgian_hie: 0x10f2, Georgian_we: 0x10f3, Georgian_har: 0x10f4, Georgian_hoe: 0x10f5, Georgian_fi: 0x10f6, Xabovedot: 0x1e8a, Ibreve: 0x012c, Zstroke: 0x01b5, Gcaron: 0x01e6, Ocaron: 0x01d2, Obarred: 0x019f, xabovedot: 0x1e8b, ibreve: 0x012d, zstroke: 0x01b6, gcaron: 0x01e7, ocaron: 0x01d2, obarred: 0x0275, SCHWA: 0x018f, schwa: 0x0259, EZH: 0x01b7, ezh: 0x0292, Lbelowdot: 0x1e36, lbelowdot: 0x1e37, Abelowdot: 0x1ea0, abelowdot: 0x1ea1, Ahook: 0x1ea2, ahook: 0x1ea3, Acircumflexacute: 0x1ea4, acircumflexacute: 0x1ea5, Acircumflexgrave: 0x1ea6, acircumflexgrave: 0x1ea7, Acircumflexhook: 0x1ea8, acircumflexhook: 0x1ea9, Acircumflextilde: 0x1eaa, acircumflextilde: 0x1eab, Acircumflexbelowdot: 0x1eac, acircumflexbelowdot: 0x1ead, Abreveacute: 0x1eae, abreveacute: 0x1eaf, Abrevegrave: 0x1eb0, abrevegrave: 0x1eb1, Abrevehook: 0x1eb2, abrevehook: 0x1eb3, Abrevetilde: 0x1eb4, abrevetilde: 0x1eb5, Abrevebelowdot: 0x1eb6, abrevebelowdot: 0x1eb7, Ebelowdot: 0x1eb8, ebelowdot: 0x1eb9, Ehook: 0x1eba, ehook: 0x1ebb, Etilde: 0x1ebc, etilde: 0x1ebd, Ecircumflexacute: 0x1ebe, ecircumflexacute: 0x1ebf, Ecircumflexgrave: 0x1ec0, ecircumflexgrave: 0x1ec1, Ecircumflexhook: 0x1ec2, ecircumflexhook: 0x1ec3, Ecircumflextilde: 0x1ec4, ecircumflextilde: 0x1ec5, Ecircumflexbelowdot: 0x1ec6, ecircumflexbelowdot: 0x1ec7, Ihook: 0x1ec8, ihook: 0x1ec9, Ibelowdot: 0x1eca, ibelowdot: 0x1ecb, Obelowdot: 0x1ecc, obelowdot: 0x1ecd, Ohook: 0x1ece, ohook: 0x1ecf, Ocircumflexacute: 0x1ed0, ocircumflexacute: 0x1ed1, Ocircumflexgrave: 0x1ed2, ocircumflexgrave: 0x1ed3, Ocircumflexhook: 0x1ed4, ocircumflexhook: 0x1ed5, Ocircumflextilde: 0x1ed6, ocircumflextilde: 0x1ed7, Ocircumflexbelowdot: 0x1ed8, ocircumflexbelowdot: 0x1ed9, Ohornacute: 0x1eda, ohornacute: 0x1edb, Ohorngrave: 0x1edc, ohorngrave: 0x1edd, Ohornhook: 0x1ede, ohornhook: 0x1edf, Ohorntilde: 0x1ee0, ohorntilde: 0x1ee1, Ohornbelowdot: 0x1ee2, ohornbelowdot: 0x1ee3, Ubelowdot: 0x1ee4, ubelowdot: 0x1ee5, Uhook: 0x1ee6, uhook: 0x1ee7, Uhornacute: 0x1ee8, uhornacute: 0x1ee9, Uhorngrave: 0x1eea, uhorngrave: 0x1eeb, Uhornhook: 0x1eec, uhornhook: 0x1eed, Uhorntilde: 0x1eee, uhorntilde: 0x1eef, Uhornbelowdot: 0x1ef0, uhornbelowdot: 0x1ef1, Ybelowdot: 0x1ef4, ybelowdot: 0x1ef5, Yhook: 0x1ef6, yhook: 0x1ef7, Ytilde: 0x1ef8, ytilde: 0x1ef9, Ohorn: 0x01a0, ohorn: 0x01a1, Uhorn: 0x01af, uhorn: 0x01b0, EcuSign: 0x20a0, ColonSign: 0x20a1, CruzeiroSign: 0x20a2, FFrancSign: 0x20a3, LiraSign: 0x20a4, MillSign: 0x20a5, NairaSign: 0x20a6, PesetaSign: 0x20a7, RupeeSign: 0x20a8, WonSign: 0x20a9, NewSheqelSign: 0x20aa, DongSign: 0x20ab, EuroSign: 0x20ac, zerosuperior: 0x2070, foursuperior: 0x2074, fivesuperior: 0x2075, sixsuperior: 0x2076, sevensuperior: 0x2077, eightsuperior: 0x2078, ninesuperior: 0x2079, zerosubscript: 0x2080, onesubscript: 0x2081, twosubscript: 0x2082, threesubscript: 0x2083, foursubscript: 0x2084, fivesubscript: 0x2085, sixsubscript: 0x2086, sevensubscript: 0x2087, eightsubscript: 0x2088, ninesubscript: 0x2089, partdifferential: 0x2202, emptyset: 0x2205, elementof: 0x2208, notelementof: 0x2209, containsas: 0x220b, squareroot: 0x221a, cuberoot: 0x221b, fourthroot: 0x221c, dintegral: 0x222c, tintegral: 0x222d, because: 0x2235, approxeq: 0x2245, notapproxeq: 0x2247, notidentical: 0x2262, stricteq: 0x2263, braille_blank: 0x2800, braille_dots_1: 0x2801, braille_dots_2: 0x2802, braille_dots_12: 0x2803, braille_dots_3: 0x2804, braille_dots_13: 0x2805, braille_dots_23: 0x2806, braille_dots_123: 0x2807, braille_dots_4: 0x2808, braille_dots_14: 0x2809, braille_dots_24: 0x280a, braille_dots_124: 0x280b, braille_dots_34: 0x280c, braille_dots_134: 0x280d, braille_dots_234: 0x280e, braille_dots_1234: 0x280f, braille_dots_5: 0x2810, braille_dots_15: 0x2811, braille_dots_25: 0x2812, braille_dots_125: 0x2813, braille_dots_35: 0x2814, braille_dots_135: 0x2815, braille_dots_235: 0x2816, braille_dots_1235: 0x2817, braille_dots_45: 0x2818, braille_dots_145: 0x2819, braille_dots_245: 0x281a, braille_dots_1245: 0x281b, braille_dots_345: 0x281c, braille_dots_1345: 0x281d, braille_dots_2345: 0x281e, braille_dots_12345: 0x281f, braille_dots_6: 0x2820, braille_dots_16: 0x2821, braille_dots_26: 0x2822, braille_dots_126: 0x2823, braille_dots_36: 0x2824, braille_dots_136: 0x2825, braille_dots_236: 0x2826, braille_dots_1236: 0x2827, braille_dots_46: 0x2828, braille_dots_146: 0x2829, braille_dots_246: 0x282a, braille_dots_1246: 0x282b, braille_dots_346: 0x282c, braille_dots_1346: 0x282d, braille_dots_2346: 0x282e, braille_dots_12346: 0x282f, braille_dots_56: 0x2830, braille_dots_156: 0x2831, braille_dots_256: 0x2832, braille_dots_1256: 0x2833, braille_dots_356: 0x2834, braille_dots_1356: 0x2835, braille_dots_2356: 0x2836, braille_dots_12356: 0x2837, braille_dots_456: 0x2838, braille_dots_1456: 0x2839, braille_dots_2456: 0x283a, braille_dots_12456: 0x283b, braille_dots_3456: 0x283c, braille_dots_13456: 0x283d, braille_dots_23456: 0x283e, braille_dots_123456: 0x283f, braille_dots_7: 0x2840, braille_dots_17: 0x2841, braille_dots_27: 0x2842, braille_dots_127: 0x2843, braille_dots_37: 0x2844, braille_dots_137: 0x2845, braille_dots_237: 0x2846, braille_dots_1237: 0x2847, braille_dots_47: 0x2848, braille_dots_147: 0x2849, braille_dots_247: 0x284a, braille_dots_1247: 0x284b, braille_dots_347: 0x284c, braille_dots_1347: 0x284d, braille_dots_2347: 0x284e, braille_dots_12347: 0x284f, braille_dots_57: 0x2850, braille_dots_157: 0x2851, braille_dots_257: 0x2852, braille_dots_1257: 0x2853, braille_dots_357: 0x2854, braille_dots_1357: 0x2855, braille_dots_2357: 0x2856, braille_dots_12357: 0x2857, braille_dots_457: 0x2858, braille_dots_1457: 0x2859, braille_dots_2457: 0x285a, braille_dots_12457: 0x285b, braille_dots_3457: 0x285c, braille_dots_13457: 0x285d, braille_dots_23457: 0x285e, braille_dots_123457: 0x285f, braille_dots_67: 0x2860, braille_dots_167: 0x2861, braille_dots_267: 0x2862, braille_dots_1267: 0x2863, braille_dots_367: 0x2864, braille_dots_1367: 0x2865, braille_dots_2367: 0x2866, braille_dots_12367: 0x2867, braille_dots_467: 0x2868, braille_dots_1467: 0x2869, braille_dots_2467: 0x286a, braille_dots_12467: 0x286b, braille_dots_3467: 0x286c, braille_dots_13467: 0x286d, braille_dots_23467: 0x286e, braille_dots_123467: 0x286f, braille_dots_567: 0x2870, braille_dots_1567: 0x2871, braille_dots_2567: 0x2872, braille_dots_12567: 0x2873, braille_dots_3567: 0x2874, braille_dots_13567: 0x2875, braille_dots_23567: 0x2876, braille_dots_123567: 0x2877, braille_dots_4567: 0x2878, braille_dots_14567: 0x2879, braille_dots_24567: 0x287a, braille_dots_124567: 0x287b, braille_dots_34567: 0x287c, braille_dots_134567: 0x287d, braille_dots_234567: 0x287e, braille_dots_1234567: 0x287f, braille_dots_8: 0x2880, braille_dots_18: 0x2881, braille_dots_28: 0x2882, braille_dots_128: 0x2883, braille_dots_38: 0x2884, braille_dots_138: 0x2885, braille_dots_238: 0x2886, braille_dots_1238: 0x2887, braille_dots_48: 0x2888, braille_dots_148: 0x2889, braille_dots_248: 0x288a, braille_dots_1248: 0x288b, braille_dots_348: 0x288c, braille_dots_1348: 0x288d, braille_dots_2348: 0x288e, braille_dots_12348: 0x288f, braille_dots_58: 0x2890, braille_dots_158: 0x2891, braille_dots_258: 0x2892, braille_dots_1258: 0x2893, braille_dots_358: 0x2894, braille_dots_1358: 0x2895, braille_dots_2358: 0x2896, braille_dots_12358: 0x2897, braille_dots_458: 0x2898, braille_dots_1458: 0x2899, braille_dots_2458: 0x289a, braille_dots_12458: 0x289b, braille_dots_3458: 0x289c, braille_dots_13458: 0x289d, braille_dots_23458: 0x289e, braille_dots_123458: 0x289f, braille_dots_68: 0x28a0, braille_dots_168: 0x28a1, braille_dots_268: 0x28a2, braille_dots_1268: 0x28a3, braille_dots_368: 0x28a4, braille_dots_1368: 0x28a5, braille_dots_2368: 0x28a6, braille_dots_12368: 0x28a7, braille_dots_468: 0x28a8, braille_dots_1468: 0x28a9, braille_dots_2468: 0x28aa, braille_dots_12468: 0x28ab, braille_dots_3468: 0x28ac, braille_dots_13468: 0x28ad, braille_dots_23468: 0x28ae, braille_dots_123468: 0x28af, braille_dots_568: 0x28b0, braille_dots_1568: 0x28b1, braille_dots_2568: 0x28b2, braille_dots_12568: 0x28b3, braille_dots_3568: 0x28b4, braille_dots_13568: 0x28b5, braille_dots_23568: 0x28b6, braille_dots_123568: 0x28b7, braille_dots_4568: 0x28b8, braille_dots_14568: 0x28b9, braille_dots_24568: 0x28ba, braille_dots_124568: 0x28bb, braille_dots_34568: 0x28bc, braille_dots_134568: 0x28bd, braille_dots_234568: 0x28be, braille_dots_1234568: 0x28bf, braille_dots_78: 0x28c0, braille_dots_178: 0x28c1, braille_dots_278: 0x28c2, braille_dots_1278: 0x28c3, braille_dots_378: 0x28c4, braille_dots_1378: 0x28c5, braille_dots_2378: 0x28c6, braille_dots_12378: 0x28c7, braille_dots_478: 0x28c8, braille_dots_1478: 0x28c9, braille_dots_2478: 0x28ca, braille_dots_12478: 0x28cb, braille_dots_3478: 0x28cc, braille_dots_13478: 0x28cd, braille_dots_23478: 0x28ce, braille_dots_123478: 0x28cf, braille_dots_578: 0x28d0, braille_dots_1578: 0x28d1, braille_dots_2578: 0x28d2, braille_dots_12578: 0x28d3, braille_dots_3578: 0x28d4, braille_dots_13578: 0x28d5, braille_dots_23578: 0x28d6, braille_dots_123578: 0x28d7, braille_dots_4578: 0x28d8, braille_dots_14578: 0x28d9, braille_dots_24578: 0x28da, braille_dots_124578: 0x28db, braille_dots_34578: 0x28dc, braille_dots_134578: 0x28dd, braille_dots_234578: 0x28de, braille_dots_1234578: 0x28df, braille_dots_678: 0x28e0, braille_dots_1678: 0x28e1, braille_dots_2678: 0x28e2, braille_dots_12678: 0x28e3, braille_dots_3678: 0x28e4, braille_dots_13678: 0x28e5, braille_dots_23678: 0x28e6, braille_dots_123678: 0x28e7, braille_dots_4678: 0x28e8, braille_dots_14678: 0x28e9, braille_dots_24678: 0x28ea, braille_dots_124678: 0x28eb, braille_dots_34678: 0x28ec, braille_dots_134678: 0x28ed, braille_dots_234678: 0x28ee, braille_dots_1234678: 0x28ef, braille_dots_5678: 0x28f0, braille_dots_15678: 0x28f1, braille_dots_25678: 0x28f2, braille_dots_125678: 0x28f3, braille_dots_35678: 0x28f4, braille_dots_135678: 0x28f5, braille_dots_235678: 0x28f6, braille_dots_1235678: 0x28f7, braille_dots_45678: 0x28f8, braille_dots_145678: 0x28f9, braille_dots_245678: 0x28fa, braille_dots_1245678: 0x28fb, braille_dots_345678: 0x28fc, braille_dots_1345678: 0x28fd, braille_dots_2345678: 0x28fe, braille_dots_12345678: 0x28ff, Sinh_ng: 0x0d82, Sinh_h2: 0x0d83, Sinh_a: 0x0d85, Sinh_aa: 0x0d86, Sinh_ae: 0x0d87, Sinh_aee: 0x0d88, Sinh_i: 0x0d89, Sinh_ii: 0x0d8a, Sinh_u: 0x0d8b, Sinh_uu: 0x0d8c, Sinh_ri: 0x0d8d, Sinh_rii: 0x0d8e, Sinh_lu: 0x0d8f, Sinh_luu: 0x0d90, Sinh_e: 0x0d91, Sinh_ee: 0x0d92, Sinh_ai: 0x0d93, Sinh_o: 0x0d94, Sinh_oo: 0x0d95, Sinh_au: 0x0d96, Sinh_ka: 0x0d9a, Sinh_kha: 0x0d9b, Sinh_ga: 0x0d9c, Sinh_gha: 0x0d9d, Sinh_ng2: 0x0d9e, Sinh_nga: 0x0d9f, Sinh_ca: 0x0da0, Sinh_cha: 0x0da1, Sinh_ja: 0x0da2, Sinh_jha: 0x0da3, Sinh_nya: 0x0da4, Sinh_jnya: 0x0da5, Sinh_nja: 0x0da6, Sinh_tta: 0x0da7, Sinh_ttha: 0x0da8, Sinh_dda: 0x0da9, Sinh_ddha: 0x0daa, Sinh_nna: 0x0dab, Sinh_ndda: 0x0dac, Sinh_tha: 0x0dad, Sinh_thha: 0x0dae, Sinh_dha: 0x0daf, Sinh_dhha: 0x0db0, Sinh_na: 0x0db1, Sinh_ndha: 0x0db3, Sinh_pa: 0x0db4, Sinh_pha: 0x0db5, Sinh_ba: 0x0db6, Sinh_bha: 0x0db7, Sinh_ma: 0x0db8, Sinh_mba: 0x0db9, Sinh_ya: 0x0dba, Sinh_ra: 0x0dbb, Sinh_la: 0x0dbd, Sinh_va: 0x0dc0, Sinh_sha: 0x0dc1, Sinh_ssha: 0x0dc2, Sinh_sa: 0x0dc3, Sinh_ha: 0x0dc4, Sinh_lla: 0x0dc5, Sinh_fa: 0x0dc6, Sinh_al: 0x0dca, Sinh_aa2: 0x0dcf, Sinh_ae2: 0x0dd0, Sinh_aee2: 0x0dd1, Sinh_i2: 0x0dd2, Sinh_ii2: 0x0dd3, Sinh_u2: 0x0dd4, Sinh_uu2: 0x0dd6, Sinh_ru2: 0x0dd8, Sinh_e2: 0x0dd9, Sinh_ee2: 0x0dda, Sinh_ai2: 0x0ddb, Sinh_o2: 0x0ddc, Sinh_oo2: 0x0ddd, Sinh_au2: 0x0dde, Sinh_lu2: 0x0ddf, Sinh_ruu2: 0x0df2, Sinh_luu2: 0x0df3, Sinh_kunddaliya: 0x0df4 }; export const CHAR_TO_NAME = Object.keys(KEYSYM_TO_UNICODE).reduce( (result, key) => Object.assign({}, result, { [String.fromCharCode(KEYSYM_TO_UNICODE[key])]: key }), {} ); //some keysyms require specific layouts export const KEYSYM_TO_LAYOUT = { kana: "jp", Farsi: "ir", Arabic: "ar", Cyrillic: "ru", Ukrainian: "uk", Macedonia: "mk", Greek: "gr", hebrew: "he", Thai: "th", Armenian: "am", Georgian: "ge", braille: "brai" }; export const CODEC_DESCRIPTION = { mp4a: "mpeg4: aac", "aac+mpeg4": "mpeg4: aac", mp3: "mp3", "mp3+mpeg4": "mpeg4: mp3", wav: "wav", wave: "wave", flac: "flac", opus: "opus", vorbis: "vorbis", "opus+mka": "webm: opus", "opus+ogg": "ogg: opus", "vorbis+mka": "webm: vorbis", "vorbis+ogg": "ogg: vorbis", "speex+ogg": "ogg: speex", "flac+ogg": "ogg: flac" }; export const CODEC_STRING = { "aac+mpeg4": 'audio/mp4; codecs="mp4a.40.2"', //"aac+mpeg4": 'audio/mp4; codecs="aac51"', //"aac+mpeg4": 'audio/aac', mp3: "audio/mpeg", "mp3+mpeg4": 'audio/mp4; codecs="mp3"', //"mp3": "audio/mp3", ogg: "audio/ogg", //"wave": 'audio/wave', //"wav": 'audio/wav; codec="1"', wav: "audio/wav", flac: "audio/flac", "opus+mka": 'audio/webm; codecs="opus"', "vorbis+mka": 'audio/webm; codecs="vorbis"', "vorbis+ogg": 'audio/ogg; codecs="vorbis"', "speex+ogg": 'audio/ogg; codecs="speex"', "flac+ogg": 'audio/ogg; codecs="flac"', "opus+ogg": 'audio/ogg; codecs="opus"' }; export const PREFERRED_CODEC_ORDER = [ "opus+mka", "vorbis+mka", "opus+ogg", "vorbis+ogg", "opus", "vorbis", "speex+ogg", "flac+ogg", "aac+mpeg4", "mp3+mpeg4", "mp3", "flac", "wav", "wave" ]; export const H264_PROFILE_CODE = { //"baseline": "42E0", baseline: "42C0", main: "4D40", high: "6400", extended: "58A0" }; export const H264_LEVEL_CODE = { "3.0": "1E", "3.1": "1F", "4.1": "29", "5.1": "33" }; export const READY_STATE = { 0: "NOTHING", 1: "METADATA", 2: "CURRENT DATA", 3: "FUTURE DATA", 4: "ENOUGH DATA" }; export const NETWORK_STATE = { 0: "EMPTY", 1: "IDLE", 2: "LOADING", 3: "NO_SOURCE" }; export const ERROR_CODE = { 1: "ABORTED: fetching process aborted by user", 2: "NETWORK: error occurred when downloading", 3: "DECODE: error occurred when decoding", 4: "SRC_NOT_SUPPORTED" }; export const AURORA_CODECS = { wav: "lpcm", mp3: "mp3", flac: "flac", "aac+mpeg4": "mp4a" }; <file_sep>/src/protocol.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ import zlib from "zlibjs"; import { ord } from "./util.js"; import { bencode, bdecode } from "./bencode.js"; import { HEADER_SIZE } from "./constants.js"; const debug = (...args) => { if ( args[1].match(/^(ping|pointer|button|cursor|draw|damage|sound-data)/) === null ) { console.debug(...args); } }; /** * Inflates compressed data */ const inflate = (level, size, data) => { if (level !== 0) { if (level & 0x10) { console.error("lz4 compression not supported"); return null; //const { inflated, uncompressedSize } = lz4decode(data); // if lz4 errors out at the end of the buffer, ignore it: if (uncompressedSize <= 0 && size + uncompressedSize !== 0) { console.error( "failed to decompress lz4 data, error code", uncompressedSize ); return null; } return inflated; } else { return zlib.inflateSync(data); } } return data; }; /** * Decodes a packet */ const decode = (inflated, rawQueue) => { let packet = bdecode(inflated); for (let index in rawQueue) { packet[index] = rawQueue[index]; } if (packet[0] === "draw" && packet[6] !== "scroll") { const uint = imageData(packet[7]); if (uint !== null) { packet[7] = uint; } } return packet; }; /** * Gets a Uint8 draw data */ const imageData = data => { if (typeof data === "string") { const uint = new Uint8Array(data.length); for (let i = 0, j = data.length; i < j; ++i) { uint[i] = data.charCodeAt(i); } return uint; } return null; // Already uint }; /** * Parses an incoming packet */ const parsePacket = (header, queue) => { // check for crypto protocol flag const proto = { flags: header[1], padding: 0, crypto: header[1] & 0x2 }; if (proto.flags !== 0 && !proto.crypto) { console.error("we can't handle this protocol flag yet", proto); return false; } const level = header[2]; if (level & 0x20) { console.error("lzo compression is not supported"); return false; } const index = header[3]; if (index >= 20) { console.error("Invalid packet index", index); return false; } let packetSize = 0; for (let i = 0; i < 4; i++) { packetSize = packetSize * 0x100; packetSize += header[4 + i]; } /* TODO if (proto.crypto) { proto.padding = (this.cipher_in_block_size - packetSize % this.cipher_in_block_size); packetSize += proto.padding; } */ // verify that we have enough data for the full payload: let rsize = 0; for (let i = 0, j = queue.length; i < j; ++i) { rsize += queue[i].length; } if (rsize < packetSize) { //console.warn('We did not get full payload'); return false; } return { index, level, proto, packetSize }; }; /** * Serializes an outgoing packet */ const serializePacket = data => { const level = 0; // TODO: zlib, but does not work const proto_flags = 0; /* TODO: if(this.cipher_out) { proto_flags = 0x2; var padding_size = this.cipher_out_block_size - (payload_size % this.cipher_out_block_size); for (var i = padding_size - 1; i >= 0; i--) { bdata += String.fromCharCode(padding_size); }; this.cipher_out.update(forge.util.createBuffer(bdata)); bdata = this.cipher_out.output.getBytes(); } */ const size = data.length; const send = data.split("").map(ord); const header = [ord("P"), proto_flags, level, 0]; for (let i = 3; i >= 0; i--) { header.push((size >> (8 * i)) & 0xff); } return [...header, ...send]; }; /** * Creates a new receieve queue handler */ export const createReceiveQueue = callback => { let queue = []; let header = []; let rawQueue = []; const processHeader = () => { if (header.length < HEADER_SIZE && queue.length > 0) { // add from receive queue data to header until we get the 8 bytes we need: while (header.length < HEADER_SIZE && queue.length > 0) { const slice = queue[0]; const needed = HEADER_SIZE - header.length; const num = Math.min(needed, slice.length); for (let i = 0; i < num; i++) { header.push(slice[i]); } // replace the slice with what is left over: if (slice.length > needed) { queue[0] = slice.subarray(num); } else { // this slice has been fully consumed already: queue.shift(); } if (header[0] !== ord("P")) { console.error("Invalid packet header format", header, ord("P")); return false; } } } // The packet has still not been downloaded, we need to wait if (header.length < HEADER_SIZE) { //console.warn('Waiting for rest of packet...'); return false; } return true; }; const processData = (level, proto, packetSize) => { let packetData; // exact match: the payload is in a buffer already: if (queue[0].length === packetSize) { packetData = queue.shift(); } else { // aggregate all the buffers into "packet_data" until we get exactly "packet_size" bytes: packetData = new Uint8Array(packetSize); let rsize = 0; while (rsize < packetSize) { const slice = queue[0]; const needed = packetSize - rsize; // add part of this slice if (slice.length > needed) { packetData.set(slice.subarray(0, needed), rsize); rsize += needed; queue[0] = slice.subarray(needed); } else { // add this slice in full packetData.set(slice, rsize); rsize += slice.length; queue.shift(); } } } // TODO: Proto /* if (proto.crypto) { this.cipher_in.update(forge.util.createBuffer(uintToString(packet_data))); const decrypted = this.cipher_in.output.getBytes(); packet_data = []; for (i=0; i<decrypted.length; i++) packet_data.push(decrypted[i].charCodeAt(0)); packet_data = packet_data.slice(0, -1 * padding); } */ return inflate(level, packetSize, packetData); }; const process = () => { if (!processHeader()) { return false; } const result = parsePacket(header, queue); if (result === false) { return false; } header = []; const { index, level, proto, packetSize } = result; const inflated = processData(level, proto, packetSize); // save it for later? (partial raw packet) if (index > 0) { rawQueue[index] = inflated; } else { // decode raw packet string into objects: try { const packet = decode(inflated, rawQueue); debug("<<<", ...packet); callback(...packet); rawQueue = []; } catch (e) { console.error("error decoding packet", e); return false; } } return true; }; return { clear: () => { queue = []; }, push: data => { queue.push(data); process(); } }; }; /** * Creates a new send queue handler */ export const createSendQueue = () => { let queue = []; const process = socket => { while (queue.length !== 0) { const packet = queue.shift(); if (!packet || !socket) { continue; } debug(">>>", ...packet); const data = bencode(packet); const pkg = serializePacket(data); const out = new Uint8Array(pkg).buffer; socket.send(out); } }; return { clear: () => { queue = []; }, push: (data, socket) => { queue.push(data); process(socket); } }; }; <file_sep>/src/keyboard.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ import { IS_WIN32, CHARCODE_TO_NAME, NUMPAD_TO_NAME, KEY_TO_NAME, CHAR_TO_NAME, KEYSYM_TO_LAYOUT, DOM_KEY_LOCATION_RIGHT } from "./constants.js"; const modifierMap = { altKey: "alt", ctrlKey: "control", metaKey: "meta", shiftKey: "shift" }; const getEventModifiers = ev => Object.keys(modifierMap) .filter(key => ev[key]) .map(key => modifierMap[key]); const translateModifiers = modifiers => { // TODO return modifiers; }; const getModifiers = (ev, capsLock, numLock) => { const modifiers = getEventModifiers(event); if (capsLock) { modifiers.push("lock"); } if (numLock) { modifiers.push("numlock"); // FIXME } return translateModifiers(modifiers); }; /** * This function is only used for figuring out the caps_lock state! * onkeyup and onkeydown give us the raw keycode, * whereas here we get the keycode in lowercase/uppercase depending * on the caps_lock and shift state, which allows us to figure * out caps_lock state since we have shift state. */ const getCapsLockState = (ev, shift) => { const keycode = ev.which || ev.keyCode; /* PITA: this only works for keypress event... */ if (keycode >= 97 && keycode <= 122 && shift) { return true; } else if (keycode >= 65 && keycode <= 90 && !shift) { return true; } return false; }; /** * Creates the keyboard input handler */ export const createKeyboard = send => { const swapKeys = false; // TODO let capsLock = false; let numLock = false; let altGr = false; const getMods = ev => getModifiers(ev, capsLock, numLock); const process = (ev, surface) => { const topwindow = surface ? surface.wid : 0; const rawModifiers = getEventModifiers(ev); const modifiers = getMods(ev); const shift = modifiers.includes("shift"); if (ev.type === "keydown" || ev.type === "keyup") { const keycode = ev.which || event.keyCode; // this usually fires when we have received the event via "oninput" already if (keycode === 229) { return false; } const group = 0; const pressed = ev.type === "keydown"; // sync numlock if (keycode === 144 && pressed) { numLock = !numLock; } let str = event.key || String.fromCharCode(keycode); let keyname = ev.code || ""; if (keyname != str && str in NUMPAD_TO_NAME) { keyname = NUMPAD_TO_NAME[str]; numLock = "0123456789.".includes(keyname); } else if (keyname in KEY_TO_NAME) { // some special keys are better mapped by name: keyname = KEY_TO_NAME[keyname]; } else if (str in CHAR_TO_NAME) { // next try mapping the actual character keyname = CHAR_TO_NAME[str]; /* TODO if (keyname.includes('_')) { // ie: Thai_dochada const lang = keyname.split('_')[0]; keylang = KEYSYM_TO_LAYOUT[lang]; } */ } else if (keycode in CHARCODE_TO_NAME) { // fallback to keycode map: keyname = CHARCODE_TO_NAME[keycode]; } if (keyname.match("_L$") && ev.location === DOM_KEY_LOCATION_RIGHT) { keyname = keyname.replace("_L", "_R"); } // AltGr: keep track of pressed state if (str == "AltGraph" || (keyname === "Alt_R" && IS_WIN32)) { altGr = pressed; keyname = "ISO_Level3_Shift"; str = "AltGraph"; } if ((capsLock && shift) || (!capsLock && !shift)) { str = str.toLowerCase(); } const oldStr = str; if (swapKeys) { if (keyname === "Control_L") { keyname = "Meta_L"; str = "meta"; } else if (keyname === "Meta_L") { keyname = "Control_L"; str = "control"; } else if (keyname === "Control_R") { keyname = "Meta_R"; str = "meta"; } else if (keyname === "Meta_R") { keyname = "Control_R"; str = "control"; } } send( "key-action", topwindow, keyname, pressed, modifiers, keycode, str, keycode, group ); // macos will swallow the key release event if the meta modifier is pressed, // so simulate one immediately: if ( pressed && swapKeys && rawModifiers.includes("meta") && oldStr !== "meta" ) { send( "key-action", topwindow, keyname, false, modifiers, keycode, str, keycode, group ); } return true; } else if (ev.type === "keypress") { capsLock = getCapsLockState(ev, shift); return true; } return false; }; return { modifiers: getMods, process }; }; <file_sep>/src/renderer/rgb.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ import { lz4decode } from "../util.js"; import zlib from "zlibjs"; export const rgbImageRenderer = ({ x, y, w, h, data, options }) => ( { drawContext }, callback ) => { const img = drawContext.createImageData(w, h); if (options.zlib > 0) { data = zlib.inflateSync(data); } else if (options.lz4 > 0) { const { uncompressedSize, inflated } = lz4decode(data); data = inflated.slice(0, uncompressedSize); } if (data.length > img.data.length) { callback("Data size mismatch"); } else { img.data.set(data); drawContext.putImageData(img, x, y); callback(); } }; <file_sep>/src/renderer/icon.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ import { arraybufferBase64 } from "../util.js"; export const iconRenderer = ({ coding, data }) => { if (coding === "png") { const src = `data:image/${coding};base64,` + arraybufferBase64(data); return src; } return "about:blank"; // FIXME }; <file_sep>/README.md **DEPRECATED:** MOVED into src/smc-webapp/frame-editors/x11-editor/xpra in https://github.com/sagemathinc/cocalc This is based on https://github.com/andersevenrud/xpra-html5-client <file_sep>/src/mouse.js /** * Xpra HTML Client * * This is a refactored (modernized) version of * https://xpra.org/trac/browser/xpra/trunk/src/html5/ * * @author <NAME> <<EMAIL>> */ import { PIXEL_STEP, LINE_HEIGHT, PAGE_HEIGHT } from "./constants.js"; const wheelEventName = (() => { const element = document.createElement("div"); const names = ["wheel", "mousewheel", "DOMMouseScroll"]; return names.find(name => { const n = `on${name}`; element.setAttribute(n, "return;"); return typeof element[n] === "function"; }); })(); const normalizeWheel = ev => { let spinX = 0, spinY = 0, pixelX = 0, pixelY = 0; // Legacy if ("detail" in ev) { spinY = ev.detail; } if ("wheelDelta" in ev) { spinY = -ev.wheelDelta / 120; } if ("wheelDeltaY" in ev) { spinY = -ev.wheelDeltaY / 120; } if ("wheelDeltaX" in ev) { spinX = -ev.wheelDeltaX / 120; } // side scrolling on FF with DOMMouseScroll if ("axis" in ev && ev.axis === ev.HORIZONTAL_AXIS) { spinX = spinY; spinY = 0; } pixelX = spinX * PIXEL_STEP; pixelY = spinY * PIXEL_STEP; if ("deltaY" in ev) { pixelY = ev.deltaY; } if ("deltaX" in ev) { pixelX = ev.deltaX; } if ((pixelX || pixelY) && ev.deltaMode) { if (ev.deltaMode == 1) { // delta in LINE units pixelX *= LINE_HEIGHT; pixelY *= LINE_HEIGHT; } else { // delta in PAGE units pixelX *= PAGE_HEIGHT; pixelY *= PAGE_HEIGHT; } } // Fall-back if spin cannot be determined if (pixelX && !spinX) { spinX = pixelX < 1 ? -1 : 1; } if (pixelY && !spinY) { spinY = pixelY < 1 ? -1 : 1; } return { spinX, spinY, pixelX, pixelY, deltaMode: ev.deltaMode || 0 }; }; const getMouseButton = ev => { let button = ev.which ? Math.max(0, ev.which) : ev.button ? Math.max(0, ev.button) + 1 : 0; if (button === 4) { button = 8; } else if (button === 5) { button = 9; } return button; }; const calculateWheel = (() => { let wheel_delta_x = 0; let wheel_delta_y = 0; return (ev, callback, callbackPrecise) => { const wheel = normalizeWheel(ev); // clamp to prevent event floods: let px = Math.min(1200, wheel.pixelX); let py = Math.min(1200, wheel.pixelY); let apx = Math.abs(px); let apy = Math.abs(py); /* TODO if (this.server_precise_wheel) { if (apx>0) { let btn_x = (px>=0) ? 6 : 7; let xdist = Math.round(px*1000/120); this.send(["wheel-motion", wid, btn_x, -xdist, (x, y), modifiers, buttons]); } if (apy>0) { let btn_y = (py>=0) ? 5 : 4; let ydist = Math.round(py*1000/120); this.send(["wheel-motion", wid, btn_y, -ydist, (x, y), modifiers, buttons]); } return; } */ // generate a single event if we can, or add to accumulators: if (apx >= 40 && apx <= 160) { wheel_delta_x = px > 0 ? 120 : -120; } else { wheel_delta_x += px; } if (apy >= 40 && apy <= 160) { wheel_delta_y = py > 0 ? 120 : -120; } else { wheel_delta_y += py; } // send synthetic click+release as many times as needed: let wx = Math.abs(wheel_delta_x); let wy = Math.abs(wheel_delta_y); const btn_x = wheel_delta_x >= 0 ? 6 : 7; const btn_y = wheel_delta_y >= 0 ? 5 : 4; while (wx >= 120) { wx -= 120; callback(btn_x); } while (wy >= 120) { wy -= 120; callback(btn_y); } // store left overs: wheel_delta_x = wheel_delta_x >= 0 ? wx : -wx; wheel_delta_y = wheel_delta_y >= 0 ? wy : -wy; }; })(); const getMouse = (ev, surface) => { let relX = 0; let relY = 0; if (surface) { const { top, left } = surface.canvas.getBoundingClientRect(); relX = left - surface.x; relY = top - surface.y; } let x = parseInt(ev.clientX - relX, 10); let y = parseInt(ev.clientY - relY, 10); const buttons = []; const button = getMouseButton(ev); x = Math.round(x * window.devicePixelRatio); y = Math.round(y * window.devicePixelRatio); return { x, y, button, buttons }; }; /** * Crates the mouse input handler */ export const createMouse = (send, keyboard) => { const scroll = (topwindow, x, y, modifiers, buttons) => pos => { send("button-action", topwindow, pos, true, [x, y], modifiers, buttons); send("button-action", topwindow, pos, false, [x, y], modifiers, buttons); }; const preciseScroll = () => { // TODO }; const process = (ev, surface) => { const topwindow = surface ? surface.wid : 0; const modifiers = keyboard.modifiers(ev); if (ev.type === "mousemove") { const { x, y, buttons } = getMouse(ev, surface); send("pointer-position", topwindow, [x, y], modifiers, buttons); } else if (ev.type === "mousedown" || ev.type === "mouseup") { const pressed = ev.type === "mousedown"; const { x, y, button, buttons } = getMouse(ev, surface); send( "button-action", topwindow, button, pressed, [x, y], modifiers, buttons ); } else if (ev.type === wheelEventName) { const { x, y, buttons } = getMouse(ev, surface); const s = scroll(topwindow, x, y, modifiers, buttons); const ps = preciseScroll(); calculateWheel(ev, s, s, ps); } }; return { process }; }; <file_sep>/src/bencode.js /* Copyright (c) 2009 <NAME> * Copyright (c) 2013 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ /* * This is a modified version, suitable for xpra wire encoding: * - the input can be a string or byte array * - we do not sort lists or dictionaries (the existing order is preserved) * - error out instead of writing "null" and generating a broken stream * - handle booleans as ints (0, 1) */ // bencode an object export function bencode(obj) { if (obj === null || obj === undefined) { throw "invalid: cannot encode null"; } switch (btypeof(obj)) { case "string": return bstring(obj); case "number": return bint(obj); case "list": return blist(obj); case "dictionary": return bdict(obj); case "boolean": return bint(obj ? 1 : 0); default: throw "invalid object type in source: " + btypeof(obj); } } function uintToString(uintArray) { // apply in chunks of 10400 to avoid call stack overflow // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply let s = ""; let skip = 10400; let slice = uintArray.slice; for (let i = 0, len = uintArray.length; i < len; i += skip) { if (!slice) { s += String.fromCharCode.apply( null, uintArray.subarray(i, Math.min(i + skip, len)) ); } else { s += String.fromCharCode.apply( null, uintArray.slice(i, Math.min(i + skip, len)) ); } } return s; } // decode a bencoded string or bytearray into a javascript object export function bdecode(buf) { if (!buf.substr) { // if we have a byte array as input, its more efficient to convert the whole // thing into a string at once buf = uintToString(buf); } let dec = bparse(buf); return dec[0]; } // parse a bencoded string; bdecode is really just a wrapper for this one. // all bparse* functions return an array in the form // [parsed object, remaining buffer to parse] function bparse(str) { switch (str.charAt(0)) { case "d": return bparseDict(str.substr(1)); case "l": return bparseList(str.substr(1)); case "i": return bparseInt(str.substr(1)); default: return bparseString(str); } } // parse a bencoded string function bparseString(str) { let str2 = str.split(":", 1)[0]; if (isNum(str2)) { let len = parseInt(str2, 10); return [ str.substr(str2.length + 1, len), str.substr(str2.length + 1 + len) ]; } return null; } // parse a bencoded integer function bparseInt(str) { let str2 = str.split("e", 1)[0]; if (!isNum(str2)) { return null; } return [parseInt(str2, 10), str.substr(str2.length + 1)]; } // parse a bencoded list function bparseList(str) { let p, list = []; while (str.charAt(0) !== "e" && str.length > 0) { p = bparse(str); if (null === p) { return null; } list[list.length] = p[0]; str = p[1]; } if (str.length <= 0) { throw "unexpected end of buffer reading list"; } return [list, str.substr(1)]; } // parse a bencoded dictionary function bparseDict(str) { let key, val, dict = {}; while (str.charAt(0) !== "e" && str.length > 0) { key = bparseString(str); if (null === key) { return null; } val = bparse(key[1]); if (null === val) { return null; } dict[key[0]] = val[0]; str = val[1]; } if (str.length <= 0) { return null; } return [dict, str.substr(1)]; } // is the given string numeric? function isNum(str) { return !isNaN(str.toString()); } // returns the bencoding type of the given object function btypeof(obj) { let type = typeof obj; if (type === "object") { if (typeof obj.length === "undefined") { return "dictionary"; } return "list"; } return type; } // bencode a string function bstring(str) { return str.length + ":" + str; } // bencode an integer function bint(num) { return "i" + num + "e"; } // bencode a list function blist(list) { let str; str = "l"; for (let key in list) { str += bencode(list[key]); } return str + "e"; } // bencode a dictionary function bdict(dict) { let str; str = "d"; for (let key in dict) { str += bencode(key) + bencode(dict[key]); } return str + "e"; }
0298404481e25dd24ece227dd7f19a07ac92da73
[ "JavaScript", "Markdown" ]
13
JavaScript
isabella232/cocalc-xpra
4065feb451ff33e12dd0715cbf7525812eec6d82
b85c79a7e4a22530e1a30f1f87edd81682d21b3b
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class DummyScript : MonoBehaviour { public int x; public int y; public KOMA_TYPE koma_type; public System_manager system_manager; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void setKoma() { board board = GameObject.Find("Board").GetComponent<board>(); try { board.SetKoma(x, y,koma_type); if (koma_type == KOMA_TYPE.Black) { system_manager.send(x, y, 1); } else { system_manager.send(x, y, 0); } system_manager.fsend(); } catch { } system_manager.turn_change(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using MonobitEngine; public enum PLAY_MODE { single, multi } public enum TURN { play_first, draw_first } public class System_manager : MonobitEngine.MonoBehaviour { public static TURN receiveTurn; public static PLAY_MODE play_mode; //最初に選んだターン private TURN turn; //現在のターン private TURN now_turn = TURN.play_first; public board b; public result_text r; public turn_text t; /** ルーム名. */ private string roomName = ""; private int sx, sy; private int n; private bool o = false; private bool pass = false; private bool end = false; public bool endflag = false; [SerializeField] GameObject ui_result; [SerializeField] GameObject ui_continue_button; [SerializeField] GameObject ui_turn; [SerializeField] GameObject ui_start; [SerializeField] GameObject ui_wait; // Start is called before the first frame update void Start() { reset_game(); } //オセロのシステム起動 public void Game_start(PLAY_MODE mode) { ui_turn.SetActive(true); ui_wait.SetActive(false); if (mode == PLAY_MODE.single) { //シングルプレイの処理 single_play_start(); } else if (mode == PLAY_MODE.multi) { //マルチプレイの処理 multi_play_start(); } else { Debug.LogError("mode選びミスってませんか?"); } } public void set_turn(TURN turn) { this.turn = turn; System_manager.receiveTurn = turn; } public TURN get_turn() { return this.turn; } public void set_now_turn(TURN now_turn) { this.now_turn = now_turn; } public TURN get_now_turn() { return this.now_turn; } //シングルプレイの初回の処理 public void single_play_start() { b.board_start(); //ループ終了処理(両者打つところがなくなる or全部の面を埋まったら) please_input(); } //マルチプレイの初回の処理 public void multi_play_start() { b.board_start(); //ループ終了処理(両者打つところがなくなる or全部の面を埋まったら) please_input_multi(); } //ターンを切り替えるときの処理 public void turn_change() { if (now_turn == TURN.draw_first) now_turn = TURN.play_first; else if (now_turn == TURN.play_first) now_turn = TURN.draw_first; else Debug.LogError("now_turn:値は不正です"); Debug.Log("<COLOR=YELLOW>ターン変わったよ" + this.turn + "</COLOR>"); if (play_mode == PLAY_MODE.single) please_input(); else if (play_mode == PLAY_MODE.multi) please_input_multi(); } public void please_input() { ui_turn.SetActive(true); dummy_array_reset(); if (now_turn == turn) { Invoke("call_single_player", 1.0f); } else { Invoke("call_cpu", 1.0f); } } public void please_input_multi() { ui_turn.SetActive(true); dummy_array_reset(); if (now_turn == receiveTurn) { Invoke("call_first", 1.0f); } else { Invoke("call_second", 1.0f); } } public void call_first() { Debug.Log("<COLOR=YELLOW>プレイヤー入力待ち</COLOR>"); t.turn_text_change(System_manager.receiveTurn, this.now_turn); b.can_set(now_turn); if (pass_check()) { if (endflag == true) { ui_turn.SetActive(false); r.change_result_text_multi(); //終了 ui_result.SetActive(true); send_end(); //Debug.Log("終了処理できてるよ"); } else { send_endflag(true); turn_change(); } } else { endflag = false; } } public void call_second() { Debug.Log("<COLOR=YELLOW>後攻入力待ち</COLOR>"); t.turn_text_change(System_manager.receiveTurn, this.now_turn); } public void call_single_player() { Debug.Log("<COLOR=YELLOW>プレイヤー入力待ち</COLOR>"); t.turn_text_change(this.turn, this.now_turn); b.can_set(now_turn); if (pass_check()) { if (endflag == true) { ui_turn.SetActive(false); r.result_text_change("player1"); //終了 ui_result.SetActive(true); //Debug.Log("終了処理できてるよ"); } else { endflag = true; turn_change(); } } else { endflag = false; } } public void call_cpu() { //cpuの配置 Debug.Log("<COLOR=YELLOW>CPU入力待ち</COLOR>"); t.turn_text_change(this.turn, this.now_turn); b.can_set(now_turn); if (!pass_check()) { endflag = false; cpu_set_check(); } else { if (endflag == true) { ui_turn.SetActive(false); r.result_text_change("cpu"); //終了処理 ui_result.SetActive(true); //Debug.Log("終了処理できてるよ"); } else { endflag = true; turn_change(); } } } public void dummy_array_reset() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { b.dummy_array[i, j].SetActive(false); } } } //CPUが置く処理 public void cpu_set_check() { Random.InitState(System.DateTime.Now.Millisecond); int cnt = 0; List<List<int>> list = new List<List<int>>(); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (b.dummy_array[i, j].activeSelf == true) { list.Add(new List<int>(new int[] { i, j })); cnt += 1; } } } int random = Random.Range(0, cnt); b.dummy_array[list[random][0], list[random][1]].GetComponent<DummyScript>().setKoma(); } //どこかに置ける場合はfalseを返す public bool pass_check() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { //Debug.Log(dummy_array[i, j].activeSelf); //置けるか置けないかを判断する if (b.dummy_array[i, j].activeSelf == true) { return false; } } } return true; } public void fsend() { this.o = true; } public void send(int x, int y, int n) { this.sx = x; this.sy = y; this.n = n; // 座標を送信する monobitView.RPC("RecvCoordinate", MonobitTargets.Others, //座標 this.sx, this.sy, this.n ); Debug.Log("x =" + x + " y =" + y); } [MunRPC] void RecvCoordinate(int sender_x, int sender_y, int n) { KOMA_TYPE sender_koma_type; if (n == 1) { sender_koma_type = KOMA_TYPE.Black; } else { sender_koma_type = KOMA_TYPE.White; } b.SetKoma(sender_x, sender_y, sender_koma_type); turn_change(); } public void send_turn(int turn_num) { Debug.Log("<COLOR=RED>送信ターン番号" + turn_num + "</COLOR>"); //this.now_turn = now_turn; //this.turn = turn; // ターンを送信する monobitView.RPC("Other_GameStart_Multi", MonobitTargets.Others, turn_num ); } [MunRPC] void Other_GameStart_Multi(int turn) { if (turn == 1) { System_manager.receiveTurn = TURN.play_first; } else if (turn == 2) { System_manager.receiveTurn = TURN.draw_first; } Debug.Log("<COLOR=RED>"+ receiveTurn +"</COLOR>"); Debug.Log("<COLOR=RED>"+ play_mode + "</COLOR>"); Game_start(play_mode); } public void send_endflag(bool endflag) { monobitView.RPC("Other_Endflag_Multi", MonobitTargets.Others, endflag ); } [MunRPC] public void Other_Endflag_Multi(bool endflag) { this.endflag = endflag; turn_change(); } public void send_end() { monobitView.RPC("Other_End_Multi", MonobitTargets.Others ); } [MunRPC] public void Other_End_Multi() { ui_turn.SetActive(false); r.change_result_text_multi(); //終了 ui_result.SetActive(true); } [MunRPC] public void reset_game() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (b.komaArray[i, j] != null) Destroy(b.komaArray[i, j].gameObject); } } now_turn = TURN.play_first; if (play_mode == PLAY_MODE.multi) { if (MonobitNetwork.isHost) ui_start.SetActive(true); else { ui_wait.SetActive(true); Destroy(ui_continue_button); } } else { ui_start.SetActive(true); } ui_result.SetActive(false); } public void onClickContinue() { reset_game(); if (play_mode == PLAY_MODE.multi) { monobitView.RPC("reset_game", MonobitTargets.Others ); } } // Update is called once per frame void Update() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class result_text : MonoBehaviour { public Text targetText; public board b; // Start is called before the first frame update void Start() { } public void result_text_change(string player_name) { int black_kazu = b.get_koma_kazu("Black"); int white_kazu = b.get_koma_kazu("White"); this.targetText = this.GetComponent<Text>(); if (black_kazu > white_kazu) { this.targetText.text = player_name + "(黒)の勝ちです\n\n先手(黒):" + black_kazu + "\n" + "後手(白):" + white_kazu; } else if (black_kazu < white_kazu) { this.targetText.text = player_name + "(白)の勝ちです\n\n先手(黒):" + black_kazu + "\n" + "後手(白):" + white_kazu; } else if (black_kazu == white_kazu) { this.targetText.text = "引き分けです\n\n先手(黒):" + black_kazu + "\n" + "後手(白):" + white_kazu; } else { Debug.Log("change_textがおかしくない"); } } public void change_result_text_multi() { int black_kazu = b.get_koma_kazu("Black"); int white_kazu = b.get_koma_kazu("White"); this.targetText = this.GetComponent<Text>(); if (System_manager.receiveTurn == TURN.play_first && black_kazu > white_kazu) { this.targetText.text = "あなた(黒)の勝ちです\n\n先手(黒):" + black_kazu + "\n" + "後手(白):" + white_kazu; } else if (System_manager.receiveTurn == TURN.play_first && black_kazu < white_kazu) { this.targetText.text = "あいて(白)の勝ちです\n\n先手(黒):" + black_kazu + "\n" + "後手(白):" + white_kazu; } else if (System_manager.receiveTurn == TURN.draw_first && black_kazu > white_kazu) { this.targetText.text = "あいて(黒)の勝ちです\n\n先手(黒):" + black_kazu + "\n" + "後手(白):" + white_kazu; } else if (System_manager.receiveTurn == TURN.draw_first && black_kazu < white_kazu) { this.targetText.text = "あなた(白)の勝ちです\n\n先手(黒):" + black_kazu + "\n" + "後手(白):" + white_kazu; } else if (black_kazu == white_kazu) { this.targetText.text = "引き分けです\n\n先手(黒):" + black_kazu + "\n" + "後手(白):" + white_kazu; } else { Debug.Log("change_textがおかしくない"); } } // Update is called once per frame void Update() { } } <file_sep>using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; public class turnSelect : MonoBehaviour { public ToggleGroup toggleGroup; public System_manager system_manager; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void OnClick() { //Get the label in activated toggles string selectedLabel = toggleGroup.ActiveToggles() .First().name; if (selectedLabel == "toggle_first") { system_manager.set_turn(TURN.play_first); system_manager.set_now_turn(TURN.play_first); Debug.Log("先手を選択しました。"); system_manager.send_turn(2); } else if (selectedLabel == "toggle_second") { system_manager.set_turn(TURN.draw_first); system_manager.set_now_turn(TURN.play_first); Debug.Log("後手を選択しました。"); system_manager.send_turn(1); } //シングルモード if (System_manager.play_mode == PLAY_MODE.single) system_manager.Game_start(PLAY_MODE.single); else if (System_manager.play_mode == PLAY_MODE.multi) system_manager.Game_start(PLAY_MODE.multi); this.transform.root.gameObject.SetActive(false); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public enum KOMA_TYPE { Black, White, None } public class komaScript : MonoBehaviour { public int x; public int y; public KOMA_TYPE type; public AnimController anim; // Start is called before the first frame update void Start() { Texture2D m_texture; m_texture = new Texture2D(128, 128, TextureFormat.ARGB32, false); float space = m_texture.height / 2; for (int y = 0; y < m_texture.height; y++) { for (int x = 0; x < m_texture.width; x++) { if (y > space) m_texture.SetPixel(x, y, Color.black); else m_texture.SetPixel(x, y, Color.white); } } m_texture.Apply(); transform.GetChild(0).GetComponent<Renderer>().material.mainTexture = m_texture; } public void rotation(bool forced) { anim.koma_rotation(forced); } public void setTyoe(KOMA_TYPE koma_type) { anim.settype(koma_type); } // Update is called once per frame void Update() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class board : MonoBehaviour { public GameObject[,] komaArray = new GameObject[8, 8]; public GameObject[,] dummy_array = new GameObject[8, 8]; private float thisX; private float thisZ; private float space_obj; public System_manager system_manager; public void board_start() { setStartPosition(); } // Start is called before the first frame update void Start() { //ボードのテクスチャを設定 Texture2D m_texture; m_texture = new Texture2D(128, 128, TextureFormat.ARGB32, false); float space_texture = m_texture.width / 8; for (int y = 0; y < m_texture.height; y++) { for (int x = 0; x < m_texture.width; x++) { if (x % space_texture == 0 || y % space_texture == 0) m_texture.SetPixel(x, y, Color.black); else m_texture.SetPixel(x, y, Color.green); } } m_texture.Apply(); GetComponent<Renderer>().material.mainTexture = m_texture; } void setStartPosition() { float width = this.transform.localScale.x; float height = this.transform.localScale.z; thisX = this.transform.localPosition.x - (width / 2);//boardの左上X thisZ = this.transform.localPosition.z - (height / 2);//boardの左上のZ space_obj = width / 8; set_thisX(thisX); set_thisZ(thisZ); set_space_obj(space_obj); for (int i = 3; i <= 4; i++) { for (int j = 3; j <= 4; j++) { GameObject obj = (GameObject)Resources.Load(@"koma_pare"); float objWidth = obj.transform.localScale.x; float objHeight = obj.transform.localScale.z; float vecX = thisX + space_obj * i + (objWidth / 2); float vecZ = thisZ + space_obj * j + (objHeight / 2); komaArray[i, j] = Instantiate(obj, new Vector3(vecX, obj.transform.localPosition.y, vecZ), Quaternion.identity); if ((i == 3 && j == 4) || (i == 4 && j == 3)) { //コマを白にする Debug.Log("白のコマを配置"); komaArray[i, j].GetComponent<komaScript>().type = KOMA_TYPE.White; komaArray[i, j].GetComponent<komaScript>().x = i; komaArray[i, j].GetComponent<komaScript>().y = j; komaArray[i, j].GetComponent<komaScript>().setTyoe(get_koma_type(i, j)); } else { //コマを黒にする Debug.Log("黒のコマを配置"); komaArray[i, j].GetComponent<komaScript>().type = KOMA_TYPE.Black; komaArray[i, j].GetComponent<komaScript>().x = i; komaArray[i, j].GetComponent<komaScript>().y = j; } } } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { dummy_array[i, j] = setDummy(i, j, KOMA_TYPE.None); } } } public GameObject setDummy(int x, int y, KOMA_TYPE type) { float width = this.transform.localScale.x; float height = this.transform.localScale.z; float thisX = this.transform.localPosition.x - (width / 2);//boardの左上X float thisZ = this.transform.localPosition.z - (height / 2);//boardの左上のZ float space_obj = width / 8; GameObject dummy = (GameObject)Resources.Load(@"dummy"); float dummyWidth = dummy.transform.localScale.x; float dummyHeight = dummy.transform.localScale.z; float vecZ = thisZ + space_obj * y + (dummyHeight / 2); float vecX = thisX + space_obj * x + (dummyWidth / 2); dummy.GetComponent<DummyScript>().x = x; dummy.GetComponent<DummyScript>().y = y; dummy.GetComponent<DummyScript>().koma_type = type; dummy.GetComponent<DummyScript>().system_manager = system_manager; dummy.SetActive(false); Debug.Log("<COLOR=blue>ダミーを生成</COLOR>"); return Instantiate(dummy, new Vector3(vecX, dummy.transform.localPosition.y, vecZ), Quaternion.identity); } public void set_thisX(float thisX) { this.thisX = thisX; } public float get_thisX() { return this.thisX; } public void set_thisZ(float thisZ) { this.thisZ = thisZ; } public float get_thisZ() { return this.thisZ; } public void set_space_obj(float space_obj) { this.space_obj = space_obj; } public float get_space_obj() { return this.space_obj; } // Update is called once per frame void Update() { } public void can_set(TURN now_turn) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { dummy_array[i, j].SetActive(false); } } //相手のターンを取得する KOMA_TYPE now_type = KOMA_TYPE.None; KOMA_TYPE opp_type = KOMA_TYPE.None; if (now_turn == TURN.play_first) { now_type = KOMA_TYPE.Black; opp_type = KOMA_TYPE.White; } else if (now_turn == TURN.draw_first) { now_type = KOMA_TYPE.White; opp_type = KOMA_TYPE.Black; } else { Debug.LogError("TURNの値が不正です"); } Debug.Log("<COLOR=RED>" + now_type + "</COLOR><COLOR=YELLOW>の打てる場所探索</COLOR>"); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (get_koma_type(i, j) == KOMA_TYPE.None) { for (int dir_x = -1; dir_x <= 1; dir_x++) { for (int dir_y = -1; dir_y <= 1; dir_y++) { //探索先が探索元のマスの場合スルー if (i + dir_x == 0 && j + dir_y == 0) continue; //周囲8マスに相手のマスがあったら if (get_koma_type((i + dir_x), (j + dir_y)) == opp_type) { //Debug.Log("<COLOR=YELLOW>y:" + i + " x:" + j + "から" + dir_y + "," + dir_x + "方向へ探索</COLOR>"); //延長線上探索 int cnt = 2; while (true) { //範囲外:ループを抜ける if (i + (dir_x * cnt) < 0 || i + (dir_x * cnt) > 7 || j + (dir_y * cnt) < 0 || j + (dir_y * cnt) > 7) { break; } //探索先にコマが置かれていないorダミーが置かれている:ループを抜ける if (get_koma_type(i + (dir_x * cnt), j + (dir_y * cnt)) == KOMA_TYPE.None) { break; } //探索先に自分のマス:ダミー表示,ループを抜ける if (get_koma_type(i + (dir_x * cnt), j + (dir_y * cnt)) == now_type) { Debug.Log("<COLOR=blue>ダミー[" + i + "," + j + "]:true</COLOR>"); dummy_array[i, j].SetActive(true); dummy_array[i, j].GetComponent<DummyScript>().koma_type = turnToKomaType(now_turn); break; } if (cnt > 8) { Debug.LogError("whileが規定回数以上回りました"); return; } cnt++; } } } } } } } } KOMA_TYPE turnToKomaType(TURN turn) { KOMA_TYPE type; if (turn == TURN.play_first) { type = KOMA_TYPE.Black; } else { type = KOMA_TYPE.White; } return type; } public void SetKoma(int x, int y, KOMA_TYPE type) { float width = this.transform.localScale.x; float height = this.transform.localScale.z; float thisX = this.transform.localPosition.x - (width / 2);//boardの左上X float thisZ = this.transform.localPosition.z - (height / 2);//boardの左上のZ float space_obj = width / 8; GameObject obj = (GameObject)Resources.Load(@"koma_pare"); float objWidth = obj.transform.localScale.x; float objHeight = obj.transform.localScale.z; float vecX = thisX + space_obj * x + (objWidth / 2); float vecZ = thisZ + space_obj * y + (objHeight / 2); komaArray[x, y] = Instantiate(obj, new Vector3(vecX, obj.transform.localPosition.y, vecZ), Quaternion.identity); komaArray[x, y].GetComponent<komaScript>().x = x; komaArray[x, y].GetComponent<komaScript>().y = y; komaArray[x, y].GetComponent<komaScript>().type = type; komaArray[x, y].GetComponent<komaScript>().setTyoe(get_koma_type(x,y)); revers(x, y); } public void revers(int x, int y) { //置いた色 KOMA_TYPE set_type = get_koma_type(x, y); //相手の色 KOMA_TYPE opp_type = KOMA_TYPE.None; if (set_type == KOMA_TYPE.Black) opp_type = KOMA_TYPE.White; else opp_type = KOMA_TYPE.Black; Debug.Log("==========================================================================\n"+ "==========================================================================\n"+ "<color=blue>置いた場所 x:" + x + " y:" + y + "</ color >\n"+ "<color=blue>置いた色:" + set_type + "</color>\n"+ "<color=blue>相手の色" + opp_type + "</color>"); //ひっくり返す処理 for (int dir_x = -1; dir_x <= 1; dir_x++) { for (int dir_y = -1; dir_y <= 1; dir_y++) { //周囲の座標を取得 if (get_koma_type(x + dir_x, y + dir_y) == opp_type) { Debug.Log("<COLOR=GREEN>" + dir_x + "," + dir_y + "方向に" + opp_type + "を確認</COLOR>"); int cnt = 2; while (true) { //範囲外:ループを抜ける if (y + (dir_y * cnt) < 0 || y + (dir_y * cnt) > 7 || x + (dir_x * cnt) < 0 || x + (dir_x * cnt) > 7) { break; } //探索先にコマが置かれていないorダミーが置かれている:ループを抜ける if (get_koma_type(x + (dir_x * cnt), y + (dir_y * cnt)) == KOMA_TYPE.None) { break; } //探索先に自分のマス:返しながら戻る if (get_koma_type(x + (dir_x * cnt), y + (dir_y * cnt)) == set_type) { Debug.Log("<COLOR=GREEN>" + (x + (dir_x * cnt)) + "," + (y + (dir_y * cnt)) + "に" + set_type + "を確認</COLOR>"); cnt--; //打てる while (cnt > 0) { Debug.Log("<COLOR=GREEN>"+(x + (dir_x * cnt)) + ", " + (y + (dir_y * cnt))+"を反転</COLOR>"); komaArray[x + (dir_x * cnt), y + (dir_y * cnt)].GetComponent<komaScript>().rotation(true); cnt--; } break; } if (cnt > 8) { Debug.LogError("whileが規定回数以上回りました"); return; } cnt++; } } } } } public KOMA_TYPE get_koma_type(int x, int y) { if (x < 0 || y < 0 || x >= 8 || y >= 8) { return KOMA_TYPE.None; } else if (komaArray[x, y] == null) { return KOMA_TYPE.None; } else { return komaArray[x, y].GetComponent<komaScript>().type; } } public int get_koma_kazu(string color) { int blackcnt = 0; int whitecnt = 0; for(int i = 0;i < 8; i++) { for(int j = 0;j < 8; j++) { if (komaArray[i,j] == null) { } else if(komaArray[i,j].GetComponent<komaScript>().type == KOMA_TYPE.Black) { blackcnt += 1; } else if(komaArray[i,j].GetComponent<komaScript>().type == KOMA_TYPE.White) { whitecnt += 1; } else { Debug.LogError("get_koma_kazu関数で数の計算がおかしいよ"); } } } if (color == "Black") { return blackcnt; } else if (color == "White") { return whitecnt; } else{ Debug.LogError("get_koma_kazuでおかしくなってるよ"); return -1; } } } <file_sep># Othello オンライン対戦型オセロ(オフラインでもプレイ可能) Unityでの開発練習のために作成 # Author 作成情報を列挙する * 作成者 tama2135、鈴木健介 * 所属  * E-mail  # URL https://play.google.com/store/apps/details?id=com.funnysoft.test <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class turn_text : MonoBehaviour { public Text targetText; // Start is called before the first frame update void Start() { } public void turn_text_change(TURN turn, TURN nowturn) { this.targetText = this.GetComponent<Text>(); if (turn == nowturn) { this.targetText.text = "あなたのターン"; } else { this.targetText.text = "相手のターン"; } } // Update is called once per frame void Update() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using MonobitEngine; using UnityEngine.SceneManagement; public class MonoScript : MonobitEngine.MonoBehaviour { public static TURN turn; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public static void CreateRoom(string roomName) { MonobitNetwork.playerName = "host"; MonobitNetwork.CreateRoom(roomName); Debug.Log("ルーム【" + roomName + "】を作成"); } public static string[] getRoomNames() { List<string> rooms = new List<string>(); foreach (RoomData room in MonobitNetwork.GetRoomData()) { //1人以下のみ if (room.playerCount <= 1) { rooms.Add(room.name); Debug.Log("ルーム【" + room.name + "】を取得"); } } return rooms.ToArray(); } public static void LeaveRoom() { MonobitNetwork.LeaveRoom(); Debug.Log("退室しました"); } public static void JoinRoom(string roomName) { MonobitNetwork.playerName = "guest"; if (MonobitNetwork.JoinRoom(roomName)) { Debug.Log("ルーム【" + roomName + "】に入室しました"); } else { Debug.LogError("ルーム【" + roomName + "】に入室できませんでした"); } } public static void ConnectServer() { MonobitNetwork.autoJoinLobby = true; MonobitNetwork.ConnectServer("othello"); Debug.Log("サーバーにアクセスしました"); } public static bool isConnect() { if (MonobitNetwork.isConnect) { if (MonobitNetwork.inRoom) return true; else Debug.LogError("ルームに入室していません"); } else Debug.LogError("サーバーに接続していません"); return false; } public void guestReady() { //相手のゲームを開始する monobitView.RPC("hostGameStart", MonobitTargets.Others); } public void gameStart() { System_manager.play_mode = PLAY_MODE.multi; System_manager.receiveTurn = MonoScript.turn; SceneManager.LoadScene("SampleScene"); } [MunRPC] public void hostGameStart() { Debug.Log("hostGameStartが呼び出されました"); if (MonoScript.turn == TURN.draw_first) monobitView.RPC("guestGameStart", MonobitTargets.Others); else if (MonoScript.turn == TURN.play_first) monobitView.RPC("guestGameStart", MonobitTargets.Others); gameStart(); } [MunRPC] public void guestGameStart() { Debug.Log("guestGameStartが呼ばれました"); gameStart(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using MonobitEngine; public class Continue : MonobitEngine.MonoBehaviour { [SerializeField] GameObject ui_start; [SerializeField] GameObject ui_result; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } } <file_sep>using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class ButtonController : MonoBehaviour { [SerializeField] GameObject ui_mode_select; [SerializeField] GameObject ui_room; [SerializeField] GameObject ui_room_name; [SerializeField] GameObject ui_room_list; [SerializeField] GameObject ui_turn_select; [SerializeField] GameObject ui_wait; [SerializeField] MonoScript monobit; [SerializeField] ToggleGroup toggleGroup; //アクセスの試行回数を記録 int acccess_count = 0; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void onClickOffButton() { System_manager.play_mode = PLAY_MODE.single; SceneManager.LoadScene("SampleScene"); } public void onClickEndButton() { UnityEngine.Application.Quit(); } public void onClickOnButton() { ui_mode_select.SetActive(false); ui_room.SetActive(true); MonoScript.ConnectServer(); Invoke("roomUpdate", 1.0F); } public void onClickRoomCreateButton() { //inputFieldからテキストを取得 string roomName = ui_room_name.GetComponent<Text>().text; MonoScript.CreateRoom(roomName); ui_room.SetActive(false); ui_wait.SetActive(true); } public void onClickRoomUpdateButton() { roomUpdate(); } private void roomUpdate() { //リスト内のボタンを削除 foreach (Transform n in ui_room_list.transform) { GameObject.Destroy(n.gameObject); } //リソースからボタンを読み込む GameObject roomPrefab = (GameObject)Resources.Load("room_select"); int cnt = 1; foreach (string roomName in MonoScript.getRoomNames()) { //リソースからルームボタンを生成 GameObject room = Instantiate(roomPrefab) as GameObject; //テキストをルーム名に変更 room.transform.GetChild(0).GetComponent<Text>().text = roomName; //表示位置を変更 RectTransform rect = room.GetComponent<RectTransform>(); rect.localPosition = new Vector3(rect.localPosition.x, -50 * cnt); //リストの子に追加 room.transform.SetParent(ui_room_list.transform, false); //クリックイベント追加 string roomName_e = roomName; room.GetComponent<Button>().onClick.AddListener(() => onClickRoom(roomName_e)); cnt++; } } public void onClickRoom(string roomName) { MonoScript.JoinRoom(roomName); Invoke("checkJoin", 1.0F); } private void checkJoin() { if (MonoScript.isConnect()) { ui_room.SetActive(false); monobit.guestReady(); } else { //5回まで再試行する if (acccess_count <= 5) { Invoke("checkJoin", 1.0F); } else { acccess_count = 0; ui_room.SetActive(true); } } } public void onClickBackToModeSelect() { ui_room.SetActive(false); ui_mode_select.SetActive(true); } public void onClickWaitCancel() { MonoScript.LeaveRoom(); ui_wait.SetActive(false); ui_room.SetActive(true); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnimController : MonoBehaviour { float defaultY; // Start is called before the first frame update void Start() { defaultY = transform.position.y; //Debug.Log("AnimControllerのコンストラクタ"); } // Update is called once per frame void Update() { } public void koma_rotation(bool forced) { if (forced || defaultY == transform.position.y) { KOMA_TYPE type = GetComponent<komaScript>().type; if (type == KOMA_TYPE.Black) { Debug.Log("BlackToWhite"); GetComponent<Animator>().Play("BlackToWhite", 0); GetComponent<komaScript>().type = KOMA_TYPE.White; } else { Debug.Log("WhiteToBlack"); GetComponent<Animator>().Play("WhiteToBlack", 0); GetComponent<komaScript>().type = KOMA_TYPE.Black; } } } public void settype(KOMA_TYPE koma_type) { if (koma_type == KOMA_TYPE.Black) { Debug.Log("setBlack"); GetComponent<Animator>().Play("setBlack", 0); } else { Debug.Log("setWhite"); GetComponent<Animator>().Play("setWhite", 0); } } }
2a97083113c93c74d307d205c6c2fc01968e2b35
[ "Markdown", "C#" ]
12
C#
KK56ken/Othello
1a7e3c74d281fc15ab2effc861040bb8ff093e23
39711d87fb9d909f8342e22bc97c139aeb1af8c1
refs/heads/master
<file_sep>package com.codecool.doram.Zoo.animal; import com.codecool.doram.Zoo.Food; public abstract class Animal { protected int fullness; protected String name; protected int max; protected int min; public Animal(int fullness, String name) { this.fullness = fullness; this.name = name; } public abstract void passADay(Food food); }
4416c66445eb12c307791e6884a67bc74396ebca
[ "Java" ]
1
Java
Doram13/Zoo
f69a169f6f0e2baae56704784f70e3f76611d240
b12d0ed4c036cc7a8f89b93f9e535e50ce32a154
refs/heads/Dev
<file_sep><?php // 课程名称的控制器,展示所有课程信息 namespace Student\Controller; use Think\Controller; class CourseNameController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 从数据库中获取所有的课程名称,并输出到模板 * 对应的数据表为hubu_course_name */ function getCourseName() { $info = D('CourseName'); // show_bug($info); $course_name = $info->select(); // 获取数据库中的全部数据 // show_bug($course_name); $this->assign('course_name', $course_name); // $this->display('course_name'); } /** * *****说实在话,写下面这么多一模一样的方法实在没必要,可以只写一个方法,使用switch case 设置传入的参数不同,从而调用不同的指令,但我还是挨个写一遍吧****** */ /** * 所有的课程 */ function all() { $m = M('CourseName'); $where = ''; // 查询条件为空,即查询出所有的课程 $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } // show_bug($list); $this->assign('course_name', $list); $this->display('course_name'); } /** * 计算机类课程 */ function computer() { $m = M('CourseName'); $where = 'course_name_class = 1'; // 课程类别信息在hubu_course_class里面有定义,之所以不在字段中字节定义是因为int型数据查询更快,而这个地方是查询最多的项 $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 经济管理 */ function ecoManagement() { $m = M('CourseName'); $where = 'course_name_class = 2'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 心理学 */ function psychology() { $m = M('CourseName'); $where = 'course_name_class = 3'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 外语 */ function foreignLanguage() { $m = M('CourseName'); $where = 'course_name_class = 4'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 文学历史 */ function literaryHistory() { $m = M('CourseName'); $where = 'course_name_class = 5'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 艺术设计 */ function artDesign() { $m = M('CourseName'); $where = 'course_name_class = 6'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 工学 */ function engineering() { $m = M('CourseName'); $where = 'course_name_class = 7'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 理学 */ function science() { $m = M('CourseName'); $where = 'course_name_class = 8'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 生命科学 */ function biomedicine() { $m = M('CourseName'); $where = 'course_name_class = 9'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 哲学 */ function philosophy() { $m = M('CourseName'); $where = 'course_name_class = 10'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 法学 */ function law() { $m = M('CourseName'); $where = 'course_name_class = 11'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 教育教学 */ function teachingMethod() { $m = M('CourseName'); $where = 'course_name_class = 12'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } /** * 其他 */ function elseCourse() { $m = M('CourseName'); $where = 'course_name_class = 13'; $p = getpage($m, $where, 5); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); /** * 循环查询出每门课程的选课人数以及总节数 */ foreach ($list as $k => $v) { $course_name_id = $v['course_name_id']; $list[$k]['course_choosed_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $list[$k]['course_chapter_count'] = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 } $this->assign('course_name', $list); $this->display('course_name'); } }<file_sep><?php // 前台Student 热门课程的控制器,展示课程信息的模板 namespace Student\Controller; use Think\Controller; class HotCourseController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * "热门课程"的模版页面,展示模版页面并向其输出数据 */ function hotCourse() { $hotCourse = D('HotCourse')->getField('hot_course_course_name', true); // 查询出所有课程的ID信息,查询出全部数据 // show_bug($hotCourse); // print_r($hotCourse); // 通过上述ID,循环查询出所有课程的信息并存储到数组中 $hot = array(); foreach ($hotCourse as $k => $v) { // 使用SQL语句查询,或者使用TP自带的CURD方法操作,推荐使用TP的封装方法 $info = D('CourseName')->where("course_name_id = $v")->find(); // show_bug($info); $info['course_name_choosed_num'] = M('ChooseCourse')->where("choose_course_choosed = $v")->count(); // 已选这门课程总人数 // 将上述查询到的结果存储到$hot数组里面 $hot[$k] = $info; } // show_bug($hot); $this->assign('hot', $hot); $this->display(); } function hotCourseList() { $hotCourse = D('HotCourse')->limit(8)->getField('hot_course_course_name', true); // 查询出所有课程的ID信息,只查询出前8个 // show_bug($hotCourse); // print_r($hotCourse); // 通过上述ID,循环查询出所有课程的信息并存储到数组中 $hot = array(); foreach ($hotCourse as $k => $v) { // 使用SQL语句查询,或者使用TP自带的CURD方法操作,推荐使用TP的封装方法 $info = D('CourseName')->where("course_name_id = $v")->find(); // show_bug($info); // 将上述查询到的结果存储到$hot数组里面 $hot[$k] = $info; } // show_bug($hot); $this->assign('hot', $hot); $this->display(); } }<file_sep><?php // 前台首页图片轮播的控制器 namespace Admin\Controller; use Think\Controller; use Model\ImgTurnModel; class ImgTurnController extends Controller { /** * TODO 展示首页轮播图的信息,并且实现新数据的添加 */ function showImgTurnInfo() { if (empty($_POST)) { // 用户没有提交表单,展示首页轮播图信息 // echo "用户没有提交表单"; header("Content-type:text/html;charset=utf-8"); // 不乱码 // 调用下面获取数据的方法,从数据库中崇训处所有的数据 $info = A('ImgTurn')->getImgTurnInfo(); // show_bug($info); $this->assign('info', $info); $this->display('adv'); } else { // echo "用户有提交表单"; // 检测是否有附件上传 // show_bug($_FILES); if (! empty($_FILES)) { // echo "有附件上传"; // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Admin的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/' ) // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->uploadOne($_FILES['pic']); // 执行上传操作 // print_r($z); // show_bug($z); if (! $z) { $this->error($upload->getError()); // 输出错误 } else { // $this->success("文件上传成功!"); echo "头像文件上传成功!"; } } $_POST['img_turn_pic_url'] = $z['savepath'] . $z['savename']; /** * 这里存储用户头像的文件路径 */ $_POST['img_turn_time'] = date('Y-m-d H:i:s'); $imgTurnInfo = D('ImgTurn')->create(); // 收集表单数据,create不能收集文件数据,所以要单独添加到$_POST里面 // show_bug($imgTurnInfo); // 将数据存储到数据库里面 $rst = D('ImgTurn')->add($imgTurnInfo); // 如果添加成功返回的是这条记录的ID // show_bug($rst); if ($rst) { $this->success('数据添加成功!'); } else { $this->error('数据添加失败!'); } } } /** * TODO 获取数据表hubu_img_turn里面的所有数据 ,其实按道理,数据的操作都应该放在Model里面来写 * * @return \Think\mixed */ function getImgTurnInfo() { $info = D('ImgTurn')->select(); // 从数据库中选出所有轮播图片的信息 // show_bug($info); // 返回获取到的信息 return $info; } /** * TODO 修改某一条轮播图记录,其实他的实现代码与上述添加是一样的,,忘了写成公共函数了,这里就再复制一次吧 * * @param 选中的这条记录的ID值 $img_turn_id */ function updateImgTurnInfo($img_turn_id) { // echo $img_turn_id; // 判断是否有表单提交 if (empty($_POST)) { // 没有表单提交 // echo "没有表单提交"; $info = D('ImgTurn')->select($img_turn_id); // show_bug($info); $this->assign('info', $info); $this->display('update_adv'); } else { // 有表单数据提交 // echo "有表单提交"; // 判断是否有文件提交 if (! empty($_FILES)) { // echo "有附件上传"; // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Admin的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/' ) // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->uploadOne($_FILES['pic']); // 执行上传操作 // print_r($z); // show_bug($z); if (! $z) { $this->error($upload->getError()); // 输出错误 } else { // $this->success("文件上传成功!"); echo "头像文件上传成功!"; } } $_POST['img_turn_pic_url'] = $z['savepath'] . $z['savename']; /** * 这里存储用户头像的文件路径 */ $_POST['img_turn_time'] = date('Y-m-d H:i:s'); $imgTurnInfo = D('ImgTurn')->create(); // 收集表单数据,create不能收集文件数据,所以要单独添加到$_POST里面 // show_bug($imgTurnInfo); $id = $_POST['img_turn_id']; // echo "ID为".$id; // 将数据存储到数据库里面 $rst = D('ImgTurn')->where("img_turn_id = $id")->save($imgTurnInfo); // 如果添加成功返回的是这条记录的ID // show_bug($rst); if ($rst) { $this->success('数据添加成功!'); } else { $this->error('数据添加失败!'); } } } /** * TODO 删除指定的轮播图 * * @param 要删除的轮播图在数据库里面的id $img_turn_id */ function deleteImgTurnTnfo($img_turn_id = 0) { if ($img_turn_id) { $rst = D('ImgTurn')->delete($img_turn_id); // show_bug($rst); $this->redirect('Admin/ImgTurn/showImgTurnInfo'); } else { $this->error('删除错误!'); } } function test() { $info = D('ImgTurn'); // show_bug($info); } }<file_sep><?php // 接口URL地址:http://172.16.31.10:3002/Hubu/Interface/Android/course_class_list.php?format=json /** * 本接口是用来向客户端提供课程大类信息的数据 */ require_once 'response.php'; // 引入公共文件 require_once 'db.php'; // 数据库连接文件 // 接收异常,数据库连接失败 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } $sql = 'select * from hubu_course_class'; $course_class_list_tmp = array(); // 用以存储课程类别信息的临时数组 $course_class_list = array(); // 用以存储课程类别信息的数组 $result = mysql_query($sql, $connect); // 结果集 // 循环取出结果集中的数据 while ($course_class = mysql_fetch_assoc($result)) { // var_dump($course_class); $course_class_list_tmp[] = $course_class; } // 用foreach来遍历数据,将数据转换为所需的格式 foreach ($course_class_list_tmp as $k => $v) { $course_class_list[$k]['college_id'] = $v['course_class_id']; $course_class_list[$k]['name'] = $v['course_class_name']; $course_class_list[$k]['type'] = $v['course_class_type']; } // var_dump($course_class_list_tmp); // 判断数据是否存在,存在就返回,不存在就返回不存在状态码 if ($course_class_list) { return Response::show(400, '课程类别数据获取成功', $course_class_list); } else { return Response::show(401, '课程类别数据获取失败', $course_class_list); }<file_sep><?php // 用户个人中心的控制器 namespace Student\Controller; use Think\Controller; class IController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } function index() { // 先判断用户是否登陆 if (isset($_SESSION['student_user_id'])) { // 用户已经登陆 header("Content-Type:text/html; charset=utf-8"); // 不乱码 $student_user_id = session('student_user_id'); // show_bug($student_user_id); /** * 从数据库中查询出用户的个人信息 */ $studentUserInfo = D('StudentUser')->where("student_user_id = $student_user_id")->find(); // $studentUserInfo['student_user_sex'] = (int)$studentUserInfo['student_user_sex'];//强制转换为int类型 // show_bug($studentUserInfo); $myCourseID = M('ChooseCourse')->where("choose_course_student = $student_user_id")->select(); // 查询出所选的课程的ID已经评分等信息 // show_bug($myCourseID); $myCourseInfo = array(); // 存储从数据库中查询到的已选课程的信息 foreach ($myCourseID as $k => $v) { $choose_course_choosed = $v['choose_course_choosed']; $myCourseInfo[$k] = D('CourseName')->where("course_name_id = $choose_course_choosed")->find(); // 把课程的评分加到$myCourseInfo里面去 $myCourseInfo[$k]['course_name_score'] = (int) $myCourseID[$k]['choose_course_score']; // 查询出课程的总的学习进度信息,并添加到 $myCourseInfo 里面 $wheres = 'chapter_progress_student = ' . $student_user_id . ' and chapter_progress_course = ' . $choose_course_choosed; $progress_tmp = M('ChapterProgress')->where($wheres)->sum('chapter_progress_state'); $chapter_count = D('CourseChapter')->where("course_chapter_course_name = $choose_course_choosed")->count(); // 统计这门课程总节数 /** * 计算出该生该课程的总学习进度 学习总进度 = 小节进度和/小节数 */ $course_progress = round($progress_tmp / ($chapter_count * 100), 3) * 100; // 算平均评分,四舍五入一位小数,再换算成百分数形式 $myCourseInfo[$k]['course_progress'] = $course_progress; } // show_bug($myCourseInfo); $this->assign('myCourseInfo', $myCourseInfo); $this->assign('studentUserInfo', $studentUserInfo); // 向页面输出用户信息 $this->display(); } else { $this->error('请先登录!', SITE_URL); } } /** * 删除已选的课程 * * @param 课程的ID信息 $course_name_id */ function deleteChoosedCourse($course_name_id = 0) { if ($course_name_id) { // echo $course_name_id; $student_user_id = session('student_user_id'); // 执行删除操作 $rzt = M('ChooseCourse')->where("choose_course_student = $student_user_id and choose_course_choosed = $course_name_id")->delete(); if ($rzt) { $this->success('退出课程成功!'); } else { $this->error('出现未知错误,请联系管理员!'); } } } /** * 给课程评分的方法 * * @param 课程的ID信息 $course_name_id */ function marking($course_name_id = 0) { if ($course_name_id) { if (! empty($_POST)) { // echo $course_name_id; // show_bug($_POST); $score = M('ChooseCourse')->create(); // 收集表单数据 $student_user_id = session('student_user_id'); $rst = M('ChooseCourse')->where("choose_course_choosed = $course_name_id and choose_course_student = $student_user_id")->save(); if ($rst) { $this->success('评分成功!'); } else { $this->error('评分失败!'); } } } else { $this->error('出现未知错误,请联系管理员', SITE_URL); } } /** * 更改用户的密码 */ function updatePassword() { // show_bug($_POST); if (! empty($_POST)) { // echo "提交了表单"; $info = new \Model\StudentUserModel(); $rst = $info->checkNamePwd(session('student_user_username'), $_POST['mpass']); // 从session中获取当前用户的用户名 // show_bug($rst); if ($rst) { // 存储表单接收到的数据 $arr = array( 'student_user_pwd' => $_POST['<PASSWORD>'],/* 获取表单中的新密码 */ ); $student_user_id = session('student_user_id'); // 存储用户的ID信息 $resault = D('StudentUser')->where("student_user_id = $student_user_id")->save($arr); // show_bug($resault); if ($resault) { $this->success('密码修改成功'); } else { $this->error('密码修改失败'); } } else { $this->error('密码输入错误'); } } else { $this->error('没有提交表单'); } } /** * 更新用户的个人信息 */ function updateUserInfo() { // show_bug($_POST); if (! empty($_FILES['student_user_pic']['tmp_name'])) { // 选择了头像图片 // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Admin的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/' ) // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->uploadOne($_FILES['student_user_pic']); // 执行上传操作 // print_r($z); // show_bug($z); if (! $z) { // show_bug($upload->getError()); // $this->error($upload->getError());//输出错误 $this->error('头像上传失败'); } else { // $this->success("头像上传成功!"); echo "头像上传成功!"; } $_POST['student_user_pic'] = $z['savepath'] . $z['savename']; /** * 这里存储用户头像的文件路径 */ $_POST['student_user_time'] = date('Y-m-d H:i:s'); $student_user_id = session('student_user_id'); // 存储用户的ID信息 $studentUserInfo = D('StudentUser')->create(); // show_bug($studentUserInfo); // show_bug($_POST); $rst = D('StudentUser')->where("student_user_id = $student_user_id")->save(); // 更新数据库 if ($rst) { $this->success('数据更新成功!'); } else { // show_bug($rst); $this->error('数据更新失败!'); } } else { $this->error('没有选择头像文件'); } } }<file_sep><?php // 接口URL地址:http://172.16.58.3:3002/Hubu/Interface/Android/hot_course_list.php?format=json /** * 本接口是用来向客户端提供热门课程信息的数据 */ require_once 'response.php'; // 引入公共文件 require_once 'db.php'; // 数据库连接文件 require_once 'common.php'; // 引入公共函数文件 // 接收异常,数据库连接失败 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } $sql = 'select * from hubu_hot_course'; $hot_course_list_tmp = array(); // 用以存储热门课程信息的临时数组 $hot_course_list = array(); // 用以存储热门课程信息的数组 $hot_course_list_final = array(); // 存储热门课程信息的最终数组 $result = mysql_query($sql, $connect); // 结果集 // 循环取出结果集中的数据 while ($hot_course_code = mysql_fetch_assoc($result)) { // var_dump($course_class); $hot_course_list_tmp[] = $hot_course_code['hot_course_course_name']; // 只存储ID } // 用foreach来遍历数据,将数据转换为所需的格式 foreach ($hot_course_list_tmp as $k => $v) { $hot_course_list[] = getHotCourse($v); // 调用common里面的函数来查询出该课程的信息 } // var_dump($hot_course_list_tmp); // var_dump($hot_course_list); foreach ($hot_course_list as $k => $v) { $hot_course_list_final[$k]['course_id'] = $v['course_name_id']; $hot_course_list_final[$k]['name'] = $v['course_name_name']; $hot_course_list_final[$k]['image'] = ADMIN_IMG_UPLOADS . $v['course_name_pic']; $hot_course_list_final[$k]['description'] = $v['course_name_intro']; $hot_course_list_final[$k]['teacher'] = $v['course_name_adder']; $hot_course_list_final[$k]['choose_count'] = getChoosedCount($v['course_name_id']); $hot_course_list_final[$k]['class'] = getChapterCount($v['course_name_id']); } // 判断数据是否存在,存在就返回,不存在就返回不存在状态码 if ($hot_course_list_final) { return Response::show(408, '热门课程信息获取成功', $hot_course_list_final); } else { return Response::show(409, '热门课程信息获取失败', $hot_course_list_final); }<file_sep><?php // 课程的控制器,展示课程信息的模板 namespace Student\Controller; use Think\Controller; class OccupationController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * "职业"选项的网页模板展示,与IndexController同等级别 */ function index() { // echo "这是职业展示页面"; $this->display(); } }<file_sep><?php // 学生用户个人基本信息的控制器 namespace Student\Controller; use Think\Controller; class StudentUserController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 用户登录的方法, * 接收用户输入的表单数据(账户,密码,验证码), * 并对其进行校验,生成session */ function login() { // 判断用户是否提交了表单 if (! empty($_POST)) { // 提交了表单 // print_r($_POST); // 验证码校验,实例化一个Verify对象,调用其中的check方法校验验证码 $verify = new \Think\Verify(); if (! $verify->check($_POST['code'])) { // echo "验证码错误!"; $this->error("验证码输入错误!"); } else { // 验证码输入正确,账号密码校验 $user = new \Model\StudentUserModel(); // 实例化StudentUserModel调用其中的checkNamePwd()方法,好对student_user数据库中的数据进行操作 $z = $user->checkNamePwd($_POST['student_user_email'], $_POST['student_user_pwd']); // show_bug($z); // 判断账号密码是否验证成功 if ($z === false) { // 账号密码输入错误 $this->error("输入的用户名或密码错误!"); } else { // 账号密码输入正确 // 进行账号激活校验,即student_user_verify字段,只有此字段为真(1)才能进行下一步操作,否则发送邮件激活 // $rst = $user->getField('student_user_verify'); $rst = $z['student_user_verify']; // show_bug($rst); if (! $rst) { // 邮箱没有验证,提示发送邮件验证 $email = $z['student_user_email']; // 获取邮箱字段的值 $id = $z['student_user_id']; // 获取id // 发送激活邮件 // show_bug($email); // show_bug($id); // 账号激活的URL地址,例如 http://web.hubu.edu:3002/index.php/Student/StudentUser/activeAccount/id/1 $activeURL = SITE_URL . 'index.php/Student/StudentUser/activeAccount/id/' . $id . ' '; // show_bug($activeURL); $a = think_send_mail($email, '湖北大学网络课程平台', '账号激活邮件', '您的账号为:' . $email . ',点击链接激活账号:' . $activeURL); // show_bug($a); $this->error("您的账号还没有激活,我们已向您的邮箱 $email 发送了激活邮件,请注意查收并登录邮箱激活账号!"); } else { /** * ********************************登陆成功后执行的操作********************************** */ // echo "登陆成功"; // show_bug($z);//数据库中查询到的用户信息那一条记录 // 登录信息持久化,生成session,这里要存储的将是大量的信息,包括学生课程相关的信息 // 性别在数据库中存储为1,2两种形式,如果为数字1就是男,数字2就是女,这里写一个判断 if ($z['student_user_sex'] == 1) { session('student_user_sex', '男'); // 存储用户性别adminuser_sex } else if ($z['student_user_sex'] == 2) { session('student_user_sex', '女'); // 存储用户性别adminuser_sex } else { session('student_user_sex', '未知'); // 存储用户性别adminuser_sex } // 在session中存储其他信息 session('student_user_id', $z['student_user_id']); // 存储用户信息在数据表中的ID值student_user_id session('student_user_username', $z['student_user_username']); // 存储用户名student_user_username session('student_user_email', $z['student_user_email']); // 存储用户注册邮箱student_user_email session('student_user_tel', $z['student_user_tel']); // 存储电话号码 session('student_user_qq', $z['student_user_qq']); // 存储QQ session('student_user_addr', $z['student_user_addr']); // 存储地址 session('student_user_pic', $z['student_user_pic']); // 存储用户头像路径 session('student_user_intro', $z['student_user_intro']); // 存储用户个人介绍 // echo "session生成成功!"; $this->success('登录成功!'); } } } } } /** * 用以激活学生用户的账号 * 用户点击这个链接后实现对数据库中student_user_verify字段的更改,将其值改为1 * * @param 要传入的学生用户那一天记录的id值 $id */ function activeAccount($id = 0) { if ($id) { // echo $id; // 传入的id值大于0,即不是默认值,对student_user数据表中字段进行修改 $user = new \Model\StudentUserModel(); // 实例化StudentUser,调用其中的方法来操作数据库,注意,数据库的操作尽量都留在Model里面 $z = $user->activeAccount_Model($id); // show_bug($z); if ($z) { // echo "^_^恭喜你,账号激活成功!点击链接访问:".SITE_URL; $this->success('^_^恭喜你,账号激活成功!', SITE_URL); } } else { // echo "额。。。貌似出现了什么了不得的东西,账号激活失败,请联系网站管理员!"; $this->error('额,账号激活失败。貌似出现了什么了不得的东西,请联系网站管理员!', SITE_URL); } } /** * 用户个人中心 * 展示个人基本信息,提供基本信息的修改功能 */ function personalCenter() { $this->display(); } /** * 学生用户注册的方法 * 接收注册时候的表单,并向数据库写入注册用户信息 */ function register() { // echo "学生用户注册的方法"; // show_bug($_POST); // 首先校验验证码的正确性 $verify = new \Think\Verify(); if (! $verify->check($_POST['code'])) { // echo "验证码错误!"; $this->error("验证码输入错误!"); } else { // 验证码输入正确 // echo "验证码正确"."<br>"; // 收集表单数据,表单验证就直接在前端用JS实现,这样效果好一些,在后端验证会增加服务器开销,当然后端校验数据完整性更强 if (! empty($_POST)) { // 用户提交了表单 // echo "提交了表单"; // show_bug($_POST); // 检查此邮箱是否已经注册过 // 实例化Model,调用其中的邮箱验证方法验证邮箱是否已经被注册过了 $user = new \Model\StudentUserModel(); // show_bug($user); $info = $user->checkEmail_Registered($_POST['student_user_email']); // show_bug($info); if ($info) { // 邮箱已经被注册过了 // echo "这个邮箱已经被人注册过了,请换一个邮箱账号重新注册"; $this->error("这个邮箱已经被人注册过了,请换一个邮箱账号重新注册!", SITE_URL); } else { // echo "邮箱没有被注册"; // 邮箱没有被注册,发送邮件到注册的邮箱,向数据库写入数据 // 收集表单数据,把时间添加到$_POST里面 $_POST['student_user_time'] = date("Y-m-d H:i:s"); // 用户注册的时间 //$_POST['student_user_username'] = $_POST['student_user_email']; // 默认在注册的时候,用户名就是邮箱,但是这是两个字段 $m = D('StudentUser'); $rst = $m->create(); // 收集表单数据,存储到 $rst 中 // show_bug($rst); $z = $m->add(); // 将数据写入到数据库 // show_bug($z); // 向邮箱发送账号激活链接 $user = new \Model\StudentUserModel(); $r = $user->getBystudent_user_email($_POST['student_user_email']); // 获取邮箱字段的值 // show_bug($r); $id = $r['student_user_id']; // 获取id $email = $r['student_user_email']; // 获取email // show_bug($email); // 账号激活的URL地址,例如 http://web.hubu.edu:3002/index.php/Student/StudentUser/activeAccount/id/1 $activeURL = SITE_URL . 'index.php/Student/StudentUser/activeAccount/id/' . $id . ' '; // show_bug($activeURL); $a = think_send_mail($email, '湖北大学网络课程平台', '账号激活邮件', '您的账号为:' . $email . ',点击链接激活账号:' . $activeURL); // show_bug($a); $this->success("^_^恭喜,注册成功,我们已经向您的邮箱发送了激活链接,请尽快激活账号!", SITE_URL); } } } } /** * 退出登录,主要是清除session,然后跳转到网站首页 */ function logout() { session(null); // 清除所有的session值 $this->redirect(SITE_URL); // 跳转到网站首页 } /** * 名称:verifyImg() * 功能:实现验证发的生成 */ function verifyImg() { // 配置验证码的数组 $config = array( 'expire' => 1800, // 验证码过期时间(s) 'useZh' => false, // 使用中文验证码 'useImgBg' => false, // 使用背景图片 'fontSize' => 14, // 验证码字体大小(px) 'useCurve' => false, // 是否画混淆曲线 'useNoise' => false, // 是否添加杂点 'imageH' => 32, // 验证码图片高度 'imageW' => 100, // 验证码图片宽度 'length' => 4, // 验证码位数 'fontttf' => '', // 验证码字体,不设置随机获取 'bg' => array( 243, 251, 254 ), // 背景颜色 'reset' => true ) // 验证成功后是否重置 ; // 实例化的时候传入配置 $verify = new \Think\Verify($config); // 实例化Verify对象,此处要注意命名空间的书写,可以使用在index.php中定义的show_bug()函数输出对象看实例化好了没有 // show_bug($verify); $verify->entry(); } // 下面的方法作为书写login的参考 /** * * * 处理用户反馈表单的方法 */ function feedback() { // echo "feedback"; // show_bug(empty($_POST)); // 判断用户是否提交了表单 if (! empty($_POST)) { // 用户提交了表单 // echo "有表单数据"; // 收集表单数据 // show_bug($_POST); // 把时间添加到$_POST里面 $_POST['feedback_time'] = date("Y-m-d H:i:s"); $info = D('Feedback'); $z = $info->create(); // show_bug(count($z)); $a = $info->add(); // 将表单数据存储到数据库 // show_bug($a);//这里$a是插入后那一行数据的ID号 // 下面的这个判断并没有多大用,留给前端去实现表单验证吧 if ($a) { // 数据提交存储成功,链接跳转 $this->success('我们已收到您的反馈,会及时处理!'); } else { // 数据存储失败 $this->error('反馈提交失败,请重新提交!'); } } else { // 用户没有提交表单,直接展示模版 // echo "无表单数据"; $this->display(); } } }<file_sep><?php // 后台管理员用户控制器 // 命名空间必须写在第一行 namespace Teacher\Controller; use Think\Controller; class TeacherUserController extends Controller { /** * 名称:login() * 功能:管理员用户登录的相关逻辑判断 */ function login() { // 判断用户是否提交了表单 if (! empty($_POST)) { // 先输出这个值看对不对,经输出,得输出值为 Array ( [name] => 00 [password] => 000 [code] => 000 ) // print_r($_POST); // 验证码校验 $verify = new \Think\Verify(); // 实例化一个Verify对象,好调用其中的校验验证码的方法 check($code, $id) if (! $verify->check($_POST['code'])) { // echo "验证码错误!"; $this->error("验证码输入错误!"); } else { // echo "验证码正确!"; // 验证码正确之后,判断用户名和密码 // 可以直接用一条SQL语句从数据库中同时查询用户名和密码,如果存在就说明正确,但此方法不安全,会增加SQL注入风险 // 一般,先查询指定用户名的信息,如果有这条信息再比较密码是否正确 // 在model模型里面专门写一个方法进行验证,当前model模型为TeacherUserModel,不要再控制器里面验证 $user = new \Model\TeacherUserModel(); // 实例化TeacherUserModel()对象,好调用其中自定义的检验用户名密码是否正确的方法checkNamePwd($name,$pwd) $rst = $user->checkNamePwd($_POST['username'], $_POST['password']); // $rst如果为false,那说明输入的密码不正确,如果为一个数组,就说明输入正确,就可以生成session信息 show_bug($rst); if ($rst === false) { // echo "输入的用户名或者密码错误!"; $this->error("输入的用户名或密码错误!"); } else { // 登录信息持久化,生成session信息 // 性别在数据库中存储为1,2两种形式,如果为数字1就是男,数字2就是女,这里写一个判断 if ($rst['adminuser_sex'] == 1) { session('adminuser_sex', '男'); // 存储用户性别adminuser_sex } else if ($rst['adminuser_sex'] == 2) { session('adminuser_sex', '女'); // 存储用户性别adminuser_sex } else { session('adminuser_sex', '未知'); // 存储用户性别adminuser_sex } session('adminuser_id', $rst['adminuser_id']); // 存储id session('adminuser_username', $rst['adminuser_username']); // 存储用户名adminuser_username session('adminuser_email', $rst['adminuser_email']); // 存储用户adminuser_email // session('adminuser_sex', $rst['adminuser_sex']);//存储用户性别adminuser_sex session('adminuser_tel', $rst['adminuser_tel']); // 存储用户电话adminuser_tel session('adminuser_qq', $rst['adminuser_qq']); // 存储用户QQ adminuser_qq session('adminuser_addr', $rst['adminuser_addr']); // 存储用户地址adminuser_addr session('adminuser_introduction', $rst['adminuser_introduction']); // 存储用户个人简介adminuser_introduction session('adminuser_pic', $rst['adminuser_pic']); // 存储用户头像路径信息 // echo "登陆成功!"; /** * *************************************教师此时同样需要模拟学生账户登录,用以得到预览课程的目的,教师账号与学生账号密码一样************************************************ */ // 检查学生用户数据表中是否有这个账户,如果有就直接生成session,没有就添加一条数据 // 验证码输入正确,账号密码校验 $user = new \Model\StudentUserModel(); // 实例化StudentUserModel调用其中的checkNamePwd()方法,好对student_user数据库中的数据进行操作 // 检查数据库中是否有这条数据 $rst0 = M('StudentUser')->where('student_user_email = ' . '\'' . $rst['adminuser_email'] . '\'')->find(); // show_bug($rst0); if (! empty($rst0)) { $z = $user->checkNamePwd($rst['adminuser_email'], $rst['adminuser_pwd']); // show_bug($z); // 判断账号密码是否验证成功 if ($z === false) { // 账号密码输入错误 // $this->error("输入的用户名或密码错误!"); echo '账号密码输入错误'; } else { // 账号密码输入正确 // 进行账号激活校验,即student_user_verify字段,只有此字段为真(1)才能进行下一步操作,否则发送邮件激活 // $rst = $user->getField('student_user_verify'); $rst = $z['student_user_is_teacher']; // show_bug($rst); if ($rst) { /** * ********************************登陆成功后执行的操作********************************** */ // echo "登陆成功"; // show_bug($z);//数据库中查询到的用户信息那一条记录 // 登录信息持久化,生成session,这里要存储的将是大量的信息,包括学生课程相关的信息 // 性别在数据库中存储为1,2两种形式,如果为数字1就是男,数字2就是女,这里写一个判断 if ($z['student_user_sex'] == 1) { session('student_user_sex', '男'); // 存储用户性别adminuser_sex } else if ($z['student_user_sex'] == 2) { session('student_user_sex', '女'); // 存储用户性别adminuser_sex } else { session('student_user_sex', '未知'); // 存储用户性别adminuser_sex } // 在session中存储其他信息 session('student_user_id', $z['student_user_id']); // 存储用户信息在数据表中的ID值student_user_id session('student_user_username', $z['student_user_username']); // 存储用户名student_user_username session('student_user_email', $z['student_user_email']); // 存储用户注册邮箱student_user_email session('student_user_tel', $z['student_user_tel']); // 存储电话号码 session('student_user_qq', $z['student_user_qq']); // 存储QQ session('student_user_addr', $z['student_user_addr']); // 存储地址 session('student_user_pic', $z['student_user_pic']); // 存储用户头像路径 session('student_user_intro', $z['student_user_intro']); // 存储用户个人介绍 // echo "session生成成功!"; // $this->success('登录成功!'); } else { $this->error('出现未知错误,请联系管理员', SITE_URL); } } } else { // 数据库中没有这条数据,插入一条数据,并指明这是教师账户 $arr = array( 'student_user_username' => $rst['adminuser_email'], 'student_user_email' => $rst['adminuser_email'], 'student_user_pwd' => $rst['<PASSWORD>'], 'student_user_is_teacher' => 1 ); $rst1 = D('StudentUser')->add($arr); if (empty($rst1)) { echo '与教师账户相互映射的学生账户添加失败'; } else { echo '与教师账户相互映射的学生账户添加成功'; // 生成session // 查询出刚添加的这条信息 $rst2 = M('StudentUser')->where('student_user_email = ' . '\'' . $rst['adminuser_email'] . '\'')->find(); session('student_user_id', $rst2['student_user_id']); // 存储用户信息在数据表中的ID值student_user_id session('student_user_username', $rst['adminuser_email']); // 存储用户名student_user_username session('student_user_email', $rst['adminuser_email']); // 存储用户注册邮箱student_user_email } } } // 跳转到后台首页,Controller类的redirect()方法 $this->redirect('New/category', array('cate_id' => 2), 5, '页面跳转中...'); // 将参数array('cate_id' => 2)传递到index $this->redirect('TeacherIndex/index'/*,array('Teacheruser_username' => $rst['adminuser_username']) ,1,'正在登录到后台系统...' */); } } else { // 调用视图display(),直接展示login.html模板,display()没有参数那么调用的模板名称就与当前方法名一致 $this->display(); } } /** * 名称:logout() 退出系统的方法 * 功能:要清除session,跳转到登录页面 */ function logout() { session(null); // 清除所有的session值 $this->redirect('TeacherUser/login'); // 跳转到登录界面,即调用TeacherUser控制器的login方法 } /** * 名称:verifyImg() * 功能:实现验证发的生成 */ function verifyImg() { // 配置验证码的数组 $config = array( 'expire' => 1800, // 验证码过期时间(s) 'useZh' => false, // 使用中文验证码 'useImgBg' => false, // 使用背景图片 'fontSize' => 14, // 验证码字体大小(px) 'useCurve' => false, // 是否画混淆曲线 'useNoise' => false, // 是否添加杂点 'imageH' => 32, // 验证码图片高度 'imageW' => 100, // 验证码图片宽度 'length' => 4, // 验证码位数 'fontttf' => '', // 验证码字体,不设置随机获取 'bg' => array( 243, 251, 254 ), // 背景颜色 'reset' => true ) // 验证成功后是否重置 ; // 实例化的时候传入配置 $verify = new \Think\Verify($config); // 实例化Verify对象,此处要注意命名空间的书写,可以使用在admin.php中定义的show_bug()函数输出对象看实例化好了没有 // show_bug($verify); $verify->entry(); } /** * 实现用户注册的方法 */ public function register() { echo "这是用户注册功能,待完善中..."; } /** * 实现对自己管理员账户信息的修改操作 * 接收表单提交过来的数据 * 并将数据库中的用户个人信息进行更新 */ function updateUserInfo() { // print_r($_POST);//Array ( [mpass] => <PASSWORD>6 [newpass] => <PASSWORD> [renewpass] => <PASSWORD> ) // echo count($_POST);//输出数组长度,后面根据数组长度判断提交的是哪个表单 // 1.检测用户是否提交了表单 if (! empty($_POST)) { // print_r($_POST); // 检测用户提交的是哪个表单,根据$_POST数组长度来判断 if (count($_POST) == 3) { // 用户提交的是修改管理员密码的表单 // 需要验证用户名与密码是否正确,可以直接跨控制器调用AdminUser/checkNamwePwd方法 $info = new \Model\TeacherUserModel(); // show_bug($info); $rst = $info->checkNamePwd(session('adminuser_username'), $_POST['mpass']); // 从session中获取当前用户的用户名 // show_bug($rst); // echo session('adminuser_username'); if ($rst) { // 原始密码输入正确 // echo "原始密码输入正确"; // 1.收集表单数据 2.实现用户密码的修改操作 $arr = array( 'adminuser_pwd' => $_POST['<PASSWORD>'],/* 获取表单中的新密码 */ ); $resault = $info->where('adminuser_id = %d', array( session('adminuser_id') ))->save($arr); // 同时更改与教师账户相映射的学生账户的密码 $arr2 = array( 'student_user_pwd' => $_POST['<PASSWORD>'],/* 获取表单中的新密码 */ ); $resault2 = M('StudentUser')->where('student_user_id = %d', array( session('student_user_id') ))->save($arr2); // show_bug($resault); // 根据$resault值判断是否修改成功,给予用户提示信息 if ($resault) { // 修改成功 // echo "修改密码成功"; // 跳转到原页面 $this->redirect('TeacherUser/updateUserInfo', array(), 3, '密码修改成功...正在跳转...'); } else { // 修改不成功 // echo "修改不成功"; $this->redirect('TeacherUser/updateUserInfo', array(), 3, '密码修改失败/未更改...正在跳转...'); } } else { // 原始密码输入不正确 // echo "原始密码输入不正确"; $this->redirect('TeacherUser/updateUserInfo', array(), 3, '原始密码输入不正确...正在跳转...'); } } else { // 用户提交的是修改管理员其他信息的表单 // echo "用户提交的是修改管理员其他信息的表单"; // $aaaa = D('TeacherUser'); // $a = $aaaa->select(); // show_bug($a); $info = new \Model\TeacherUserModel(); // 判断是否有附件上传,有就实例化Upload,把附件上传到服务器指定位置,获得附件路径名存入$_POST if (! empty($_FILES)) { // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Teacher的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/' ) // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->uploadOne($_FILES['pic']); // 执行上传操作 // print_r($z); // show_bug($z); if (! $z) { $this->error($upload->getError()); // 输出错误 } else { // $this->success("文件上传成功!"); echo "头像文件上传成功!"; } } // 实现对用户其他信息修改的操作 // 收集post表单数据 $user_info = array( 'adminuser_email' => $_POST['email'], 'adminuser_sex' => $_POST['sex'], 'adminuser_tel' => $_POST['tel'], 'adminuser_qq' => $_POST['qq'], 'adminuser_addr' => $_POST['addr'], 'adminuser_introduction' => $_POST['introduction'], 'adminuser_pic' => /* $config['rootPath']. */$z['savepath'] . $z['savename'] )/** * 这里存储用户头像的文件路径 */ ; // show_bug($user_info); $res = $info->where('adminuser_id = %s', array( $_POST['adminuser_id'] ))->save($user_info); // show_bug($res); // 根据$resault值判断是否修改成功,给予用户提示信息 if ($res) { // 修改成功 // echo "修改成功"; /** * 因为页面上部分信息是从session中获得,所以更改个人信息后就需要更新以下session */ // 跳转到原页面 $this->redirect('TeacherUser/updateUserInfo', array(), 3, '信息修改成功,重新登录后生效...正在跳转...'); } else { // 修改不成功 // echo "信息修改不成功"; $this->redirect('TeacherUser/updateUserInfo', array(), 3, '信息修改失败/未更改...正在跳转...'); } } } else { // 用户没有提交表单,那么从session中读取出用户的个人信息,放到表单里面 // 展现表单 // $this->assign($a); $this->display(); } // echo "实现对自己管理员账户信息的修改操作"; // $this->display(); } }<file_sep><?php // 数据分析的控制器 namespace Teacher\Controller; use Think\Controller; class DaController extends Controller { /** * 展示我所有的课程 */ function showMyCourse() { header("Content-Type:text/html; charset=utf-8"); // 不乱码 $wheres = 'course_name_adder_id = ' . session('adminuser_id'); $course_list = M('CourseName')->where($wheres)->select(); // show_bug($course_list); // 每门课程的选课人数 foreach ($course_list as $k => $v) { $course_name_id = $v['course_name_id']; $course_list[$k]['course_name_choose_count'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 } // show_bug($course_list); $this->assign('course_list', $course_list); $this->display(); } /** * 展示选了这门课的学生的列表 * * @param unknown $course_name_id */ function showChooseCourseList($course_name_id) { header("Content-Type:text/html; charset=utf-8"); // 不乱码 $wheres = 'choose_course_choosed = ' . $course_name_id; $student_id_list = M('ChooseCourse')->where($wheres)->select(); // show_bug($student_id_list); $student_info_list = array(); foreach ($student_id_list as $k => $v) { $student_info_list[$k] = M('StudentUser')->where('student_user_id = ' . $v['choose_course_student'])->find(); // find生成的是一维数组 $chapter_count = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 /** * 查询出该生该课程的总得学习进度 学习总进度 = 小节进度和/小节数 */ $wheres = 'chapter_progress_student = ' . $v['choose_course_student'] . ' and chapter_progress_course = ' . $course_name_id; $progress_tmp = M('ChapterProgress')->where($wheres)->sum('chapter_progress_state'); /** * 计算出该生该课程的总学习进度 学习总进度 = 小节进度和/小节数 */ $student_info_list[$k]['progress'] = round($progress_tmp / ($chapter_count * 100), 3) * 100; // 算平均评分,四舍五入一位小数,再换算成百分数形式 } // show_bug($student_info_list); // krsort($student_info_list); $student_high_95 = array(); // 全部学完的学生,大于等于95 $student_low_95 = array(); $student_low_70 = array(); // 低于80%的学生 $student_low_50 = array(); $student_low_30 = array(); foreach ($student_info_list as $kk => $vv) { if ($vv['progress'] >= 95) { $student_high_95[] = $vv; } elseif (70 < $vv['progress'] && $vv['progress'] <= 95) { $student_low_95[] = $vv; } elseif (50 < $vv['progress'] && $vv['progress'] <= 70) { $student_low_70[] = $vv; } elseif (30 < $vv['progress'] && $vv['progress'] <= 50) { $student_low_50[] = $vv; } elseif ($vv['progress'] <= 30) { $student_low_30[] = $vv; } else {} } /* * show_bug($student_high_95); * show_bug($student_low_95); * show_bug($student_low_70); * show_bug($student_low_50); * show_bug($student_low_30); */ $this->assign('student_high_95', $student_high_95); $this->assign('student_low_95', $student_low_95); $this->assign('student_low_70', $student_low_70); $this->assign('student_low_50', $student_low_50); $this->assign('student_low_30', $student_low_30); $this->assign('student_info_list', $student_info_list); $this->display(); } }<file_sep><?php // 课程类别的控制器,数学类,艺术设计类,计算机类 namespace Student\Controller; use Think\Controller; class CourseClassController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 读取数据库中课程类别的信息 * 读出有数据库表hubu_course_class多少种类别 */ function getCourseClass() { $info = D('CourseClass'); // show_bug($info); $course_class = $info->select(); // show_bug($z); $this->assign('course_class', $course_class); // 将数据输出到模板引擎 } }<file_sep><?php // 播放视频的控制器 namespace Student\Controller; use Think\Controller; class VideoController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 展示视频播放页的方法,并将课程的参数传递进来 * * @param 课程名的id $course_name * @param 课程小节chapter的id $id */ function index($course_name, $id) { // echo $course_name; // echo $id; header("Content-Type:text/html; charset=utf-8"); // 首页不乱码 /** * 通过session值查询数据库中的信息,判断用户是否选了这门课程* */ // echo session('student_user_id'); if (isset($_SESSION['student_user_id'])) { // 用户已经登陆,查询数据表hubu_choose_course看用户有没有选择这门课 $user_id = session('student_user_id'); $check = M('ChooseCourse')->where("choose_course_choosed = $course_name and choose_course_student = $user_id")->find(); // show_bug($check); if ($check) { // echo "真"; } else { // echo "假"; // 用户没有选择这门课程,弹出提示让他选择,否则不能观看视频 $this->error('您还没有选择这门课程,不能观看视频', SITE_URL); } } else { $this->error('请登陆后再查看视频', SITE_URL); } // echo $course_name.'<br>'; // echo $id; // 根据传进来的参数,获取课程的信息,该节视频的信息,该门课程的信息 // $course_chapter_sql = "select * from hubu_course_chapter where course_chapter_name = $course_name and course_chapter_id = $id"; // $course_info = getCourseSectionChapterList($course_name); // //show_bug($course_info); // /**下面用循环将$course_info 里面的url地址统一用url安全编码方法进行编码,同时将课程进度记录要用的参数拼接进去**/ // foreach ($course_info as $k => &$v){ // //show_bug($v); // foreach ($v as $kk => &$vv){ // //执行url编码 // //echo $vv['course_chapter_video_url'].'<br>'; // $vv['course_chapter_video_url'] = urlsafe_b64encode(ADMIN_IMG_UPLOADS.$vv['course_chapter_video_url']); // //echo $vv['course_chapter_video_url']; // /**课程进度记录相关的代码*/ // //课程进度记录需要四个参数,课程ID,小节ID,用户ID,还有播放进度,将其加入到下面的section_chapter中 // //需要添加的信息有 课程ID 用户ID ,小节ID已经有了, // $vv['course_id'] = $course_name; // $vv['student_id'] = $_SESSION['student_user_id']; // $vv['chapter_id'] = $vv['course_chapter_id'];//换个名字在存储一次 // //该小节课程之前的学习进度 // $wheres = 'chapter_progress_student = '.$_SESSION['student_user_id'].' and chapter_progress_course = '.$course_name.' and chapter_progress_chapter = '.$vv['course_chapter_id']; // //echo $wheres; // $chapter_current_time_tmp = M('ChapterProgress')->where($wheres)->find(); // //show_bug($chapter_current_time_tmp); // //echo $chapter_current_time_tmp['chapter_progress_current_time']; // $vv['chapter_current_time'] = (int)$chapter_current_time_tmp['chapter_progress_current_time']; // } // unset($vv);//取消引用 // } // unset($v);//取消引用 $chapter_info = D('CourseChapter')->where("course_chapter_course_name = $course_name and course_chapter_id = $id")->find(); /* query($course_chapter_sql); */ // show_bug($chapter_info); // echo $chapter_info['course_chapter_video_url'];//数据库中存储的video视频的相对地址 $chapter_info['course_chapter_video_url'] = ADMIN_IMG_UPLOADS . $chapter_info['course_chapter_video_url']; // 拼接成完整的url地址 // echo $chapter_info['course_chapter_video_url']; $chapter_info['course_chapter_video_url'] = urlsafe_b64encode($chapter_info['course_chapter_video_url']); // url编码 // echo $chapter_info['course_chapter_video_url']; // echo urlsafe_b64decode($chapter_info['course_chapter_video_url']); // show_bug($chapter_info); // show_bug($course_info); // 课程进度记录需要四个参数,课程ID,小节ID,用户ID,还有播放进度,将其加入到下面的$chapter_info中 // 需要添加的信息有 课程ID 用户ID ,小节ID已经有了, $chapter_info['course_id'] = $course_name; $chapter_info['student_id'] = $_SESSION['student_user_id']; $chapter_info['chapter_id'] = $chapter_info['course_chapter_id']; // 该小节课程之前的学习进度 $wheres = 'chapter_progress_student = ' . $_SESSION['student_user_id'] . ' and chapter_progress_course = ' . $course_name . ' and chapter_progress_chapter = ' . $chapter_info['course_chapter_id']; // echo $wheres; $chapter_current_time_tmp = M('ChapterProgress')->where($wheres)->find(); $chapter_info['chapter_current_time'] = (int) $chapter_current_time_tmp['chapter_progress_current_time']; // show_bug($chapter_info); // section_chapter中添加了进度记录的几个参数,因为在模板中要用到 $this->assign('chapter_info', $chapter_info); // $this->assign('section_chapter',$course_info); $this->display('index'); } /** * 视频播放模板展示与控制,传入的参数是视频的url地址,这个url地址是从Uploads以后的地址 * ADMIN_IMG_UPLOADS这个常量与其拼接之后才是完整的url地址 * 这里强调一下,因为url地址里面有/符号,所以需要用到一种方案将斜杠/以及其他字符转变为其他的字符串,随后使用的时候将其解码 */ function videoPlayer($video_url = '', $course_id = 0, $chapter_id = 0, $student_id = 0, $chapter_current_time = 0) { // echo $video_url; // echo urlencode($video_url);// // echo urlsafe_b64decode($video_url);//url解码 $video_url = urlsafe_b64decode($video_url); // echo $video_url; /** * 此方法还承担着接收以及输出相关课程小节学习进度记录的资料 */ // echo $chapter_current_time; // 存储用get方式传进来的参数的值 $parameter = array( 'chapter_id' => $chapter_id, 'student_id' => $student_id, 'course_id' => $course_id, 'chapter_current_time' => $chapter_current_time ); // show_bug($parameter); // 获取该课程的章节列表信息输出到模板页面 $course_info = A('Student/Video')->getCourseInfo($course_id); // show_bug($course_info); $this->assign('section_chapter', $course_info); $this->assign('parameter', $parameter); $this->assign('video_url', $video_url); $this->display(); } /** * 展示学习资料的模板 */ function studyingData() { echo "学习资料"; } /** * 展示PPT的方法 */ function showPPT() { echo "showPPT"; } /** * 展示章节section,以及该章节下所有小节chapter的信息 * 我这里section表示章,chapter表示节 * 要展示的效果如下: * 第一章 课程介绍 * 1.0映射与函数 * 1.1无穷小与无穷大 * 第二章 xxxxx * 上述使用的是一个.html模板 */ /* * function section_chapter(){ * $section_chapter = getCourseSectionChapterList(2);//高等数学 * $this->assign('section_chapter',$section_chapter); * $this->display(); * } */ /** * 获取该门课程的列表信息并且添加数据库中该课程之前的学习进度记录到其中 * * @param * 符合要求的数组 array $course_name_id */ function getCourseInfo($course_name_id) { $course_info = getCourseSectionChapterList($course_name_id); // show_bug($course_info); /** * 下面用循环将$course_info 里面的url地址统一用url安全编码方法进行编码,同时将课程进度记录要用的参数拼接进去* */ foreach ($course_info as $k => &$v) { // show_bug($v); foreach ($v as $kk => &$vv) { // 执行url编码 // echo $vv['course_chapter_video_url'].'<br>'; $vv['course_chapter_video_url'] = urlsafe_b64encode(ADMIN_IMG_UPLOADS . $vv['course_chapter_video_url']); // echo $vv['course_chapter_video_url']; /** * 课程进度记录相关的代码 */ // 课程进度记录需要四个参数,课程ID,小节ID,用户ID,还有播放进度,将其加入到下面的section_chapter中 // 需要添加的信息有 课程ID 用户ID ,小节ID已经有了, $vv['course_id'] = $course_name_id; $vv['student_id'] = $_SESSION['student_user_id']; $vv['chapter_id'] = $vv['course_chapter_id']; // 换个名字在存储一次 // 该小节课程之前的学习进度 $wheres = 'chapter_progress_student = ' . $_SESSION['student_user_id'] . ' and chapter_progress_course = ' . $course_name_id . ' and chapter_progress_chapter = ' . $vv['course_chapter_id']; // echo $wheres; $chapter_current_time_tmp = M('ChapterProgress')->where($wheres)->find(); // show_bug($chapter_current_time_tmp); // echo $chapter_current_time_tmp['chapter_progress_current_time']; $vv['chapter_current_time'] = (int) $chapter_current_time_tmp['chapter_progress_current_time']; } unset($vv); // 取消引用 } unset($v); // 取消引用 return $course_info; } }<file_sep><?php // 站内搜索功能的控制器 namespace Student\Controller; use Think\Controller; class SearchController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 展示搜索结果的方法 */ function search() { if (! empty($_POST['search'])) { // echo '有提交数据'; // show_bug($_POST); $search = $_POST['search']; $wheres = 'course_name_name LIKE \'%' . $search . '%\' OR course_name_intro LIKE \'%' . $search . '%\' OR course_name_adder LIKE \'%' . $search . '%\''; $info = M('CourseName')->where($wheres)->select(); if (! empty($info)) { // show_bug($info); // 替换上述关键字为其他颜色,以示高亮 foreach ($info as $k => &$v) { // 正则表达式替换关键字为红色 $v['course_name_name'] = preg_replace('/' . $search . '/', '<font color=red>' . $search . '</font>', $v['course_name_name']); $v['course_name_intro'] = preg_replace('/' . $search . '/', '<font color=red>' . $search . '</font>', $v['course_name_intro']); $v['course_name_adder'] = preg_replace('/' . $search . '/', '<font color=red>' . $search . '</font>', $v['course_name_adder']); // echo $v['course_name_name']; } $this->assign('search_num', count($info)); // 搜索结果个数 $this->assign('search_keywords', $search); $this->assign('search', $info); $this->display(); } else { // echo '暂无搜索结果,请更换关键字重新搜索'; $this->error('暂无搜索结果,请更换关键字重新搜索'); } } else { // echo '没有提交数据'; $this->redirect(SITE_URL); } } }<file_sep><?php /** * 发送邮件的方法 * @param 收信人邮箱 $to * @param 发信人名称 $name * @param 邮件主题 $subject * @param 邮件内容 $body * @param string $attachment * @return boolean */ function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null){ $config = C('THINK_EMAIL'); vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件 vendor('SMTP'); $mail = new PHPMailer(); //PHPMailer对象 $mail->CharSet = 'UTF-8'; //设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码 $mail->IsSMTP(); // 设定使用SMTP服务 $mail->SMTPDebug = 0; // SMTP调试功能 // 1 = errors and messages // 2 = messages only // 0 关闭 $mail->SMTPAuth = true; // 启用 SMTP 验证功能 $mail->SMTPSecure = 'ssl'; // 使用安全协议 $mail->Host = $config['SMTP_HOST']; // SMTP 服务器 $mail->Port = $config['SMTP_PORT']; // SMTP服务器的端口号 $mail->Username = $config['SMTP_USER']; // SMTP服务器用户名 $mail->Password = $config['SMTP_PASS']; // SMTP服务器密码 $mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']); $replyEmail = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL']; $replyName = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME']; $mail->AddReplyTo($replyEmail, $replyName); $mail->Subject = $subject; $mail->AltBody = "为了查看该邮件,请切换到支持 HTML 的邮件客户端"; $mail->MsgHTML($body); $mail->AddAddress($to, $name); if(is_array($attachment)){ // 添加附件 foreach ($attachment as $file){ is_file($file) && $mail->AddAttachment($file); } } return $mail->Send() ? true : $mail->ErrorInfo; } /** * TODO 基础分页的相同代码封装,使前台的代码更少 * @param $m 模型,引用传递 * @param $where 查询条件 * @param int $pagesize 每页查询条数 * @return \Think\Page */ function getPage(&$m,$where,$pagesize=10){ $m1=clone $m;//浅复制一个模型 $count = $m->where($where)->count();//连惯操作后会对join等操作进行重置 $m=$m1;//为保持在为定的连惯操作,浅复制一个模型 $p=new Think\Page($count,$pagesize); $p->lastSuffix=false; $p->setConfig('header','<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>'); $p->setConfig('prev','上一页'); $p->setConfig('next','下一页'); $p->setConfig('last','末页'); $p->setConfig('first','首页'); $p->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%'); $p->parameter=I('get.'); $m->limit($p->firstRow,$p->listRows); return $p; } /** * 用以生成符合输出课程章节列表数组的方法,从数据库获取指定数据并生成对应格式返回 * @param 课程章表里面对应的课程名$course_section_course_name字段的值,实际就是课程名course_name里面对应课程的code或者id $course_section_course_name * @param 课程节表里面对应的课程名$course_chapter_course_name字段的值 $course_chapter_course_name * @return Ambigous <multitype:, \Think\mixed, Arrary数组> */ function getCourseSectionChapterList($course_section_course_name /*,$course_chapter_course_name ,$course_chapter_section */){ /**这里section代表章,例如第一章,chapter代表节,例如1-1节*/ $info_chapter = D('CourseChapter');//实例化CourseChapter 好获取数据表hubu_course_chapter中的数据 $info_section = M('CourseSection');//实例化Model $sql_section = "select * from hubu_course_section WHERE course_section_course_name = $course_section_course_name order by course_section_section_num";//选出该课程的所有章信息 $rst_section = $info_section->query($sql_section);//章信息存储在$rst_section里面 //$sql_chapter = "select * from hubu_course_chapter where course_chapter_course_name = $course_chapter_course_name and course_chapter_section = $course_chapter_section";//查询出该课程所有节信息 //$rst_chapter = $info_chapter->query($sql_chapter);//节信息存储在$rst_section里面 /**将上述 $rst_chapter 以及 $rst_section 信息合并成我们所需要的数据格式*/ $res = array();//存储最终结果的数组 foreach ($rst_section as $key => $value){ $res[$value['course_section_name']][] = $value['course_section_name']; //获取新的$rst /* 下面应该用 $course_chapter_course_name 但其实本函数前两个值一样 */ $sql = "select * from hubu_course_chapter where course_chapter_course_name = $course_section_course_name and course_chapter_section = $key+1 order by course_chapter_section,course_chapter_name";//查询出该课程所有章节 $rst = $info_chapter->query($sql); foreach ($rst as $k => $v){ $res[$value['course_section_name']][$k] = $v; } } //print_r($res); //所需要的数组格式如下 /* $test_arr = array( '第一章hahaha'=>array( array( 'course_chapter_name'=>'1.0前言', 'course_chapter_time'=>'2017-01-20 19:25:16'), array( 'course_chapter_name'=>'1.1前言', 'course_chapter_time'=>'2017-01-20 19:25:16'), array( 'course_chapter_name'=>'1.2前言', 'course_chapter_time'=>'2017-01-20 19:25:16') ), '第二章,,,,,'=>array( array( 'course_chapter_name'=>'2.0前言', 'course_chapter_time'=>'2017-01-20 19:25:16'), array( 'course_chapter_name'=>'2.1前言', 'course_chapter_time'=>'2017-01-20 19:25:16'), array( 'course_chapter_name'=>'2.2前言', 'course_chapter_time'=>'2017-01-20 19:25:16' ) ), '第三章nnn'=>array( array( 'course_chapter_name'=>'3.0前言', 'course_chapter_time'=>'2017-01-20 19:25:16'), array( 'course_chapter_name'=>'3.1前言', 'course_chapter_time'=>'2017-01-20 19:25:16'), array( 'course_chapter_name'=>'3.2前言', 'course_chapter_time'=>'2017-01-20 19:25:16' ) ) ); */ return $res; } /** * URL安全编码函数 * @param 需要转换的URL路径 $string * @return mixed */ function urlsafe_b64encode($string) { $data = base64_encode($string); $data = str_replace(array('+','/','='),array('-','_',''),$data); return $data; } /** * URL安全解码函数 * @param 编码后的URL地址 $string * @return string */ function urlsafe_b64decode($string) { $data = str_replace(array('-','_'),array('+','/'),$string); $mod4 = strlen($data) % 4; if ($mod4) { $data .= substr('====', $mod4); } return base64_decode($data); } <file_sep># hubuedu项目说明 ## 访问地址: ###管理员 web.hubu.edu:3002/index.php/Admin/控制器名/方法名 ###学生 web.hubu.edu:3002/index.php/Student/控制器名/方法名 ###老师 web.hubu.edu:3002/index.php/Teacher/控制器名/方法名 <file_sep><?php // 接口URL地址:http://172.16.58.3:3002/Hubu/Interface/Android/course_introduce.php?format=json&course_id=1&student_id=9 /** * 向客户端提供指定课程的介绍信息 * 客户端需要通过GET方式提交一个字符串信息用以制定要获取的是哪个课程 * 同时客户端提交一个字符串,用户的ID信息,用以表明是哪位用户 */ require_once 'response.php'; // 引入公共文件 require_once 'db.php'; // 数据库连接文件 require_once 'common.php'; // 引入公共文件 // 接收异常,数据库连接失败 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } // 获取用户通过GET提交的课程ID $course_id = isset($_GET['course_id']) ? $_GET['course_id'] : 0; // 如果没有给出course_id则默认为0 $student_id = isset($_GET['student_id']) ? $_GET['student_id'] : 0; // 如果没有给出student_id则默认为0 // echo $course_id; // 当$course_id为数字且不为零 if (is_numeric($course_id) && $course_id > 0) { // 当$student_id为数字且不为零 if (is_numeric($student_id) && $student_id > 0) { // 课程ID与学生ID都指定正确,输出课程信息以及该学生的该课程的学习进度等信息 $sql2 = 'select * from hubu_course_name where course_name_id = ' . $course_id; // 查询出课程的信息的SQL语句 $result2 = mysql_query($sql2, $connect); // 结果集2 $course_tmp2 = array(); // 存储课程介绍信息 // 循环取出结果集中的数据 while ($tmp2 = mysql_fetch_assoc($result2)) { // var_dump($course_class); $course_tmp2[] = $tmp2; } // var_dump($course_tmp2); foreach ($course_tmp2 as $k => &$v) { $v['course_name_pic'] = ADMIN_IMG_UPLOADS . $v['course_name_pic']; } $course_introduce = array(); $course_introduce['course_introduce'] = $course_tmp2; // 学生的学习进度等信息,首先判断用户是否登录,如果已经登录,再判断用户是否选了这门课 // 不判断登录,由于提供了用户ID,所以直接查询是否选了这门课 $sql3 = 'select * from hubu_choose_course where choose_course_choosed = ' . $course_id . ' and choose_course_student = ' . $student_id; // echo $sql3; $result3 = mysql_query($sql3, $connect); // 结果集3 if (mysql_num_rows($result3) > 0) { // 用户选了这门课程 // echo mysql_num_rows($result3); $sql4 = 'select * from hubu_chapter_progress where chapter_progress_student = ' . $student_id . ' and chapter_progress_course = ' . $course_id; // echo $sql4; $result4 = mysql_query($sql4, $connect); // 结果集4 $chapter_progress_tmp = array(); // 存储章节进度信息临时数组 $chapter_progress = array(); // 存储章节进度信息最终数组 // 循环取出结果集中的数据 while ($tmp4 = mysql_fetch_assoc($result4)) { $chapter_progress_tmp[] = $tmp4; } // var_dump($chapter_progress_tmp); // 数组调整为 chapter_id => 进度记录 这种形式 /* * foreach ($chapter_progress_tmp as $k => $v){ * $chapter_progress[$v['chapter_progress_chapter']] = $v['chapter_progress_state']; * } */ /** * 查询并计算该课程总得学习进度 */ $sql5 = 'select sum(chapter_progress_state) from hubu_chapter_progress where chapter_progress_student = ' . $student_id . ' and chapter_progress_course = ' . $course_id; $result5 = mysql_query($sql5, $connect); // 结果集5 while ($tmp5 = mysql_fetch_assoc($result5)) { $course_progresss_tmp = $tmp5; // var_dump($course_progresss_tmp); } // echo $course_progresss_tmp['sum(chapter_progress_state)'];//学习进度求和 // 课程总的小节数 $sql6 = 'select * from hubu_course_chapter where course_chapter_course_name = ' . $course_id; $result6 = mysql_query($sql6, $connect); // 结果集6 $chapter_count = mysql_num_rows($result6); // 课程小节数 // echo $chapter_count; if ($chapter_count) { $course_progresss = round($course_progresss_tmp['sum(chapter_progress_state)'] / ($chapter_count * 100), 3) * 100; // 算平均评分,四舍五入一位小数,再换算成百分数形式 } else { // 没有小节,则进度为0 $course_progresss = 0; } // var_dump($course_progresss); // echo $course_progresss; } // var_dump($chapter_progress); $course_introduce['chapter_progress'] = $chapter_progress_tmp; $course_introduce['course_progress'] = $course_progresss; return Response::show(424, '课程介绍信息获取成功,学生该课程学习进度获取成功', $course_introduce); exit(); } elseif (is_numeric($student_id) && $student_id == 0) { // 课程ID指定,学生ID未指定,只输出课程的信息 $sql1 = 'select * from hubu_course_name where course_name_id = ' . $course_id; // 查询出课程的信息的SQL语句 $result1 = mysql_query($sql1, $connect); // 结果集1 $course_tmp1 = array(); // 存储课程介绍信息 // 循环取出结果集中的数据 while ($tmp1 = mysql_fetch_assoc($result1)) { // var_dump($course_class); $course_tmp1[] = $tmp1; } // var_dump($course_tmp); foreach ($course_tmp1 as $k => &$v) { $v['course_name_pic'] = ADMIN_IMG_UPLOADS . $v['course_name_pic']; } $course_introduce = array(); $course_introduce['course_introduce'] = $course_tmp1; // $course_introduce['my_study_progress'] = array(); return Response::show(423, '课程介绍信息获取成功,未提供学生ID因而不反馈学生的学习进度等信息', $course_introduce); exit(); } elseif (! is_numeric($student_id)) { return Response::show(422, '客户端指定的学生用户的ID信息不合法,不是int类型'); exit(); } } else { // $course_id 字符不合法或者为0 return Response::show(410, '客户端指定的课程的ID信息不合法或者未指定'); exit(); } //判断数据是否存在,存在就返回,不存在就返回不存在状态码 /* if ($course_introduce){ return Response::show(411,'课程章节列表细心获取成功',$course_introduce); }else { return Response::show(412,'课程章节列表细心获取失败',$course_introduce); } */<file_sep><?php // 空控制器,用以处理空控制器,以及空操作 namespace Student\Controller; use Think\Controller; class EmptyController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } }<file_sep><?php //用户反馈的Model namespace Model; use Think\Model; //父类是Model class FeedbackModel extends Model{ }<file_sep><?php // 接口URL地址:http://172.16.58.3:3002/Hubu/Interface/Android/course_name_list.php?format=json&course_class_code=2 /** * 向客户端提供某一特定类别下面所有课程的信息 * 客户端需要通过GET方式提交一个字符串信息用以制定要获取的是哪个大类的课程 */ require_once 'response.php'; // 引入公共文件 require_once 'db.php'; // 数据库连接文件 require_once 'common.php'; // 引入公共文件 // 接收异常,数据库连接失败 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } // 获取用户通过GET提交的课程类别标志码 $course_class_code = isset($_GET['course_class_code']) ? $_GET['course_class_code'] : 0; // 如果没有给出course_class_code则默认为0 // echo $course_class_code; // 当$course_class_code为20的时候,选取出所有的课程 if ($course_class_code == 20) { $sql = 'select * from hubu_course_name'; } elseif ($course_class_code >= 1 && $course_class_code <= 13) { $sql = 'select * from hubu_course_name where course_name_class = ' . $course_class_code; } else { // $course_class_code 字符不合法或者为0 return Response::show(407, '客户端未指定所要获取的课程大类信息或者指定的变量不合法'); exit(); } $course_name_list_tmp = array(); // 用以存储某一大类课程名称信息的临时数组 $course_name_list = array(); // 用以存储某一大类课程名称信息的数组 $result = mysql_query($sql, $connect); // 结果集 // 循环取出结果集中的数据 while ($course_name = mysql_fetch_assoc($result)) { // var_dump($course_name); $course_name_list_tmp[] = $course_name; } // var_dump($course_name_list_tmp); // 用foreach来遍历数据,将数据转换为所需的格式 foreach ($course_name_list_tmp as $k => $v) { $course_name_list[$k]['course_id'] = $v['course_name_id']; $course_name_list[$k]['name'] = $v['course_name_name']; $course_name_list[$k]['image'] = ADMIN_IMG_UPLOADS . $v['course_name_pic']; $course_name_list[$k]['description'] = $v['course_name_intro']; $course_name_list[$k]['teacher'] = $v['course_name_adder']; $course_name_list[$k]['choose_count'] = getChoosedCount($v['course_name_id']); // common里面获取选课人数的方法 $course_name_list[$k]['class'] = getChapterCount($v['course_name_id']); // common里面获取小节总数的方法 } // var_dump($course_name_list); // 判断数据是否存在,存在就返回,不存在就返回不存在状态码 if ($course_name_list) { return Response::show(405, '课程名称数据获取成功', $course_name_list); } else { return Response::show(406, '课程名称数据获取失败', $course_name_list); }<file_sep><?php // 课程章节页面的控制器 namespace Student\Controller; use Think\Controller; class CourseChapterController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 用户点击课程后,例如点击“高等数学”,跳转到高等数学这门课程所有的章节列表页面 */ function index($course_name_id) { // echo $course_name_id; header("Content-Type:text/html; charset=utf-8"); // 首页不乱码 // 这里传进来的$course_name_id是课程的ID值 // 根据上述ID查询出该课程的名称等信息 $info = D('CourseName'); // show_bug($info); $course_info = $info->where("course_name_id = $course_name_id")->find(); // show_bug($course_info); /** * 通过session值查询数据库中的信息,判断用户是否选了这门课程* */ // echo session('student_user_id'); if (isset($_SESSION['student_user_id'])) { // 用户已经登陆,查询数据表hubu_choose_course看用户有没有选择这门课 $user_id = session('student_user_id'); $check = M('ChooseCourse')->where("choose_course_choosed = $course_name_id and choose_course_student = $user_id")->find(); // show_bug($check); if ($check) { // echo "真"; /** * 查询出该生该课程的总得学习进度 学习总进度 = 小节进度和/小节数 */ $wheres = 'chapter_progress_student = ' . $user_id . ' and chapter_progress_course = ' . $course_name_id; $progress_tmp = M('ChapterProgress')->where($wheres)->sum('chapter_progress_state'); $this->assign('check', true); } else { // echo "假"; $this->assign('check', false); } } /** * 查询出课程学习人数,课程节数,总时长等信息,输出到模板* */ $choosed_count = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 // show_bug($choosed_count); $chapter_count = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->count(); // 统计这门课程总节数 // show_bug($chapter_count); $sql = "SELECT SUM(choose_course_score) FROM hubu_choose_course WHERE choose_course_choosed = $course_name_id"; // 查询出分数求和值 $course_score = M('ChooseCourse')->query($sql); // 查询出来的结果是个二维数组 // show_bug($course_score[0]['sum(choose_course_score)']); $choosed_marked_count = M('ChooseCourse')->where("choose_course_choosed = $course_name_id and choose_course_score > 0")->count(); // 已选这门课程且已评分的总人数 $course_score = round($course_score[0]['sum(choose_course_score)'] / $choosed_marked_count, 1); // 算平均评分,四舍五入一位小数 // show_bug($course_score); /** * 计算出该生该课程的总学习进度 学习总进度 = 小节进度和/小节数 */ $course_progress = round($progress_tmp / ($chapter_count * 100), 3) * 100; // 算平均评分,四舍五入一位小数,再换算成百分数形式 // echo $course_progress; $this->assign('course_progress', $course_progress); $this->assign('course_score', $course_score); $this->assign('choosed_count', $choosed_count); $this->assign('chapter_count', $chapter_count); $this->assign('course_info', $course_info); // 将信息输出到模板 $this->display('index'); } /** * 将该课程添加到已选课程 * * @param 课程的ID信息 $course_name_id */ function chooseCourse($course_name_id = 0) { if ($course_name_id) { if (isset($_SESSION['student_user_id'])) { $data = array( 'choose_course_student' => session('student_user_id'), 'choose_course_choosed' => $course_name_id ); // show_bug($data); $rst = M('ChooseCourse')->add($data); if ($rst) { $this->success('课程添加成功!'); } else { $this->error('课程添加失败!'); } } else { $this->error('请先登陆!', SITE_URL); } } else { $this->error('出现未知错误,请联系管理员!', SITE_URL); } } /** * 展示章节section,以及该章节下所有小节chapter的信息 * 我这里section表示章,chapter表示节 * 要展示的效果如下: * 第一章 课程介绍 * 1.0映射与函数 * 1.1无穷小与无穷大 * 第二章 xxxxx * 上述使用的是一个.html模板 */ /** * 查询出这门课的简介,课程名等等信息$course_section_course_name ,$course_chapter_course_name * * @param 传入的是课程的ID $course_name_id */ function section_chapter($course_name_id = 0) { // $$course_name_id指的是课程的ID信息 if ($course_name_id > 0) { // echo $course_name_id; $section_chapter = getCourseSectionChapterList($course_name_id); // 高等数学1,1 信号系统2,2 // show_bug($section_chapter);//查看从数据库中查询出来的信息是否正确 // 查询出用户的本课程的学习进度,首先用户要已选课,其次用户要处于登陆状态 if (isset($_SESSION['student_user_id'])) { // 用户已经登录 // 查询用户是否已经选了这门课 $rst = M('ChooseCourse')->where('choose_course_choosed = ' . $course_name_id . ' and choose_course_student = ' . session('student_user_id'))->select(); if (! empty($rst)) { // 用户选了这门课 $chapter_progress = A('Student/ChapterProgress')->getChapterProgress($course_name_id, session('student_user_id')); // show_bug($chapter_progress); foreach ($section_chapter as $k => &$v) { // echo $k; foreach ($v as $kk => &$vv) { // show_bug($vv); $vv['course_chapter_progress'] = (int) $chapter_progress[$vv['course_chapter_id']]; // 将学习进度记录拼装到数组中 } } } } // show_bug($section_chapter); $this->assign('section_chapter', $section_chapter); $this->display(); } else { echo "数据查询不成功,联系管理员处理"; } } function test() { show_bug(getCourseSectionChapterList(2, 2)); } /** * 展示这个页面的评论板块 * 用iframe嵌入 */ function comment() { $this->display(); } /** * 展示这个页面的笔记板块 * 同上,用iframe嵌入 */ function note() { $this->display(); } }<file_sep><?php //课程名称的Model,存储所有课程的名称以及基本信息 namespace Model; use Think\Model; //父类是Model class CourseNameModel extends Model{ }<file_sep><?php // 后台管理首页的控制器 namespace Student\Controller; use Think\Controller; class FeedbackController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * * * 处理用户反馈表单的方法 */ function feedback() { // echo "feedback"; // show_bug(empty($_POST)); // 判断用户是否提交了表单 if (! empty($_POST)) { // 用户提交了表单 // echo "有表单数据"; // 收集表单数据 // show_bug($_POST); // 把时间添加到$_POST里面 $_POST['feedback_time'] = date("Y-m-d H:i:s"); $info = D('Feedback'); $z = $info->create(); // show_bug(count($z)); $a = $info->add(); // 将表单数据存储到数据库 // show_bug($a);//这里$a是插入后那一行数据的ID号 // 下面的这个判断并没有多大用,留给前端去实现表单验证吧 if ($a) { // 数据提交存储成功,链接跳转 $this->success('我们已收到您的反馈,会及时处理!'); } else { // 数据存储失败 $this->error('反馈提交失败,请重新提交!'); } } else { // 用户没有提交表单,直接展示模版 // echo "无表单数据"; // 如果用户登录了,就把用户的个人信息直接输出到前台 if (isset($_SESSION['student_user_id'])){ $userInfo = D('StudentUser')->where('student_user_id = '.$_SESSION['student_user_id'])->find(); $this->assign('userInfo',$userInfo); } $this->display(); } } }<file_sep><?php // 接口URL地址:http://192.168.3.11:3002/Hubu/Interface/Android/course_info.php?format=json&course_id=2 /** * 向客户端提供指定课程的章节信息 * 客户端需要通过GET方式提交一个字符串信息用以制定要获取的是哪个课程 */ require_once 'response.php'; // 引入公共文件 require_once 'db.php'; // 数据库连接文件 require_once 'common.php'; // 引入公共文件 // 接收异常,数据库连接失败 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } // 获取用户通过GET提交的课程ID $course_id = isset($_GET['course_id']) ? $_GET['course_id'] : 0; // 如果没有给出course_id则默认为0 // echo $course_id; // 当$course_id为数字且不为零 if (is_numeric($course_id) && $course_id > 0) { $course_info = getCourseSectionChapterList($course_id); } else { // $course_id 字符不合法或者为0 return Response::show(410, '客户端指定的课程的ID信息不合法或者未指定'); exit(); } // 判断数据是否存在,存在就返回,不存在就返回不存在状态码 if ($course_info) { return Response::show(411, '课程章节列表细心获取成功', $course_info); } else { return Response::show(412, '课程章节列表细心获取失败', $course_info); }<file_sep><?php //config.php是我们当前自己项目的配置文件,我们可以通过修改该文件达到配置变量的目录 //这个文件在系统运行过程中会覆盖convertion.php的配置变量 return array( );<file_sep><?php //网站首页轮播图的Model namespace Model; use Think\Model; //父类是Model class ImgTurnModel extends Model{ }<file_sep><?php // 后台管理首页的控制器 namespace Admin\Controller; use Think\Controller; class AdminIndexController extends Controller { /** * 用以展示后台管理首页的模板 */ function index() { // 用session判断当前是否有用户登录,如果没有登录则不允许访问index,这种判断方式有待调整 // 且跳转到login页面 if (! session()) { // 如果session为空跳转到login $this->redirect('AdminUser/login'); } else { // 下面是用来输出所有常量的语句 // var_dump(get_defined_constants(true)); // 调用视图display(),直接展示index.html模板,display()没有参数那么调用的模板名称就与当前方法名一致 $this->display(); } } /** * 展示管理员基本信息的模板 */ function userinfo() { $this->display(); } }<file_sep><?php //config.php是我们当前自己项目的配置文件,我们可以通过修改该文件达到配置变量的目录 //这个文件在系统运行过程中会覆盖convertion.php的配置变量 //此文件配置的信息三个模块都生效 return array( 'DEFAULT_MODULE' => 'Student', // 默认模块 'MULTI_MODULE' => true, // 是否允许多模块 如果为false 则必须设置 DEFAULT_MODULE //以下是发送邮件相关的配置文件 'THINK_EMAIL' => array( 'SMTP_HOST' => 'smtp.163.com', //SMTP服务器 'SMTP_PORT' => '465', //SMTP服务器端口 'SMTP_USER' => '<EMAIL>', //SMTP服务器用户名 'SMTP_PASS' => '<PASSWORD>', //SMTP服务器密码,此处填写的是授权码,可以代替密码 'FROM_EMAIL' => '<EMAIL>', 'FROM_NAME' => '湖大在线学习平台', //发件人名称 'REPLY_EMAIL' => '', //回复EMAIL(留空则为发件人EMAIL) 'REPLY_NAME' => '', //回复名称(留空则为发件人名称) 'SESSION_EXPIRE'=>'72', ), //'配置项'=>'配置值' 'URL_MODEL' => 1, // URL访问模式,可选参数0、1、2、3,代表以下四种模式: 0 (普通模式); 1 (PATHINFO 模式); 2 (REWRITE 模式); 3 (兼容模式) 默认为PATHINFO 模式 //让页面显示追踪日志信息 'SHOW_PAGE_TRACE' => true, // 显示页面Trace信息 //URL大小写敏感设置,PHP本身不敏感,但是TP为了安全做了敏感设置 'URL_CASE_INSENSITIVE' => false, // 默认false 表示URL区分大小写 true则表示不区分大小写 /* 数据库连接相关的配置 */ 'DB_TYPE' => 'mysql', // 数据库类型 'DB_HOST' => '172.16.17.32', // 服务器地址 'DB_NAME' => 'hubuedu_data', // 数据库名 'DB_USER' => 'root', // 用户名 'DB_PWD' => '', // 密码 'DB_PORT' => '3306', // 端口 /* 默认3306 */ 'DB_PREFIX' => 'hubu_', // 数据库表前缀 'DB_FIELDTYPE_CHECK' => false, // 是否进行字段类型检查 //以下字段缓存,在DEBUG模式是不起作用的,设置为false也不起作用 'DB_FIELDS_CACHE' => true, // 启用字段缓存 'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8 );<file_sep><?php //ThinkPHP框架入口 //设置head头,防止乱码 header("Content-type:text/html,charset=utf-8"); /** * 功能:制作一个输出调试函数,便于开发的时候使用 * @param 需要输出的对象或者其他信息 $msg */ function show_bug($msg){ echo "<pre style = 'color:blue'"; var_dump($msg); echo "</pre>"; } //把当前的模式设置为debug模式,项目上线后需改为生产模式 define(“APP_DEBUG”,false); define("APP_DEBUG", true); //自己定义的CSS JS IMG路径全局常量,用以存储网页相关的资源文件的路径 //定义路径常量,直接定义http绝对路径,框架在应用的时候会自动将SITE_URL 与 CSS等资源路径进行组合得到一个统一资源定位符 define("SITE_URL", "http://web.hubu.edu:3002/");//站点路径 define("ADMIN_ROOT_URL", SITE_URL."Hubu/Public/");//资源根路径 define("ADMIN_CSS_URL", SITE_URL."Hubu/Public/css/");//css路径 define("ADMIN_JS_URL", SITE_URL."Hubu/Public/js/");//js路径 define("ADMIN_IMG_URL", SITE_URL."Hubu/Public/images/");//images图片路径 define("ADMIN_IE_URL", SITE_URL."Hubu/Public/ie/");//适配ie9以下浏览器的js文件 //为上传用户头像路径设置路径 define("ADMIN_IMG_UPLOADS", SITE_URL."Hubu/Public/"); //定义用户头像默认存储位置 define("ADMIN_DEFAULT_IMG", "Uploads/default/default_admin_user.jpg"); //1.定义我们的项目名称 define("APP_NAME","hubu"); //2.定义当前项目的路径 define("APP_PATH","./Hubu/"); //3.引入框架的核心程序 include "./ThinkPHP/ThinkPHP.php"; <file_sep><?php // 接口URL地址:http://172.16.58.3:3002/Hubu/Interface/Android/student_login.php?format=json /** * 学生用户登录的接口,验证用户密码是否正确,生成session,向客户端回传用户的个人信息 */ require_once 'response.php'; // 引入公共文件 require_once 'db.php'; // 数据库连接文件 require_once 'common.php'; // $_POST['userinfo'] = '{"username":"<EMAIL>","password":"<PASSWORD>"}'; if (! empty($_POST)) { // 接收异常,数据库连接失败 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } // 接收POST数据 $str = $_POST['userinfo']; // 判断是否为JSON格式 if (is_null(json_decode($str))) { return Response::show(421, '学生用户登录API使用错误,post上传的数据不是标准的JSON格式'); exit(); } $userinfo_obj = json_decode($str, true); // 解析JSON数据 if (empty($userinfo_obj['username'])) { // echo 'username不存在'; return Response::show(419, '学生用户登录API使用错误,里面不含有 username 字段'); exit(); } elseif (empty($userinfo_obj['password'])) { return Response::show(420, '学生用户登录API使用错误,里面不含有 password 字段'); exit(); } $username = $userinfo_obj['username']; $password = $userinfo_obj['password']; // 验证账户密码是否正确 $sql = 'select * from hubu_student_user where student_user_email = ' . '\'' . $username . '\''; // 不能漏掉了引号 // echo $sql; $result = mysql_query($sql, $connect); // 查询出的结果集 // var_dump($result); $userinfo = array(); while ($tmp = mysql_fetch_assoc($result)) { $userinfo[] = $tmp; } if (empty($userinfo)) { return Response::show(414, '用户名不存在'); exit(); } else { // 判断账号是否处于激活状态 if ($userinfo[0]['student_user_verify'] == '1') { // 用户账户已经激活,验证密码是否正确 if ($password == $userinfo[0]['student_user_pwd']) { // 密码正确,生成session,回传用户信息,回传用户已选的课程 // var_dump($userinfo); $i = array(); // 存储用户个人信息的数组 hubu_student_user里面的数据 foreach ($userinfo as $k => $v) { $i['student_id'] = $v['student_user_id']; $i['email'] = $v['student_user_email']; $i['username'] = $v['student_user_username']; $i['sex'] = $v['student_user_sex']; $i['tel'] = $v['student_user_tel']; $i['qq'] = $v['student_user_qq']; $i['addr'] = $v['student_user_addr']; $i['pic'] = ADMIN_IMG_UPLOADS . $v['student_user_pic']; $i['intro'] = $v['student_user_intro']; $i['verify'] = $v['student_user_verify']; // 生成session $_SESSION['student_user_email'] = $v['student_user_email']; $_SESSION['student_user_id'] = $v['student_user_id']; } // var_dump($i); $sql_mycourse = 'select * from hubu_choose_course where choose_course_student = ' . $userinfo[0]['student_user_id']; // 已选课程 $result_mycourse = mysql_query($sql_mycourse, $connect); $mycourse = array(); while ($mycourse_tmp = mysql_fetch_assoc($result_mycourse)) { $mycourse[] = $mycourse_tmp['choose_course_choosed']; // 获取已选课程的ID信息 // $mycourse[] = $mycourse_tmp; } // var_dump($mycourse); if (empty($mycourse)) { // 用户一门课也没有选 $arr = array( 'userinfo' => $i, 'mycourse' => '' ); return Response::show(417, '登陆成功,用户没有已选的课程', $arr); exit(); } else { // 用户有已选的课程 $arr = array( 'userinfo' => $i, 'mycourse' => $mycourse ); return Response::show(418, '登陆成功,学生用户个人信息以及已选课程的ID信息获取成功', $arr); exit(); } } else { // 密码输入错误 return Response::show(416, '密码输入不正确'); } } else { // 账户未激活 return Response::show(415, '账户处于未激活状态'); } } } else { // 提交的是空表单 return Response::show(413, '提交的表单为空'); } <file_sep><?php // 课程的控制器,展示课程信息的模板 namespace Student\Controller; use Think\Controller; class CourseController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * "课程"选项的网页模板展示,与IndexController同等级别 */ function index() { // echo "这是课程展示页面"; // 将课程类别信息用模板输入到页面,调用CourseClass里面的方法,这输入跨控制器调用,使用A方法 // $course_class = A('CourseClass'); // show_bug($course_class); // $course_class->getCourseClass();//调用CourseClass控制器里面的getCourseClass()方法 // 将所有课程名称信息输出到模板,方法同上所示 // $course_name = A('CourseName'); // show_bug($course_name); // $course_name->getCourseName(); $this->display(); } }<file_sep><?php /** * 此文件用以存储所需的例如常量,公共函数等的代码 */ // 自己定义的CSS JS IMG路径全局常量,用以存储网页相关的资源文件的路径 // 定义路径常量,直接定义http绝对路径,框架在应用的时候会自动将SITE_URL 与 CSS等资源路径进行组合得到一个统一资源定位符 define("SITE_URL", "http://172.16.31.10:3002/"); // 站点路径 define("ADMIN_ROOT_URL", SITE_URL . "Hubu/Public/"); // 资源根路径 // define("ADMIN_CSS_URL", SITE_URL."Hubu/Public/css/");//css路径 // define("ADMIN_JS_URL", SITE_URL."Hubu/Public/js/");//js路径 // define("ADMIN_IMG_URL", SITE_URL."Hubu/Public/images/");//images图片路径 // define("ADMIN_IE_URL", SITE_URL."Hubu/Public/ie/");//适配ie9以下浏览器的js文件 // 为上传用户头像路径设置路径 define("ADMIN_IMG_UPLOADS", SITE_URL . "Hubu/Public/"); // 定义用户头像默认存储位置 // define("ADMIN_DEFAULT_IMG", "Uploads/default/default_admin_user.jpg"); /** * 获取一门课程的选课人数 * * @param number $course_name_id * @return string|number */ function getChoosedCount($course_name_id = 0) { if ($course_name_id) { // 接收异常,数据库连接失败 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } // 从数据库中查询出这门课程的选课人数 $sql = 'select * from hubu_choose_course where choose_course_choosed = ' . $course_name_id; $result = mysql_query($sql, $connect); // 结果集 return mysql_num_rows($result); } else { return 0; } } /** * 获取一门课程的小节总数 * * @param number $course_name_id * @return string|number */ function getChapterCount($course_name_id = 0) { if ($course_name_id) { // 查询数据库 // 接收异常,数据库连接失败 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } // 从数据库中查询出这门课程的小节总数 $sql = 'select * from hubu_course_chapter where course_chapter_course_name = ' . $course_name_id; $result = mysql_query($sql, $connect); // 结果集 return mysql_num_rows($result); } else { return 0; } } /** * 根据hot_course数据表里面的ID信息查询出该课程的所有信息 * * @param number $course_id */ function getHotCourse($course_id = 0) { if ($course_id) { // 连接数据库 // 接收异常,数据库连接失败 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } $hot_course_list_tmp = array(); // 存储热门课程的临时数组 $sql = 'select * from hubu_course_name where course_name_id = ' . $course_id; $result = mysql_query($sql, $connect); // 查询出结果集 // 循环取出结果集中的数据 while ($course_name = mysql_fetch_assoc($result)) { // var_dump($course_name); $hot_course_list_tmp[] = $course_name; } // var_dump($hot_course_list_tmp); if ($hot_course_list_tmp) { return $hot_course_list_tmp['0']; // 只返回一维数组 } else { return 0; } } else { return 0; } } /** * 获取一门课程的章节信息 * * @param 课程的ID信息 $course_id */ function getCourseSectionChapterList($course_id) { if (is_numeric($course_id) && $course_id > 0) { // 查询数据库 try { $connect = Db::getInstance()->connect(); // mysql连接资源 } catch (Exception $e) { // $e->getMessage();//获取错误信息,调试模式使用 return Response::show(403, '数据库链接失败'); } $sql_section = 'select * from hubu_course_section WHERE course_section_course_name = ' . $course_id . ' order by course_section_section_num'; // 查询章信息的SQL语句 // echo $sql_section; $result_section = mysql_query($sql_section, $connect); // 查询出章的结果集 $section = array(); // 存储章信息的临时数组 $chapter = array(); // 存储节信息的临时数组 $section_chapter = array(); // 存储章节信息的临时数组 // 循环取出章结果集中的数据 while ($tmp = mysql_fetch_assoc($result_section)) { // var_dump($tmp); $section[] = $tmp['course_section_name']; // $section是一维数组,专门存储章信息 } // var_dump($section);//exit(); foreach ($section as $k => $v) { /** * 下面查询出节的信息并与章信息对号入座 */ $sql_chapter = 'select * from hubu_course_chapter where course_chapter_course_name = ' . $course_id . " and course_chapter_section = $k+1 order by course_chapter_section,course_chapter_name"; $result_chapter = mysql_query($sql_chapter, $connect); // 查询出节的结果集 // var_dump($result_chapter); // 循环取出节结果集中的数据 while ($tmp2 = mysql_fetch_assoc($result_chapter)) { // var_dump($tmp2); $chapter[] = $tmp2; } $section_chapter[$k]['chapter_name'] = $v; // 章信息 // var_dump($chapter); // exit(); // 下面代码为更改$chapter里面的字段名称 $chapter_tmp = array(); foreach ($chapter as $kk => $vv) { $chapter_tmp[$kk]['section_id'] = $vv['course_chapter_id']; $chapter_tmp[$kk]['name'] = $vv['course_chapter_name']; $chapter_tmp[$kk]['video_url'] = ADMIN_IMG_UPLOADS . $vv['course_chapter_video_url']; $chapter_tmp[$kk]['ppt_url'] = ADMIN_IMG_UPLOADS . $vv['course_chapter_ppt_url']; } $section_chapter[$k]['section'] = $chapter_tmp; // 节信息 $chapter = array(); // 清空数组,每将一整章所有小节的信息赋值完就必须清空一次 $chapter_tmp = array(); } // var_dump($section_chapter); return $section_chapter; } else { return 0; } } <file_sep><?php //User数据模型Model,数据库中的每个数据表都对应一个model模型文件 namespace Model; use Think\Model; //父类是Model class AdminUserModel extends Model{ //可以自定义数据表的相关属性,例如数据表前缀,名称等等,进行个性化的设置 /** * 功能:验证用户名以及密码 供AdminUser控制器使用 * @param 登陆表单中用户输入的用户名 $name * @param 登陆表单中用户输入的密码 $pwd * @return boolean|unknown */ function checkNamePwd($name,$pwd){ //根据$name查询数据库里面是否有这一条记录 //可以根据指定字段进行查询getByXXX($name),XXX是字段名,Model父类封装好的方法,执行结果一位数组,PHP本身不区分大小写,采用驼峰法命名 //此处驼峰法命名与数据库之间有一个下划线_的关系,AdminUser对应数据表名字hubu_admin_user,hubu_为数据表前缀 $info = $this-> getByAdminuser_email($name); //show_bug($info);//$info是一个以为数组才是正确,为空说明表单用户名输入错误 //$info不为空,继续验证密码 if($info != null){ //验证密码,查询出来儿密码对比用户输入的密码 if($info['adminuser_pwd'] != $pwd){ return false;//返回false } else { //密码输入正确 return $info;//返回$info,回头生成session信息 } } else { //密码错误 return false;//返回false } } }<file_sep><?php // 后台管理首页的控制器 namespace Admin\Controller; use Think\Controller; class RecommendedController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 管理员对后台精品课程进行查看修改的的方法 */ function updateRecommendedCourse(){ echo '这是updateRecommendedCourse'; $courseList = M('Recommended')->order('recommended_class')->select();//按照类别ID从小到大排序查询 //show_bug($courseList); } }<file_sep><?php namespace Model; use Think\Model; //父类是Model class TestModel extends Model{ //可以自定义数据表的相关属性,例如数据表前缀,名称等等,进行个性化的设置 }<file_sep><?php // 用户学习进度业务逻辑处理的控制器 namespace Student\Controller; use Think\Controller; class ChapterProgressController extends Controller { function test() { $info = D('ChapterProgress')->select(); show_bug($info); } // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 获取用户某一课程所有小节的学习进度 * * @param 课程ID $course_id * @param 学生用户ID $student_id * @return array */ function getChapterProgress($course_id, $student_id) { $progress = D('ChapterProgress')->where('chapter_progress_student = ' . $student_id . ' and chapter_progress_course = ' . $course_id)->select(); // show_bug($progress); $progress_chapter = array(); foreach ($progress as $k => $v) { $progress_chapter[$v['chapter_progress_chapter']] = $v['chapter_progress_state']; } // show_bug($progress_chapter); return $progress_chapter; } /** * 接收前台Ajax传来的用户视频播放进度数据 * 并将数据存储到数据库中 */ function receiveChapterProgress() { // if (IS_POST){ $student_id = $_POST['student_id']; $course_id = $_POST['course_id']; $chapter_id = $_POST['chapter_id']; $chapter_progress = $_POST['chapter_progress']; $chapter_nowprogress = round($_POST['chapter_nowprogress'], 2); // 四舍五入保留两位小时 $wheres = 'chapter_progress_student = ' . $student_id . ' and chapter_progress_course = ' . $course_id . ' and chapter_progress_chapter = ' . $chapter_id; $info = M('ChapterProgress')->where($wheres)->find(); // show_bug($info); if (! empty($info)) { // 原来数据库中有这条记录,则更新这条记录即可 if ($info['chapter_progress_state'] < 100) { // echo '小于100'; $chapter_progress1 = $chapter_progress + $info['chapter_progress_state']; // 百分比累加 if ($chapter_progress1 >= 100) { $chapter_progress1 = 100; $chapter_nowprogress = 0; // 时间归零 } else { // 不进行操作 } $arr = array( 'chapter_progress_state' => $chapter_progress1, 'chapter_progress_current_time' => $chapter_nowprogress ); // 更新数据库 // show_bug($arr); $rst = M('ChapterProgress')->where('chapter_progress_id = ' . $info['chapter_progress_id'])->save($arr); // show_bug($rst); if ($rst) { $this->ajaxReturn(json_encode('data-save-success' . $chapter_progress . 'A' . $chapter_nowprogress)); } else { $this->ajaxReturn(json_encode('data-save-fail' . $chapter_progress)); } } elseif ($info['chapter_progress_state'] >= 100) { // 什么也不做,不操作数据库 $this->ajaxReturn(json_encode('data-is-100%' . $chapter_progress)); } } else { // 原来数据库中没有这条数据,插入一条新的记录 $arr = array( 'chapter_progress_state' => $chapter_progress, 'chapter_progress_student' => $student_id, 'chapter_progress_course' => $course_id, 'chapter_progress_chapter' => $chapter_id, 'chapter_progress_current_time' => $chapter_nowprogress, 'chapter_progress_time' => date('y-m-d h:i:s', time()) ); $rst = M('ChapterProgress')->add($arr); // show_bug($rst); if ($rst) { $this->ajaxReturn(json_encode('data-save-success' . $chapter_progress)); } else { $this->ajaxReturn(json_encode('data-save-fail' . $chapter_progress)); } } // } } }<file_sep><?php // 后台管理首页的控制器 namespace Student\Controller; use Think\Controller; class IndexController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 展示网站首页的方法,默认调用的方法,index.html也是默认的模版,即首页 */ function index() { header("Content-Type:text/html; charset=utf-8"); // 首页不乱码 // echo "这里是学生模块,以后是网站首页" ; $this->display('index'); } /** * 展示网站首页的轮播图,其中的图片信息都是从数据库中获取的 */ function imgturn() { header("Content-Type:text/html; charset=utf-8"); // 不乱码 $info = D('ImgTurn')->order('img_turn_order')->select(); // 按照顺序,从数据库中选出所有轮播图片的信息 // show_bug($info); $this->assign('info', $info); // 向模板输出数据 $this->display(); } /** * 展示bottom的模板,这个需要复用 * 原本Index也要做出复用的,但是已经写成现在这样了,就不改了 */ function bottom() { header("Content-Type:text/html; charset=utf-8"); // 首页不乱码 // echo "bottom" ; $this->display(); } function header() { $this->display(); } }<file_sep><?php // 后台管理首页的控制器 namespace Student\Controller; use Think\Controller; class TestController extends Controller { function index() { echo "test"; } function test() { $this->display('test'); // test方法 // 实例化对象 $form = D('Test'); $aaa = $form->create(); // 收集表单数据 show_bug($aaa); $z = $form->add(); // 添加数据 show_bug($z); } function test2() { $form = D('Test'); $aaa = $form->delete(2); show_bug($aaa); } function test3() { $form = D('Test'); $aaa = $form->find(3); show_bug($aaa); } function test4() { $this->display('test'); $form = M('Test'); $aaa = $form->create(); // 收集表单数据 $bbb = $form->where('id=4')->save($aaa); show_bug($bbb); } function test5() { $sql = "SELECT * FROM hubu_feedback"; $info = M(); $z = $info->query($sql); show_bug($z); } function test6() { header("Content-Type:text/html; charset=utf-8"); // 设置后不乱码 $student_user_id = 1; $User = M("StudentUser"); // 实例化User对象// 更改用户的name值 show_bug($User); $z = $User->where("student_user_id = $student_user_id")->setField('student_user_verify', '3'); show_bug($z); } function emailCheck() { $a = think_send_mail('<EMAIL>', '周博文', '重要邮件', '这不是垃圾邮件啊'); show_bug($a); // think_send_mail('要发送的邮箱','发送人名称,即你的名称','邮件主题','邮件内容'); } // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } }<file_sep><?php //学生用户个人基本信息Model namespace Model; use Think\Model; //父类是Model class StudentUserModel extends Model{ //可以自定义数据表的相关属性,例如数据表前缀,名称等等,进行个性化的设置 /** * 功能:验证用户名以及密码 供控制器使用 * @param 登陆表单中用户输入的用户名/邮箱 $name * @param 登陆表单中用户输入的密码 $pwd * @return boolean|unknown */ function checkNamePwd($name,$pwd){ //根据$name查询数据库里面是否有这一条记录 //可以根据指定字段进行查询getByXXX($name),XXX是字段名,Model父类封装好的方法,执行结果一位数组,PHP本身不区分大小写,采用驼峰法命名 //此处驼峰法命名与数据库之间有一个下划线_的关系,AdminUser对应数据表名字hubu_admin_user,hubu_为数据表前缀 $info = $this-> getBystudent_user_email($name); //show_bug($info);//$info是一个以为数组才是正确,为空说明表单用户名输入错误 //$info不为空,继续验证密码 if($info != null){ //验证密码,查询出来儿密码对比用户输入的密码 if($info['student_user_pwd'] != $pwd){ return false;//返回false } else { //密码输入正确 return $info;//返回$info,回头生成session信息 } } else { //密码错误 return false;//返回false } } /** * 更新学生用户的账户激活状态 * @param 传入的id的值 $student_user_id */ function activeAccount_Model($student_user_id=0){ header("Content-Type:text/html; charset=utf-8");//设置后不乱码 //直接使用SQL语句来更新数据,建议少使用SQL语句,容易加大SQL注入的风险,尽量用框架提供的方法来做 //$sql = "UPDATE hubu_student_user SET student_user_verify = 1 WHERE student_user_id = $student_user_id"; //$a = $this->execute($sql); $User = M("StudentUser"); // 实例化对象 $b = $User-> where("student_user_id = $student_user_id")->setField('student_user_verify',1); //show_bug($b); return $b; } /** * 检查用户填写的邮箱是否已经被注册过 * @param 用户注册的时候填入的表单 $email */ function checkEmail_Registered($email){ //查询数据库中是否已存在这个email $info = $this->getByStudent_user_email($email); if ($info['student_user_email']){ return $info; }else { //数据库中没有这个记录,即用户输入的邮箱可以注册 return false; } } }<file_sep><?php // 后台管理课程的控制器 namespace Teacher\Controller; use Think\Controller; class CourseController extends Controller { /** * TODO 输出课程的列表信息 */ function courseList() { if (! empty($_POST)) { // 有表单数据传递进来 // post表单传递进来的课程类别值 $course_name_class = $_POST['course_name_class']; // show_bug($_POST); // show_bug($course_name_class); if ($course_name_class != null) { // 传进来的值不为空 $m = M('CourseName'); $where = "course_name_class = $course_name_class " . ' and course_name_adder_id = ' . session('adminuser_id'); $p = getpage($m, $where, 5); $course_name = $m->field(true) ->where($where) ->select(); $this->course_name = $course_name; $this->page = $p->show(); $this->assign('course_name', $course_name); $this->display(); } else { // 传进来的值为空,即默认选了全选 $m = M('CourseName'); $where = 'course_name_adder_id = ' . session('adminuser_id'); $p = getpage($m, $where, 5); $course_name = $m->field(true) ->where($where) ->select(); $this->course_name = $course_name; $this->page = $p->show(); $this->assign('course_name', $course_name); $this->display(); } } else { // 没有表单提交 // echo "无表单数据提交"; $m = M('CourseName'); $where = 'course_name_adder_id = ' . session('adminuser_id'); $p = getpage($m, $where, 5); $course_name = $m->field(true) ->where($where) ->select(); $this->course_name = $course_name; $this->page = $p->show(); // show_bug($course_name); $this->assign('course_name', $course_name); $this->display(); } } /** * TODO 查看课程的章节信息的方法 * * @param 课程信息这条记录在数据库中的ID值 $course_name_id */ function showCourseChapter($course_name_id = 0) { if ($course_name_id) { // 有参数传递进来,查询数据库中该课程章节的所有信息,并输出到模板展示 // echo $course_name_id; $section_chapter = getCourseSectionChapterList($course_name_id); // show_bug($section_chapter); // 输出章名称以及信息 $wheres = ' course_section_course_name = ' . $course_name_id; $section_info = D('CourseSection')->where($wheres)->select(); // show_bug($section_info); $this->assign('section_info', $section_info); $this->assign('section_chapter', $section_chapter); $this->display(); } else { echo "出现错误,请联系网站管理员。"; } } /** * 更新一章的章名称,章编号 * * @param 章信息的ID $course_section_id */ function updateSectionInfo($course_section_id) { // show_bug($_POST); $section_info = D('CourseSection')->create(); // show_bug($section_info); $rzt = D('CourseSection')->where("course_section_id = $course_section_id")->save(); if ($rzt) { $this->success('本章信息修改成功!'); } else { $this->error('本章信息未作更改或者出现错误'); } } /** * 删除某一章以及盖章所有小节 * * @param 章信息的ID $course_section_id */ function deleteSection($course_section_id) { $rzt = D('CourseSection')->where("course_section_id = $course_section_id")->delete(); if ($rzt) { $this->success('本章信息删除成功!'); } else { $this->error('本章信息未作更改或者出现错误'); } } /** * TODO 修改课程节的信息 * * @param * 课程节的id course_chapter_id */ function updateCourseChapterInfo($course_chapter_id = 0) { // echo $course_chapter_id; // 表单为空则表示用户没有提交表单 if (empty($_POST)) { if ($course_chapter_id) { // 用传进来的id查询出该节信息,并且输出到模板文件 // 下面这个不要使用select,否则生成的就是一个二维数组,find查询出来的的是一维数组 $course_chapter_info = D('CourseChapter')->where("course_chapter_id = $course_chapter_id")->find(); // show_bug($course_chapter_info); $this->assign('course_chapter_info', $course_chapter_info); // print_r($rst); $this->display('updateCourseChapterInfo'); // $info = D('CourseChapter')->create(); // show_bug($info); } else { echo "出现错误,请联系网站管理员。"; // show_bug($_POST); } } else { // 有表单提交,收集表单数据并且更新数据库 // show_bug($_POST); $info = D('CourseChapter')->create(); // show_bug($info); $rst = D('CourseChapter')->where("course_chapter_id = $course_chapter_id")->save(); // 更新数据库中的对应数据 // show_bug($rst); if ($rst) { $this->success('信息修改成功'); } else { $this->error('信息修改失败,或者未修改'); } } } /** * TODO 更新视频 * * @param number $course_chapter_id */ function updateCourseChapterInfo_video($course_chapter_id = 0) { // echo $course_chapter_id; if ($course_chapter_id) { // 传入的参数为真,执行更新操作 // 检测是否有附件上传 // show_bug($_FILES); if (! empty($_FILES)) { // echo "有附件上传"; // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Admin的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/' ) // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->uploadOne($_FILES['course_chapter_video_url']); // 执行上传操作 // print_r($z); // show_bug($z); if (! $z) { // show_bug($upload->getError()); $this->error($upload->getError()); // 输出错误 } else { // $this->success("文件上传成功!"); echo "文件上传成功!"; } } $_POST['course_chapter_video_url'] = $z['savepath'] . $z['savename']; /** * 这里存储用户头像的文件路径 */ $_POST['course_chapter_time'] = date('Y-m-d H:i:s'); $imgTurnInfo = D('CourseChapter')->create(); // 收集表单数据,create不能收集文件数据,所以要单独添加到$_POST里面 // show_bug($imgTurnInfo); // 将数据存储到数据库里面 $rst = D('CourseChapter')->where("course_chapter_id = $course_chapter_id")->save($imgTurnInfo); // 如果添加成功返回的是这条记录的ID // show_bug($rst); if ($rst) { $this->success('数据更新成功!'); } else { $this->error('数据更新失败!'); } } else { $this->error('程序出现错误,请联系管理员'); } } /** * TODO 更新PPT * * @param number $course_chapter_id */ function updateCourseChapterInfo_ppt($course_chapter_id = 0) { // echo $course_chapter_id; if ($course_chapter_id) { // 传入的参数为真,执行更新操作 // 检测是否有附件上传 // show_bug($_FILES); if (! empty($_FILES)) { // echo "有附件上传"; // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Admin的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/' ) // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->uploadOne($_FILES['course_chapter_ppt_url']); // 执行上传操作 // print_r($z); // show_bug($z); if (! $z) { // show_bug($upload->getError()); $this->error($upload->getError()); // 输出错误 } else { // $this->success("文件上传成功!"); echo "视频文件上传成功!"; } } $_POST['course_chapter_ppt_url'] = $z['savepath'] . $z['savename']; /** * 这里存储用户头像的文件路径 */ $_POST['course_chapter_time'] = date('Y-m-d H:i:s'); $imgTurnInfo = D('CourseChapter')->create(); // 收集表单数据,create不能收集文件数据,所以要单独添加到$_POST里面 // show_bug($imgTurnInfo); // 将数据存储到数据库里面 $rst = D('CourseChapter')->where("course_chapter_id = $course_chapter_id")->save($imgTurnInfo); // 如果添加成功返回的是这条记录的ID // show_bug($rst); if ($rst) { $this->success('数据更新成功!'); } else { $this->error('数据更新失败!'); } } else { $this->error('程序出现错误,请联系管理员'); } } /** * TODO 更新其他附加资料 * * @param number $course_chapter_id */ function updateCourseChapterInfo_else($course_chapter_id = 0) { if ($course_chapter_id) { // 传入的参数为真,执行更新操作 } } /** * TODO 修改课程名称简介以及其他信息的方法 * * @param number $course_name_id */ function updateCourseInfo($course_name_id = 0) { // 判断有无表单提交 if (empty($_POST)) { // echo $course_name_id; if ($course_name_id) { $courseinfo = D('CourseName')->where("course_name_id = $course_name_id")->find(); // show_bug($courseinfo); $this->assign('courseinfo', $courseinfo); $this->display(); } else { $this->error('程序出现错误'); } } else { // 有表单提交,收集表单数据 if (empty($_FILES['course_name_pic']['tmp_name'])) { // 没有附件上传 $this->error('没有选择课程图片'); } else { // 选择了课程图片 // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Admin的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/' ) // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->uploadOne($_FILES['course_name_pic']); // 执行上传操作 // print_r($z); // show_bug($z); if (! $z) { // show_bug($upload->getError()); $this->error($upload->getError()); // 输出错误 } else { // $this->success("文件上传成功!"); echo "文件上传成功!"; } } $_POST['course_name_pic'] = $z['savepath'] . $z['savename']; /** * 这里存储用户头像的文件路径 */ $_POST['course_name_time'] = date('Y-m-d H:i:s'); $course = D('CourseName')->create(); // show_bug($course); // show_bug($_POST); $rst = D('CourseName')->where("course_name_id = $course_name_id")->save(); // 更新数据库 if ($rst) { $this->success('数据更新成功!'); } else { $this->error('数据更新失败!'); } } } /** * 用于展示添加课程模板的方法 */ function showAddCourse() { $wheres = 'course_name_adder_id = ' . session('adminuser_id'); $courseList = D('CourseName')->where($wheres)->select(); $sectionList = D('CourseSection')->select(); // show_bug($sectionList); // show_bug($courseList); $this->assign('sectionList', $sectionList); $this->assign('courseList', $courseList); $this->assign('courseList2', $courseList); $this->display(); } function addCourse() { // show_bug($_POST); if (! empty($_POST)) { // 有表单数据提交 if (empty($_FILES['course_name_pic']['tmp_name'])) { // 没有附件上传 $this->error('没有选择课程图片'); } else { // 选择了课程图片 // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Admin的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/' ) // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->uploadOne($_FILES['course_name_pic']); // 执行上传操作 // print_r($z); // show_bug($z); if (! $z) { // show_bug($upload->getError()); $this->error($upload->getError()); // 输出错误 } else { // $this->success("文件上传成功!"); echo "文件上传成功!"; } } $_POST['course_name_pic'] = $z['savepath'] . $z['savename']; /** * 这里存储用户头像的文件路径 */ $_POST['course_name_time'] = date('Y-m-d H:i:s'); $_POST['course_name_adder_id'] = session('adminuser_id'); // 添加用户的ID $course = D('CourseName')->create(); // show_bug($course); // show_bug($_POST); $rst = D('CourseName')->add(); // 添加数据到数据库 if ($rst) { $this->success('数据添加成功!'); } else { $this->error('数据添加失败!'); } } } function addSection() { if (! empty($_POST)) { // 有表单数据提交,收集表单数据 // show_bug($_POST); $_POST['course_section_time'] = date('Y-m-d H:i:s'); // 添加时间戳 $courseSection = D('CourseSection')->create(); // show_bug($courseSection); $rst = D('CourseSection')->add(); // 添加数据到数据库 if ($rst) { $this->success('数据添加成功!'); } else { $this->error('数据添加失败!'); } } else { // 从数据库中查询数据,并且添加到模板之中 // 这一步就在showAddCourse里面已经完成 } } function addChapter() { // show_bug($_POST); if (! empty($_POST)) { // 有表单数据提交 // print_r($_FILES); if (empty($_FILES['course_chapter_video_url']['tmp_name'])) { // 没有附件上传 // exit(); $this->error('没有选择视频文件'); } else { // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Admin的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/', // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 'maxSize' => 0 ) // 上传的文件大小限制 (0-不做限制) ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->upload(); // 执行上传操作,如果视频和PPT都有,这里需要上传两个文件,PPT以及视频 // print_r($z); // show_bug($z); // exit(); if (! $z) { // show_bug($upload->getError()); $this->error($upload->getError()); // 输出错误 } else { // $this->success("文件上传成功!"); echo "文件上传成功!"; } } $_POST['course_chapter_video_url'] = $z['course_chapter_video_url']['savepath'] . $z['course_chapter_video_url']['savename']; /** * 这里存储视频的文件路径 */ $_POST['course_chapter_video_size'] = $z['course_chapter_video_url']['size']; // 存储视频文件的大小 $_POST['course_chapter_ppt_url'] = $z['course_chapter_ppt_url']['savepath'] . $z['course_chapter_ppt_url']['savename']; /** * 这里存储PPT的文件路径 */ $_POST['course_chapter_ppt_size'] = $z['course_chapter_ppt_url']['size']; // 存储PPT文件的大小 $_POST['course_chapter_time'] = date('Y-m-d H:i:s'); // $_POST['course_chapter_adder_id'] = session('adminuser_id');//添加用户ID $course = D('CourseChapter')->create(); // show_bug($course); // show_bug($_POST); $rst = D('CourseChapter')->add(); // 添加数据到数据库 if ($rst) { $this->success('数据添加成功!'); // echo '数据添加成功'; } else { $this->error('数据添加失败!'); } } } /** * TODO 删除课程的所有信息,包括所有小节信息 * * @param number $course_name_id */ function deleteCourse($course_name_id = 0) { if ($course_name_id) { // 删除课程以及该课程的所有章节信息 $rst_course = D('CourseName')->where("course_name_id = $course_name_id")->delete(); // 删除课程信息 $rst_chapter = D('CourseChapter')->where("course_chapter_course_name = $course_name_id")->delete(); if ($rst_chapter or $rst_course) { $this->success('删除成功'); } else { $this->error('删除失败'); } } } /** * TODO 删除课程的某一个小节 * * @param number $course_chapter_id */ function deleteCourseChapter($course_chapter_id = 0) { if ($course_chapter_id) { // 执行删除课程小结操作 $rst = D('CourseChapter')->where("course_chapter_id = $course_chapter_id")->delete(); if ($rst) { $this->success('删除成功'); } else { $this->error('删除失败'); } } } } <file_sep><?php // 后台管理首页的控制器 namespace Student\Controller; use Think\Controller; class RecommendedController extends Controller { // 空操作的方法 function _empty() { echo '服务器繁忙,请稍后再试...'; } /** * 精品推荐的相关课程 */ function recommended() { header("Content-Type:text/html; charset=utf-8"); // 不乱码 $info = M('Recommended')->select(); // show_bug($info); $recommended = array(); // 存储模板需要的数据,下面的代码将生成所需格式的数据 foreach ($info as $k => $v) { $course_name_id = $v['recommended_course_name']; $course_info = D('CourseName')->where("course_name_id = $course_name_id")->find(); // show_bug($course_info); $course_info['course_name_choosed_num'] = M('ChooseCourse')->where("choose_course_choosed = $course_name_id")->count(); // 已选这门课程总人数 $recommended[$k] = $course_info; } // show_bug($recommended); $this->assign('recommended', $recommended); // 向模板输出数据 $this->display(); } }<file_sep><?php // 后台管理用户留言的控制器 namespace Teacher\Controller; use Think\Controller; class FeedbackController extends Controller { function feedback($feedback_id = 0) { // echo $feedback_id; // 获取“删除”按钮传回来的id,根据id来执行删除 if ($feedback_id > 0) { // 执行删除操作 $del = D('Feedback'); $rst = $del->delete($feedback_id); // show_bug($rst); } // 用户留言的浏览与管理页面 // echo "feedback"; // var_dump(get) // 从数据库中查询出数据,并输出到前台模板 $m = M('Feedback'); $where = ''; $p = getpage($m, $where, 6); $list = $m->field(true) ->where($where) ->select(); $this->list = $list; $this->page = $p->show(); $this->assign('info', $list); // $feedback = D('Feedback'); // $info = $feedback->select();//从数据库中查询出数据存储在$info中 // show_bug($info); // $this->assign('info',$info); $this->display(); } function emailCheck() { $a = think_send_mail('<EMAIL>', '发件人', '在线学习平台', '这是一封测试邮件,无需回复!不要太在意为什么是126邮箱。。。这并不重要。。。'); show_bug($a); // think_send_mail('要发送的邮箱','发送人名称,即你的名称','邮件主题','邮件内容'); } }<file_sep><?php //课程类别的Model namespace Model; use Think\Model; //父类是Model class CourseClassModel extends Model{ }<file_sep><?php //CourseChapter的Model,存储所有课程的章节信息 namespace Model; use Think\Model; //父类是Model class CourseChapterModel extends Model{ }<file_sep><?php // 后台管理员用户控制器 // 命名空间必须写在第一行 namespace Admin\Controller; use Think\Controller; class AdminUserController extends Controller { /** * 名称:login() * 功能:管理员用户登录的相关逻辑判断 */ function login() { // 判断用户是否提交了表单 if (! empty($_POST)) { // 先输出这个值看对不对,经输出,得输出值为 Array ( [name] => 00 [password] => 000 [code] => 000 ) // print_r($_POST); // 验证码校验 $verify = new \Think\Verify(); // 实例化一个Verify对象,好调用其中的校验验证码的方法 check($code, $id) if (! $verify->check($_POST['code'])) { // echo "验证码错误!"; $this->error("验证码输入错误!"); } else { // echo "验证码正确!"; // 验证码正确之后,判断用户名和密码 // 可以直接用一条SQL语句从数据库中同时查询用户名和密码,如果存在就说明正确,但此方法不安全,会增加SQL注入风险 // 一般,先查询指定用户名的信息,如果有这条信息再比较密码是否正确 // 在model模型里面专门写一个方法进行验证,当前model模型为AdminUserModel,不要再控制器里面验证 $user = new \Model\AdminUserModel(); // 实例化AdminUserModel()对象,好调用其中自定义的检验用户名密码是否正确的方法checkNamePwd($name,$pwd) $rst = $user->checkNamePwd($_POST['username'], $_POST['password']); // $rst如果为false,那说明输入的密码不正确,如果为一个数组,就说明输入正确,就可以生成session信息 // show_bug($rst); if ($rst === false) { // echo "输入的用户名或者密码错误!"; $this->error("输入的用户名或密码错误!"); } else { // 登录信息持久化,生成session信息 // 性别在数据库中存储为1,2两种形式,如果为数字1就是男,数字2就是女,这里写一个判断 if ($rst['adminuser_sex'] == 1) { session('adminuser_sex', '男'); // 存储用户性别adminuser_sex } else if ($rst['adminuser_sex'] == 2) { session('adminuser_sex', '女'); // 存储用户性别adminuser_sex } else { session('adminuser_sex', '未知'); // 存储用户性别adminuser_sex } session('adminuser_id', $rst['adminuser_id']); // 存储id session('adminuser_username', $rst['adminuser_username']); // 存储用户名adminuser_username session('adminuser_email', $rst['adminuser_email']); // 存储用户adminuser_email // session('adminuser_sex', $rst['adminuser_sex']);//存储用户性别adminuser_sex session('adminuser_tel', $rst['adminuser_tel']); // 存储用户电话adminuser_tel session('adminuser_qq', $rst['adminuser_qq']); // 存储用户QQ adminuser_qq session('adminuser_addr', $rst['adminuser_addr']); // 存储用户地址adminuser_addr session('adminuser_introduction', $rst['adminuser_introduction']); // 存储用户个人简介adminuser_introduction session('adminuser_pic', $rst['adminuser_pic']); // 存储用户头像路径信息 // echo "登陆成功!"; // 跳转到后台首页,Controller类的redirect()方法 $this->redirect('New/category', array('cate_id' => 2), 5, '页面跳转中...'); // 将参数array('cate_id' => 2)传递到index $this->redirect('AdminIndex/index'/*,array('adminuser_username' => $rst['adminuser_username']) ,1,'正在登录到后台系统...' */); } } } else { // 调用视图display(),直接展示login.html模板,display()没有参数那么调用的模板名称就与当前方法名一致 $this->display(); } } /** * 名称:logout() 退出系统的方法 * 功能:要清除session,跳转到登录页面 */ function logout() { session(null); // 清除所有的session值 $this->redirect('AdminUser/login'); // 跳转到登录界面,即调用AdminUser控制器的login方法 } /** * 名称:verifyImg() * 功能:实现验证发的生成 */ function verifyImg() { // 配置验证码的数组 $config = array( 'expire' => 1800, // 验证码过期时间(s) 'useZh' => false, // 使用中文验证码 'useImgBg' => false, // 使用背景图片 'fontSize' => 14, // 验证码字体大小(px) 'useCurve' => false, // 是否画混淆曲线 'useNoise' => false, // 是否添加杂点 'imageH' => 32, // 验证码图片高度 'imageW' => 100, // 验证码图片宽度 'length' => 4, // 验证码位数 'fontttf' => '', // 验证码字体,不设置随机获取 'bg' => array( 243, 251, 254 ), // 背景颜色 'reset' => true ) // 验证成功后是否重置 ; // 实例化的时候传入配置 $verify = new \Think\Verify($config); // 实例化Verify对象,此处要注意命名空间的书写,可以使用在admin.php中定义的show_bug()函数输出对象看实例化好了没有 // show_bug($verify); $verify->entry(); } /** * 实现用户注册的方法 */ public function register() { echo "这是用户注册功能,待完善中..."; } /** * 实现对自己管理员账户信息的修改操作 * 接收表单提交过来的数据 * 并将数据库中的用户个人信息进行更新 */ function updateUserInfo() { // print_r($_POST);//Array ( [mpass] => 123456 [newpass] => <PASSWORD>7 [renewpass] => <PASSWORD> ) // echo count($_POST);//输出数组长度,后面根据数组长度判断提交的是哪个表单 // 1.检测用户是否提交了表单 if (! empty($_POST)) { // print_r($_POST); // 检测用户提交的是哪个表单,根据$_POST数组长度来判断 if (count($_POST) == 3) { // 用户提交的是修改管理员密码的表单 // 需要验证用户名与密码是否正确,可以直接跨控制器调用AdminUser/checkNamwePwd方法 $info = new \Model\AdminUserModel(); // show_bug($info); $rst = $info->checkNamePwd(session('adminuser_username'), $_POST['mpass']); // 从session中获取当前用户的用户名 // show_bug($rst); // echo session('adminuser_username'); if ($rst) { // 原始密码输入正确 // echo "原始密码输入正确"; // 1.收集表单数据 2.实现用户密码的修改操作 $arr = array( 'adminuser_pwd' => $_POST['renew<PASSWORD>'],/* 获取表单中的新密码 */ ); $resault = $info->where('adminuser_id = %d', array( session('adminuser_id') ))->save($arr); // show_bug($resault); // 根据$resault值判断是否修改成功,给予用户提示信息 if ($resault) { // 修改成功 // echo "修改密码成功"; // 跳转到原页面 $this->redirect('AdminUser/updateUserInfo', array(), 3, '密码修改成功...正在跳转...'); } else { // 修改不成功 // echo "修改不成功"; $this->redirect('AdminUser/updateUserInfo', array(), 3, '密码修改失败/未更改...正在跳转...'); } } else { // 原始密码输入不正确 // echo "原始密码输入不正确"; $this->redirect('AdminUser/updateUserInfo', array(), 3, '原始密码输入不正确...正在跳转...'); } } else { // 用户提交的是修改管理员其他信息的表单 // echo "用户提交的是修改管理员其他信息的表单"; // $aaaa = D('AdminUser'); // $a = $aaaa->select(); // show_bug($a); $info = new \Model\AdminUserModel(); // 判断是否有附件上传,有就实例化Upload,把附件上传到服务器指定位置,获得附件路径名存入$_POST if (! empty($_FILES)) { // 自定义文件接收相关配置 $config = array( 'rootPath' => 'Hubu/Public/', // 保存根路径,Andim目录下面public目录定义为Admin的根目录,这里的路径设置是以admin.php所在路径为依据设置 'savePath' => 'Uploads/' ) // 保存路径为Uploads,TP框架会自动生成如2016-12-18的日期文件夹 ; // print_r($_FILES);//是个二维数组 $upload = new \Think\Upload($config); // 实例化Upload对象 // show_bug($upload); $z = $upload->uploadOne($_FILES['pic']); // 执行上传操作 // print_r($z); // show_bug($z); if (! $z) { $this->error($upload->getError()); // 输出错误 } else { // $this->success("文件上传成功!"); echo "头像文件上传成功!"; } } // 实现对用户其他信息修改的操作 // 收集post表单数据 $user_info = array( 'adminuser_email' => $_POST['email'], 'adminuser_sex' => $_POST['sex'], 'adminuser_tel' => $_POST['tel'], 'adminuser_qq' => $_POST['qq'], 'adminuser_addr' => $_POST['addr'], 'adminuser_introduction' => $_POST['introduction'], 'adminuser_pic' => /* $config['rootPath']. */$z['savepath'] . $z['savename'] )/** * 这里存储用户头像的文件路径 */ ; // show_bug($user_info); $res = $info->where('adminuser_id = %s', array( $_POST['adminuser_id'] ))->save($user_info); // show_bug($res); // 根据$resault值判断是否修改成功,给予用户提示信息 if ($res) { // 修改成功 // echo "修改成功"; /** * 因为页面上部分信息是从session中获得,所以更改个人信息后就需要更新以下session */ // 跳转到原页面 $this->redirect('AdminUser/updateUserInfo', array(), 3, '信息修改成功,重新登录后生效...正在跳转...'); } else { // 修改不成功 // echo "信息修改不成功"; $this->redirect('AdminUser/updateUserInfo', array(), 3, '信息修改失败/未更改...正在跳转...'); } } } else { // 用户没有提交表单,那么从session中读取出用户的个人信息,放到表单里面 // 展现表单 // $this->assign($a); $this->display(); } // echo "实现对自己管理员账户信息的修改操作"; // $this->display(); } }<file_sep><?php //热门课程的Model namespace Model; use Think\Model; //父类是Model class HotCourseModel extends Model{ }<file_sep>$(".login-1 #user").each(function(){ var maxwidth=6; if($(this).text().length>maxwidth){ $(this).text($(this).text().substring(0,maxwidth)); $(this).html($(this).html()+'…'); } }); $('a#m-nav-other').click(function () { $(this).removeClass().addClass("btn btn-warning").siblings().removeClass().addClass('btn btn-link'); }); $(function (){ $("#appurl").popover({ trigger : 'hover', html:true, placement:'bottom' }); $("#appurl2").popover({ trigger : 'hover', html:true, placement:'left' }); $("#loginURL").popover({ trigger : 'hover', html:true, delay: { "show": 0, "hide": 1000 }, placement:'bottom' }); }); function iFrameHeight() { var ifm= document.getElementById("iframepage"); var subWeb = document.frames ? document.frames["iframepage"].document : ifm.contentDocument; if(ifm != null && subWeb != null) { ifm.height = subWeb.body.scrollHeight; ifm.width = subWeb.body.scrollWidth; } } <file_sep><?php // 后台管理员 热门课程的控制器,展示课程信息的模板 namespace Teacher\Controller; use Think\Controller; class HotCourseController extends Controller { /** * "热门课程"的模版页面,展示模版页面并向其输出数据 */ function hotCourse() { $hotCourse = D('HotCourse')->getField('hot_course_course_name', true); // 查询出所有课程的ID信息,查询出全部信息 // show_bug($hotCourse); // print_r($hotCourse); // 通过上述ID,循环查询出所有课程的信息并存储到数组中 $hot = array(); foreach ($hotCourse as $k => $v) { // 使用SQL语句查询,或者使用TP自带的CURD方法操作,推荐使用TP的封装方法 $info = D('CourseName')->where("course_name_id = $v")->find(); // show_bug($info); // 将上述查询到的结果存储到$hot数组里面 $hot[$k] = $info; } // show_bug($hot); /** * 查询出所有课程的信息 * 同时要查询已有的热门课程,如果该课程已经是热门课程,那就不在下面展示出来 */ $courseList = D('CourseName')->select();//这里面是所有课程的信息 //下面剔除已经是热门课程的课程 //查询出已有的热门课程 $hotCourseList = D('HotCourse')->select(); //用循环来剔除热门课程 //show_bug($courseList); $courseListNew = array(); foreach ($courseList as $k => $v){ foreach ($hotCourseList as $kk => $vv){ if ($v['course_name_id'] === $vv['hot_course_course_name']){ //$courseListNew[] = $vv['hot_course_course_name']; unset($courseList[$k]); } } } $this->assign('courseList', $courseList); $this->assign('hot', $hot); $this->display(); } /** * 删除指定的热门课程 * * @param number $hot_course_id */ function deleteHotCourse($hot_course_id = 0) { if ($hot_course_id) { $info = D('HotCourse')->where("hot_course_course_name = $hot_course_id")->delete(); // 执行删除操作 if ($info) { $this->success('删除热门课程成功'); } else { $this->error('删除热门课程失败'); } } else { $this->error('出现未知错误!'); } } /** * 添加一门课程为热门课程 */ function addHotCourse() { if (! empty($_POST)) { // show_bug($_POST); $info = D('HotCourse')->create(); // show_bug($info); $z = D('HotCourse')->add($info); // 添加热门课程到数据库中 if ($z) { $this->success('添加成功'); } else { $this->error('添加失败'); } } } }<file_sep><?php //用户反馈的Model namespace Model; use Think\Model; //父类是Model class ChapterProgressModel extends Model{ }<file_sep><?php header('content-type:text/html;charset=utf-8');//如果这个漏掉了会导致接口无效 //获取Android上传的字符串 $text = $_POST['text']; //获取时间 $date_tmp = time();//获取Linux时间戳 $dateline = date("Y-m-d H:i:s", $date_tmp);//将时间戳转换为标准时间 //返回数据 //echo "1111111111111111111111"; echo $text.$dateline;
6ea76a1567254555d2fceca44521479d49d19646
[ "Markdown", "JavaScript", "PHP" ]
49
PHP
zhoubowen-sky/hubuedu
9cbea768b9cd5de2bc8bd6f59e5a511d1dd263a5
2c63c6bd561b0d06b8f2a0d26e1c489904e30b7f
refs/heads/main
<repo_name>zidinghe/generals-AI<file_sep>/README.md # generals-AI An simulated AI for the game generals.io Copyright (C) zidinghe Do not use this program for negative purposes. This is a generals simulated AI written in C++. It is basically written using Q-Learning algorithm. If you find any bug or stupid code, please send an email to my account <EMAIL> , this is very important to me! Enjoy playing! <file_sep>/generals-AI-v2.3.cpp #include<bits/stdc++.h> #include<windows.h> #include<conio.h> #define random(a,b) rand()%(b-a+1)+a using namespace std; struct square{ int color=0; int type=0;//0:mountain 1:temple 2:field 3:general int popu=0; square()=default; square(int c,int t,int p){ color=c; type=t; popu=p; } }a[51][51]; bool alive[11]={0}; int val[51][51]={0}; int s[2501][2501]={0}; int q[2501][2501]={0}; int n=20,turn=0,lastColPos[11]; int totalField[11]={0}; int colPosX,colPosY; int GetTotalPopu(int Color){ int sum=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(a[i][j].color==Color){ sum+=a[i][j].popu; } } } return sum; } int GetTotalField(int Color){ int sum=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(a[i][j].color==Color){ sum++; } } } return sum; } void Check(int Color){ memset(val,0,sizeof(val)); memset(s,-1,sizeof(s)); memset(q,0,sizeof(q)); int g=random(45,85); cout<<g<<" "<<endl; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ int x=a[i][j].popu; if(a[i][j].type==0) val[i][j]=-1e6; else if(a[i][j].type==1){ if(a[i][j].color==0) val[i][j]=0-2*x+int(turn/2); else if(a[i][j].color==Color) val[i][j]=-5+15*x+int(turn/4); else val[i][j]=0-x+int(turn/8);//若对方庙人数少则占庙 } else if(a[i][j].type==2){ if(a[i][j].color==0) val[i][j]=2+3*int(turn/25); else if(a[i][j].color==Color) val[i][j]=2*x+int(turn/50); else val[i][j]=2-int(x/2)+int(turn/25);//避开对方主力部队 } else if(a[i][j].type==3){ if(a[i][j].color==Color) val[i][j]=int(x/2); else val[i][j]=-int(x/2)+150*turn+10000; } } } int mx=-2e6,mxa=-1,mxb=-1,mxv=-2e6,mxva=-1,mxvb=-1; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(val[i][j]>mxv){ mxv=val[i][j]; mxva=i; mxvb=j; } if(a[i][j].color==Color&&val[i][j]>mx&&a[i][j].popu>1&&i*n+j!=lastColPos[Color]){ mx=val[i][j]; mxa=i; mxb=j; } else if(a[i][j].color==Color&&a[i][j].type==3&&val[i][j]>=mx*2 &&a[i][j].popu>1&&i*n+j!=lastColPos[Color]){//己方主城,保留一半兵力 mx=a[i][j].popu/2; mxa=i; mxb=j; } } } colPosX=mxa; colPosY=mxb; // cout<<colPosX<<" "<<colPosY<<endl; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i<n-1) s[i*n+j][i*n+n+j]=(val[i][j]+val[i+1][j])/2; if(i>0) s[i*n+j][i*n-n+j]=(val[i][j]+val[i-1][j])/2; if(j<n-1) s[i*n+j][i*n+j+1]=(val[i][j]+val[i][j+1])/2; if(j>0) s[i*n+j][i*n+j-1]=(val[i][j]+val[i][j-1])/2; } } for(int i=1;i<=n*n;i++){ int pos=random(0,n*n-1); while(pos!=mxva*n+mxvb){ int to=random(0,n*n-1); int mx=-2e6,mxa=pos; if(s[pos][to]>-1){ for(int k=0;k<n*n;k++){ if(q[to][k]>mx){ mx=q[to][k]; mxa=k; } } q[pos][to]=s[pos][to]+g*1.0*q[to][mxa]*0.01+0.5; } pos=to; } } int mmx=0,mxdir=0; for(int i=0;i<n*n;i++){ if(i==lastColPos[Color]) continue; int p=random(80,120); if(q[colPosX*n+colPosY][i]*p*1.0/100.0>mmx){ // cout<<i<<" "; mmx=q[colPosX*n+colPosY][i]*p*1.0/100.0; mxdir=colPosX*n+colPosY-i; } } // cout<<colPosX<<" "<<colPosY<<" "<<mxdir<<endl; lastColPos[Color]=colPosX*n+colPosY; // cout<<lastColPos[Color]<<endl; int movePopu=a[colPosX][colPosY].popu-1; if(mxdir==1&&colPosY>0){//move left if(a[colPosX][colPosY-1].color==Color) a[colPosX][colPosY-1].popu+=movePopu; else{ a[colPosX][colPosY-1].popu-=movePopu; if(a[colPosX][colPosY-1].popu<0){ a[colPosX][colPosY-1].color=Color; a[colPosX][colPosY-1].popu=0-a[colPosX][colPosY-1].popu; } } a[colPosX][colPosY].popu=1; } if(mxdir==-1&&colPosY<n-1){//move right if(a[colPosX][colPosY+1].color==Color) a[colPosX][colPosY+1].popu+=movePopu; else{ a[colPosX][colPosY+1].popu-=movePopu; if(a[colPosX][colPosY+1].popu<0){ a[colPosX][colPosY+1].color=Color; a[colPosX][colPosY+1].popu=0-a[colPosX][colPosY+1].popu; } } a[colPosX][colPosY].popu=1; } if(mxdir==n&&colPosX>0){//move up if(a[colPosX-1][colPosY].color==Color) a[colPosX-1][colPosY].popu+=movePopu; else{ a[colPosX-1][colPosY].popu-=movePopu; if(a[colPosX-1][colPosY].popu<0){ a[colPosX-1][colPosY].color=Color; a[colPosX-1][colPosY].popu=0-a[colPosX-1][colPosY].popu; } } a[colPosX][colPosY].popu=1; } if(mxdir==0-n&&colPosX<n-1){//move down if(a[colPosX+1][colPosY].color==Color) a[colPosX+1][colPosY].popu+=movePopu; else{ a[colPosX+1][colPosY].popu-=movePopu; if(a[colPosX+1][colPosY].popu<0){ a[colPosX+1][colPosY].color=Color; a[colPosX+1][colPosY].popu=0-a[colPosX+1][colPosY].popu; } } a[colPosX][colPosY].popu=1; } return; } int main(){ srand(time(NULL)); /* a[0][0]={2,3,10}; a[0][1]={2,2,3}; a[0][2]={2,2,3}; a[0][3]={1,2,2}; a[1][0]={2,1,10}; a[1][1]={2,2,4}; a[1][2]={2,2,2}; a[1][3]={1,2,1}; a[2][0]={1,2,4}; a[2][1]={1,2,3}; a[2][2]={2,2,15}; a[2][3]={1,2,1}; a[3][0]={0,0,0}; a[3][1]={1,2,3}; a[3][2]={1,2,2}; a[3][3]={1,3,30}; */ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ a[i][j]={0,2,0}; } } a[0][0]={2,3,1}; a[n-1][n-1]={1,3,1}; a[2][2]={0,1,20}; a[n-3][n-3]={0,1,20}; a[1][n-2]={0,1,20}; a[n-2][1]={0,1,20}; a[0][n-1]={0,0,0}; a[0][1]={0,0,0}; a[n-1][0]={0,0,0}; a[n-1][n-2]={0,0,0}; while(1){ COORD pos; pos.X=0; pos.Y=0; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); turn++; cout<<"Turn "<<turn<<" "<<endl<<endl; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ int t=a[i][j].type; if((t==1||t==3)&&a[i][j].color!=0){ a[i][j].popu++; } if(turn%25==0&&a[i][j].color!=0){ a[i][j].popu++; } } } // /* for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(a[i][j].color==1) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),4*17); else if(a[i][j].color==2) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),1*17); else SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),0*17); cout<<" "; if(a[i][j].type==0) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),2*17);//mountain if(a[i][j].type==1) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),8*17);//temple if(a[i][j].type==2) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),7*17);//field if(a[i][j].type==3) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),6*17);//general cout<<" "; } SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),15); cout<<endl; for(int j=0;j<n;j++){ cout<<setw(4)<<a[i][j].popu; } SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),15); cout<<endl; } cout<<endl; // */ memset(alive,0,sizeof(alive)); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ for(int col=1;col<=2;col++){ if(a[i][j].color==col&&a[i][j].type==3) alive[col]=1; } } } if(!alive[1]){ cout<<endl<<endl<<endl<<"Blue won!"<<endl; system("pause"); break; } if(!alive[2]){ cout<<endl<<endl<<endl<<"Red won!"<<endl; system("pause"); break; } memset(totalField,0,sizeof(totalField)); cout<<" Field Popu "<<endl; for(int col=1;col<=2;col++){ if(col==1) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),4*17); else if(col==2) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),1*17); else SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),0*17); cout<<" "; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),15); cout<<" "<<setw(5)<<GetTotalField(col)<<" "<<setw(4)<<GetTotalPopu(col)<<" "<<endl; } if(turn%2==1){ for(int col=1;col<=2;col++){ Check(col); } } else{ for(int col=2;col>=1;col--){ Check(col); } } // system("pause"); } return 0; }
724b594cc7ad3f228a14b5266a95c98bf4f4af88
[ "Markdown", "C++" ]
2
Markdown
zidinghe/generals-AI
8cfe2f8abd82ae8ba3128d70cce176d12e733be3
a8dbc240352c5637d1e75a6dbdec4e6dfea7c608
refs/heads/master
<file_sep># ussd-test spring boot ussd sample with h2 console session management <file_sep>/* * 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 com.pocco.pl.ussdtest.business.logic; import com.pocco.pl.ussdtest.interfaces.LoanRequestRepo; import com.pocco.pl.ussdtest.model.USSDRequestModel; import java.util.Map; /** * * @author sure */ public class Pin { private final LoanRequestRepo loanRequestRepo; public Pin(LoanRequestRepo loanRequestRepo) { this.loanRequestRepo = loanRequestRepo; } public Map init(Map<String, String> sessionMap, USSDRequestModel mnoSession) { String statusLevel = sessionMap.get("statusLevel"); String ussdType = "continue"; String responseString = ""; switch (statusLevel) { case "2": String pin = mnoSession.getUssdBody().replaceAll("[^\\d.]", ""); if (pin.length() != 4) { ussdType = "repeat"; responseString = "Invalid Pin. Please try again"; } else { if ("1234".equals(pin)) { responseString = "Please select service:\n1. Loan Request\n2. Loan Repayment"; } else { ussdType = "repeat"; responseString = "Invalid Pin. Please try again"; } } break; case "3": String serviceRequest = mnoSession.getUssdBody().replaceAll("[^\\d.]", ""); if ("1".equals(serviceRequest)) {// sessionMap.put("statusLevel", "1"); sessionMap.put("status", "LoanRequest"); return new LoanRequest().init(sessionMap, mnoSession); } else if ("2".equals(serviceRequest)) { sessionMap.put("statusLevel", "1"); sessionMap.put("status", "PayLoan"); return new PayLoan().init(sessionMap, mnoSession); } else { ussdType = "repeat"; responseString = serviceRequest + "Invalid Menu. Please try again"; } break; default: responseString = "An error occured please try again later"; ussdType = "end"; break; } sessionMap.put("responseString", responseString); sessionMap.put("ussdType", ussdType); // sessionMap.put("responseObject", new Gson().toJson(responseObject)); return sessionMap; } }
999c6ef1beca801926d50c81a8e360bf93102413
[ "Markdown", "Java" ]
2
Markdown
anumber8/ussd-test
77eb23313fd284eef11d03a2f1daeedc4bf7ec7c
747f17ad276b069f4a09ba9d54c8fcbd5c87dd3e
refs/heads/master
<file_sep>// // ViewController.swift // litterBoxStatus // // Created by <NAME> on 12/7/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { //outlets @IBOutlet weak var scoopLabel: UILabel! @IBOutlet weak var cleanBoxLabel: UILabel! @IBOutlet weak var firstStartButton: UIButton! @IBOutlet weak var imageView: UIImageView! //variables var scoopTimer = Timer() var cleanBoxTimer = Timer() var scoopStartTime = TimeInterval() var cleanBoxStartTime = TimeInterval() var elapsedScoopTime = 0.0 var elapsedCleanBoxTime = 0.0 var refreshInterval = 0.1 //MARK: vDL override func viewDidLoad() { super.viewDidLoad() let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore") if launchedBefore { print("Not first launch.") } else { print("First launch, setting UserDefault.") UserDefaults.standard.set(true, forKey: "launchedBefore") } if !launchedBefore { //set all UD to 0.0 aka current values let scoopStartTime = 0.0 let cleanBoxStartTime = 0.0 let defaults = UserDefaults.standard print("first launch, setting the four UserDefault variables to current value of 0.0") defaults.set(scoopStartTime, forKey: "sST") defaults.set(cleanBoxStartTime, forKey: "cBST") defaults.set(elapsedScoopTime, forKey: "eST") defaults.set(elapsedCleanBoxTime, forKey: "eCBT") defaults.synchronize() } else { loadDefaults() } print("eST on load = \(elapsedScoopTime)") print("eCBT on load = \(elapsedCleanBoxTime)") print("sST on load = \(scoopStartTime)") print("cBST on load = \(cleanBoxStartTime)") if elapsedCleanBoxTime > 0.0 || elapsedScoopTime > 0.0 { //start timers with current values and hide firstStartButton scoopTimer = Timer.scheduledTimer(timeInterval: refreshInterval, target: self, selector: #selector(updateScoopTimer), userInfo: nil, repeats: true) cleanBoxTimer = Timer.scheduledTimer(timeInterval: refreshInterval, target: self, selector: #selector(updateCleanBoxTimer), userInfo: nil, repeats: true) firstStartButton.isHidden = true } firstStartButton.isHidden = false } //MARK: press buttons @IBAction func firstStartButtonPressed(_ sender: Any) { scoopButtonPressed(UIButton.self) cleanBoxButtonPressed(UIButton.self) firstStartButton.isHidden = true } @IBAction func scoopButtonPressed(_ sender: Any) { scoopStartTime = NSDate.timeIntervalSinceReferenceDate print("sST = \(scoopStartTime)") let defaults = UserDefaults.standard defaults.set(scoopStartTime, forKey: "sST") defaults.synchronize() scoopTimer = Timer.scheduledTimer(timeInterval: refreshInterval, target: self, selector: #selector(updateScoopTimer), userInfo: nil, repeats: true) } @IBAction func cleanBoxButtonPressed(_ sender: Any) { cleanBoxStartTime = NSDate.timeIntervalSinceReferenceDate print("cBST = \(cleanBoxStartTime)") let defaults = UserDefaults.standard defaults.set(cleanBoxStartTime, forKey: "cBST") defaults.synchronize() cleanBoxTimer = Timer.scheduledTimer(timeInterval: refreshInterval, target: self, selector: #selector(updateCleanBoxTimer), userInfo: nil, repeats: true) scoopButtonPressed(UIButton.self) } //MARK: updateTimers @objc func updateScoopTimer() { let currentTime = NSDate.timeIntervalSinceReferenceDate elapsedScoopTime = currentTime - scoopStartTime //save let defaults = UserDefaults.standard defaults.set(elapsedScoopTime, forKey: "eST") defaults.synchronize() print("eST = \(elapsedScoopTime)") let days = Int(elapsedScoopTime / 86400) elapsedScoopTime -= (TimeInterval(days) * 86400) let hours = Int(elapsedScoopTime / 3600.0) elapsedScoopTime -= (TimeInterval(hours) * 3600) let minutes = Int(elapsedScoopTime / 60.0) elapsedScoopTime -= (TimeInterval(minutes) * 60) let seconds = Int(elapsedScoopTime) elapsedScoopTime -= TimeInterval(seconds) //update UIImage View based on time if days >= 1 { print("RED LIGHT") imageView.image = UIImage(named: "redLight") } else if hours >= 12 { print("YELLOW LIGHT") imageView.image = UIImage(named: "yellowLight") } else { imageView.image = UIImage(named: "greenLight") } let timeString = String(format:"%01i:%02i:%02i:%02i", days, hours, minutes, seconds) scoopLabel.text = timeString } @objc func updateCleanBoxTimer() { let currentTime2 = NSDate.timeIntervalSinceReferenceDate elapsedCleanBoxTime = currentTime2 - cleanBoxStartTime //save let defaults = UserDefaults.standard defaults.set(elapsedCleanBoxTime, forKey: "eCBT") defaults.synchronize() print("eCBT = \(elapsedCleanBoxTime)") let days2 = Int(elapsedCleanBoxTime / 86400) elapsedCleanBoxTime -= (TimeInterval(days2) * 86400) // let hours2 = Int(elapsedCleanBoxTime / 3600.0) // elapsedCleanBoxTime -= (TimeInterval(hours2) * 3600) // // let minutes2 = Int(elapsedCleanBoxTime / 60.0) // elapsedCleanBoxTime -= (TimeInterval(minutes2) * 60) // // let seconds2 = Int(elapsedCleanBoxTime) // elapsedCleanBoxTime -= TimeInterval(seconds2) let timeString = String(format:"%01i Days", days2) cleanBoxLabel.text = timeString cleanBoxLabel.sizeToFit() } func loadDefaults() { let defaults = UserDefaults.standard elapsedScoopTime = defaults.object(forKey: "eST") as! Double elapsedCleanBoxTime = defaults.object(forKey: "eCBT") as! Double if elapsedScoopTime > 0.0 || elapsedCleanBoxTime > 0.0 { scoopStartTime = defaults.object(forKey: "sST") as! TimeInterval cleanBoxStartTime = defaults.object(forKey: "cBST") as! TimeInterval } } }
450fa56d6f264ff3b7c6e1fddfc3d76f6756992e
[ "Swift" ]
1
Swift
salmeleh/litterBoxStatus
7c0d5acc4b97430577fb407b016769a23e18ff34
7a224d958811be9ccf08f31f35eb79c939d91038
refs/heads/master
<repo_name>masterchief410/meals-app<file_sep>/screens/CategoryMealsScreen.js import React from "react"; import { View, StyleSheet, FlatList } from "react-native"; import { CATEGORIES, MEALS } from "../data/dummy-data"; import CategoryMealGridTile from "../components/CategoryMealsGridTile"; import MealList from "../components/MealList"; const CategoryMealsScreen = (props) => { const catId = props.navigation.getParam("categoryId"); const selectedCategory = CATEGORIES.find((cat) => cat.id === catId); const displayedMeals = MEALS.filter( (meal) => meal.categoryIds.indexOf(catId) >= 0 ); return ( <MealList listData={displayedMeals} navigation={props.navigation} headerColor={selectedCategory.color} fontColor={"#000000"} /> ); }; CategoryMealsScreen.navigationOptions = (navigationData) => { const catId = navigationData.navigation.getParam("categoryId"); const selectedCategory = CATEGORIES.find((cat) => cat.id === catId); return { headerTitle: selectedCategory.title, headerStyle: { backgroundColor: selectedCategory.color, }, headerTintColor: "black", }; }; export default CategoryMealsScreen; <file_sep>/components/CategoryMealsGridTile.js import React from "react"; import { ImageBackground, Text, TouchableNativeFeedback, View, StyleSheet, } from "react-native"; import Card from "./Card"; import { LinearGradient } from "expo-linear-gradient"; import { FontAwesome5 } from "@expo/vector-icons"; import { MaterialIcons } from "@expo/vector-icons"; import { MaterialCommunityIcons } from "@expo/vector-icons"; const CategoryMealGridTile = (props) => { function Affordability() { if (props.item.affordability === "affordable") return ( <View style={styles.iconViewStyle}> <MaterialIcons name="attach-money" size={20} color="white" /> </View> ); else if (props.item.affordability === "pricey") return ( <View style={styles.iconViewStyle}> <MaterialIcons name="attach-money" size={20} color="white" /> <MaterialIcons name="attach-money" size={20} color="white" style={{ margin: -10, padding: -10 }} /> </View> ); else return ( <View style={styles.iconViewStyle}> <MaterialIcons name="attach-money" size={20} color="white" /> <MaterialIcons name="attach-money" size={20} color="white" style={{ margin: -10, padding: -10 }} /> <MaterialIcons name="attach-money" size={20} color="white" /> </View> ); } function Complexity() { if (props.item.complexity === "simple") return ( <View style={styles.iconViewStyle}> <FontAwesome5 name="star" size={16} color="white" /> </View> ); else if (props.item.complexity === "hard") return ( <View style={styles.iconViewStyle}> <FontAwesome5 name="star" size={16} color="white" /> <FontAwesome5 name="star" size={16} color="white" /> </View> ); else return ( <View style={styles.iconViewStyle}> <FontAwesome5 name="star" size={16} color="white" /> <FontAwesome5 name="star" size={16} color="white" /> <FontAwesome5 name="star" size={16} color="white" /> </View> ); } return ( <View style={styles.viewStyle}> <ImageBackground source={{ uri: props.item.imageURL }} resizeMode="cover" style={{ flex: 1, justifyContent: "center", width: "100%" }} > <TouchableNativeFeedback onPress={props.onSelectMeal}> <LinearGradient colors={["#00000000", "#222222c0"]}> <Card style={styles.cardStyle}> <Text style={styles.titleStyle}> {props.item.title} </Text> <View style={styles.iconViewStyle}> <FontAwesome5 name="hourglass" size={18} color="white" /> <Text style={styles.textStyle}> {" "} {props.item.duration} mins{" |"} </Text> <Affordability /> <Text style={styles.textStyle}>{"| "}</Text> <Complexity /> </View> </Card> </LinearGradient> </TouchableNativeFeedback> </ImageBackground> </View> ); }; const styles = StyleSheet.create({ textStyle: { textAlign: "right", fontFamily: "roboto-regular", fontSize: 14, color: "white", }, titleStyle: { textAlign: "right", fontFamily: "roboto-regular", fontSize: 21, color: "white", marginVertical: 3, }, cardStyle: { height: 150, justifyContent: "flex-end", alignItems: "flex-end", width: "100%", }, viewStyle: { marginVertical: 10, marginHorizontal: 20, overflow: "hidden", borderRadius: 10, }, iconViewStyle: { flexDirection: "row", justifyContent: "center", alignItems: "center", }, }); export default CategoryMealGridTile; <file_sep>/App.js import React, { useState } from "react"; import { enableScreens } from "react-native-screens"; import * as Font from "expo-font"; import AppLoading from "expo-app-loading"; import MealsNavigator from "./navigation/MealsNavigator"; enableScreens(true); const fetchFonts = () => { return Font.loadAsync({ "roboto-bold": require("./assets/fonts/Roboto/Roboto-Bold.ttf"), "roboto-medium": require("./assets/fonts/Roboto/Roboto-Medium.ttf"), "roboto-regular": require("./assets/fonts/Roboto/Roboto-Regular.ttf"), "roboto-light": require("./assets/fonts/Roboto/Roboto-Light.ttf"), }); }; export default function App() { const [fontLoaded, setFontLoaded] = useState(false); if (!fontLoaded) { return ( <AppLoading startAsync={fetchFonts} onFinish={() => setFontLoaded(true)} onError={(err) => console.log(err)} /> ); } return <MealsNavigator />; } <file_sep>/components/MealList.js import React from "react"; import { View, StyleSheet, FlatList, TextPropTypes } from "react-native"; import CategoryMealGridTile from "../components/CategoryMealsGridTile"; const MealList = (props) => { const renderMealItem = (itemData) => { return ( <CategoryMealGridTile item={itemData.item} onSelectMeal={() => props.navigation.navigate({ routeName: "MealDetail", params: { mealId: itemData.item.id, headerColor: props.headerColor, fontColor: props.fontColor, }, }) } /> ); }; return ( <View style={styles.list}> <FlatList style={{ width: "100%" }} data={props.listData} renderItem={renderMealItem} /> </View> ); }; const styles = StyleSheet.create({ list: { backgroundColor: "#000000", flex: 1, justifyContent: "center", alignItems: "center", width: "100%", }, }); export default MealList; <file_sep>/screens/MealDetailScreen.js import React from "react"; import { View, Text, StyleSheet, ImageBackground, SafeAreaView, SectionList, } from "react-native"; import { LinearGradient } from "expo-linear-gradient"; import { HeaderButtons, Item } from "react-navigation-header-buttons"; import { FontAwesome5, MaterialIcons, Ionicons } from "@expo/vector-icons"; import HeaderButton from "../components/CustomHeaderButton"; import { MEALS, CATEGORIES } from "../data/dummy-data"; function PrintTickOrCross(bool) { if (bool.bool === true) return ( <Ionicons name="checkmark" size={24} color="white" // style={{ marginHorizontal: -10 }} /> ); else return ( <Ionicons name="close" size={24} color="white" // style={{ marginHorizontal: 10 }} /> ); } const MealDetailScreen = (props) => { const mealId = props.navigation.getParam("mealId"); const selectedMeal = MEALS.find((meal) => meal.id === mealId); const DATA = [ { title: "Ingredients", data: selectedMeal.ingredients, }, { title: "Recipe", data: selectedMeal.steps, }, ]; const renderLine = (itemData) => { return ( <View style={{ flexDirection: "row", paddingHorizontal: 25, marginRight: 5, marginVertical: 2, }} > <Text style={{ flex: 0.09, ...styles.textStyle, textAlign: "left", marginRight: 5, }} > {itemData.index + 1} {"."} </Text> <Text style={{ flex: 0.91, ...styles.textStyle, textAlign: "left", marginRight: 2, }} > {itemData.item} </Text> </View> ); }; function Affordability() { if (selectedMeal.affordability === "affordable") return ( <View style={styles.iconViewStyle}> <MaterialIcons name="attach-money" size={20} color="white" /> </View> ); else if (selectedMeal.affordability === "pricey") return ( <View style={styles.iconViewStyle}> <MaterialIcons name="attach-money" size={20} color="white" /> <MaterialIcons name="attach-money" size={20} color="white" style={{ margin: -10, padding: -10 }} /> </View> ); else return ( <View style={styles.iconViewStyle}> <MaterialIcons name="attach-money" size={20} color="white" /> <MaterialIcons name="attach-money" size={20} color="white" style={{ margin: -10, padding: -10 }} /> <MaterialIcons name="attach-money" size={20} color="white" /> </View> ); } function Complexity() { if (selectedMeal.complexity === "simple") return ( <View style={styles.iconViewStyle}> <FontAwesome5 name="star" size={16} color="white" /> </View> ); else if (selectedMeal.complexity === "hard") return ( <View style={styles.iconViewStyle}> <FontAwesome5 name="star" size={16} color="white" /> <FontAwesome5 name="star" size={16} color="white" /> </View> ); else return ( <View style={styles.iconViewStyle}> <FontAwesome5 name="star" size={16} color="white" /> <FontAwesome5 name="star" size={16} color="white" /> <FontAwesome5 name="star" size={16} color="white" /> </View> ); } return ( <View style={styles.screen}> <View style={styles.cardStyle}> <ImageBackground source={{ uri: selectedMeal.imageURL }} resizeMode="cover" style={{ justifyContent: "flex-start", height: 220, }} > <LinearGradient colors={["#00000000", "#111111a0", "#222222"]} style={styles.linearGradient} > <Text style={styles.titleStyle}> {selectedMeal.title} </Text> <View style={styles.iconViewStyle}> <FontAwesome5 name="hourglass" size={18} color="white" /> <Text style={styles.textStyle}> {" "} {selectedMeal.duration} mins{" |"} </Text> <Affordability /> <Text style={styles.textStyle}>{"| "}</Text> <Complexity /> </View> </LinearGradient> </ImageBackground> <SafeAreaView style={{ flex: 1 }}> <SectionList ListHeaderComponent={ <View> <View style={{ flexDirection: "row", marginHorizontal: 10, justifyContent: "space-between", }} > <View style={styles.conditionsViewStyle}> <Text style={{ ...styles.textStyle, fontSize: 16, }} > Vegan </Text> <PrintTickOrCross bool={selectedMeal.isVegan} /> </View> <View style={styles.conditionsViewStyle}> <Text style={{ ...styles.textStyle, fontSize: 16, }} > Vegeterian </Text> <PrintTickOrCross bool={selectedMeal.isVegeterian} /> </View> </View> <View style={{ flexDirection: "row", margin: 10, justifyContent: "space-between", }} > <View style={styles.conditionsViewStyle}> <Text style={{ ...styles.textStyle, fontSize: 16, }} > Gluten Free </Text> <PrintTickOrCross bool={selectedMeal.isGlutenFree} /> </View> <View style={styles.conditionsViewStyle}> <Text style={{ ...styles.textStyle, fontSize: 16, }} > Lactose Free </Text> <PrintTickOrCross bool={selectedMeal.isLatoseFree} /> </View> </View> </View> } contentContainerStyle={{ paddingVertical: 20 }} sections={DATA} keyExtractor={(item, index) => index.toString() + item} renderItem={renderLine} renderSectionHeader={({ section: { title } }) => ( <Text style={{ ...styles.titleStyle, textAlign: "left", margin: 20, }} > {title} </Text> )} /> </SafeAreaView> </View> </View> ); }; MealDetailScreen.navigationOptions = (navigationData) => { const mealId = navigationData.navigation.getParam("mealId"); const selectedMeal = MEALS.find((meal) => meal.id === mealId); const headerColor = navigationData.navigation.getParam("headerColor"); const fontColor = navigationData.navigation.getParam("fontColor"); return { headerTitle: selectedMeal.title, headerRight: () => ( <HeaderButtons HeaderButtonComponent={HeaderButton}> <Item title="Favorite" iconName="heart-outline" onPress={() => { console.log("Favorited"); }} color={fontColor} /> </HeaderButtons> ), headerTintColor: fontColor, headerStyle: { backgroundColor: headerColor, }, }; }; const styles = StyleSheet.create({ screen: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#000000", }, cardStyle: { flex: 1, height: "100%", width: "90%", margin: 15, marginVertical: 25, backgroundColor: "#222222", borderRadius: 15, justifyContent: "flex-start", overflow: "hidden", }, viewStyle: { backgroundColor: "#00000060", height: 220, overflow: "hidden", padding: 15, justifyContent: "flex-end", alignItems: "flex-end", }, linearGradient: { height: 220, overflow: "hidden", padding: 15, justifyContent: "flex-end", alignItems: "flex-end", }, titleStyle: { textAlign: "right", fontFamily: "roboto-regular", fontSize: 25, color: "white", marginVertical: 3, }, iconViewStyle: { flexDirection: "row", justifyContent: "flex-start", alignItems: "center", }, textStyle: { textAlign: "right", fontFamily: "roboto-light", fontSize: 14, color: "white", }, conditionsViewStyle: { flex: 1, flexDirection: "row", justifyContent: "space-between", marginHorizontal: 20, }, }); export default MealDetailScreen; <file_sep>/screens/FavouritesScreen.js import React from "react"; import { MEALS, FAVOURITES } from "../data/dummy-data"; import MealList from "../components/MealList"; import { HeaderButtons, Item } from "react-navigation-header-buttons"; import HeaderButton from "../components/CustomHeaderButton"; const FavouritesScreen = (props) => { const displayedMeals = MEALS.filter( (meal) => FAVOURITES.indexOf(meal.id) >= 0 ); return ( <MealList listData={displayedMeals} navigation={props.navigation} headerColor={"#222222"} fontColor={"#ffffff"} /> ); }; FavouritesScreen.navigationOptions = (navData) => { return { headerLeft: () => ( <HeaderButtons HeaderButtonComponent={HeaderButton}> <Item title="Menu" iconName="ios-menu" color="#ffffff" onPress={() => { navData.navigation.toggleDrawer(); }} /> </HeaderButtons> ), }; }; export default FavouritesScreen;
3fa898ae15c31d3ba2a72ddba513f1b6644798e9
[ "JavaScript" ]
6
JavaScript
masterchief410/meals-app
b572783e15d3d9c47a50d56ff3abec729b66b6b4
84b9acc773d803889a1b376076a5fa668cb7a1ee
refs/heads/master
<repo_name>MrJaxK/OpenQR<file_sep>/OpenQR/SupFunction.h #pragma once #include"core.h" #include "FFTCore.h" #include"rs.hpp" #include"DataEncoder.h" #include"DataDecoder.h"<file_sep>/OpenQR/FFTCore.h // // Created by DxxK on 2017/11/21. // #ifndef OPENQR_FFTCORE_H #define OPENQR_FFTCORE_H #include <complex> #include <vector> enum fourier_transform_direction { ftdFunctionToSpectrum, ftdSpectrumToFunction }; #define INCORRECT_SPECTRUM_SIZE_FOR_FFT 1 #define UNSUPPORTED_FTD 2 void DiscreteFourierFast(const std::complex<double>* f, int i_max, std::complex<double>* F, fourier_transform_direction ftd); void DiscreteFourierFast2D(const std::complex<double>* f, int i_max, int j_max, std::complex<double>* F, fourier_transform_direction ftd); /* * This function convert input's cardlinality to 2^N */ std::vector<std::complex<double>> FastFourierTransform(const std::complex<double>* input, int inputNumber, fourier_transform_direction ftd); std::vector<std::complex<double>> FastConvolution(const std::vector<std::complex<double>>& lPoly,const std::vector<std::complex<double>>& rPoly); #endif //OPENQR_FFTCORE_H <file_sep>/OpenQR/Examples.cpp #include"Examples.h" #include"core.h" #include"SupFunction.h" //If u want to use the samples, //Please copy the functions inside the main function //cause some header files are not included in this file namespace openqr { void BMPIOTest() { //region BMPImageIO test //BMPImageIO<int> t; //Matrix<int> temp = t.ImageRead("no.bmp"); //cout << temp << endl; //BMP t("no.bmp"); //unsigned char R, G, B; //unsigned char gray; //BYTE* ImgValue_s = t.pixels; //cout << t.rows << " " << t.cols << endl; //for (int y = 0; y < t.rows; y++) { // for (int x = 0; x < t.cols; x++) { // R = ImgValue_s[3 * (t.cols*y + x) + 2]; // G = ImgValue_s[3 * (t.cols*y + x) + 1]; // B = ImgValue_s[3 * (t.cols *y + x) + 0]; // //cout << (int)R << " " << (int)G << " " << (int)B << endl; // gray = (R * 11 + G * 16 + B * 5) / 32; // define gray color // ImgValue_s[3 * (t.cols*y + x) + 2] = gray; // ImgValue_s[3 * (t.cols*y + x) + 1] = gray; // ImgValue_s[3 * (t.cols*y + x) + 0] = gray; // } //} //t.save("another.bmp"); //endregion } void ImageIOTest() { // region ImageIO test //ImageIO imageIO; // Matrix<int> mat = imageIO.ImageRead<int>("no.bmp"); //for (int x = 0; x < 1000; ++x) // for (int j = 0; j < 100; ++j) // mat(x, j) = 0; // if (imageIO.ImageSave("another1.bmp", mat)) // cout << "Done" << endl; //else // cout << "Save fail" << endl; //Matrix<int> mat2(500,300,130); //if (imageIO.ImageSave("pure.bmp", mat2)) // cout << "Done" << endl; //else // cout << "Save fail" << endl; // endregion } void FastFourierTransTest() { //complex<double>a[5],b[5],c[5]; // for(int i=0;i<5;++i) // a[i]=i+1; // FastFourierTransform(a,5,b,fourier_transform_direction::ftdSpectrumToFunction); // for(int i=0;i<5;++i) // cout<<b[i]<<endl; // cout<<endl; // FastFourierTransform(b,5,c,fourier_transform_direction::ftdFunctionToSpectrum); // for(int i=0;i<5;++i) // cout<<c[i]<<endl; } void GenerateRSCodeword() { //DataEncoder da; //string encodeWith2_QStandard = da.Encode2_Q("openqr"); //const int MessageLength = 22; //uint8_t EncodeCoeff[22]; //for (int i = 0; i < 22; ++i) //{ // string temp = encodeWith2_QStandard.substr(8 * i, 8); // bitset<8>tempBit(temp); // //cout << temp << " " << tempBit.to_ulong() << endl; // cout << tempBit.to_ulong() << ","; // EncodeCoeff[i] = tempBit.to_ulong(); //} //cout << endl; //const int EccLength = 22; ////char* encoded = new char[EccLength + MessageLength]; //uint8_t* encoded = new uint8_t[EccLength + MessageLength]; //RS::ReedSolomon<MessageLength, EccLength> rsencoder; //rsencoder.Encode(EncodeCoeff, encoded); //int standardEncoded[44]; //for (int i = 0; i < 44; ++i) //{ // standardEncoded[i] = encoded[i];//(encoded[i] + 256) % 256; //} //for (int i = 22; i < 44; ++i) //{ // cout << standardEncoded[i] << " "; //} //delete[] encoded; } void Generate2_QStandardQRCode() { //QRCode qr; ////qr.GenerateQRCode("OpEnQR"); //ImageIO io; //io.ImageSave("ModulePlaced.bmp", qr.BitConvertToGray()); //qr.GenerateQRCode("OPENQR MRK HELLOWORLD"); //io.ImageSave("bestMasked.bmp", qr.BitConvertToGray()); } void Decode2_QStandardQRCode() { QRCode qrGen; ImageIO io; qrGen.GenerateQRCode("$$OPENQR MRK HELLO world$$$"); io.ImageSave("scanQR.bmp", qrGen.BitConvertToGray()); Matrix<int> qrPic = io.ImageRead<int>("scanQR.bmp"); QRCode qrScan; for (int i = 0; i<16; ++i) for (int j = 0; j < 16; ++j) { qrPic(12 * 16 + i, 12 * 16 + j) = ~qrPic(12 * 16 + i, 12 * 16 + j); qrPic(13 * 16 + i, 12 * 16 + j) = ~qrPic(13 * 16 + i, 12 * 16 + j); qrPic(15 * 16 + i, 18 * 16 + j) = ~qrPic(15 * 16 + i, 18 * 16 + j); qrPic(14 * 16 + i, 13 * 16 + j) = ~qrPic(14 * 16 + i, 13 * 16 + j); } io.ImageSave("scanQRchanged.bmp", qrPic); std::cout << qrScan.DecodeQRCode(qrPic); } } <file_sep>/OpenQR/QRCode.cpp #include "QRCode.h" openqr::QRCode::QRCode() { MatrixDataInitlize(); } openqr::QRCode::QRCode(const std::string & message) { GenerateQRCode(message); } openqr::QRCode::~QRCode() { } //Origin: 25x25 matrix //Convert to 400x400 matrix openqr::Matrix<int> openqr::QRCode::BitConvertToGray() { return BitConvertToGray(functionPatterns); } openqr::Matrix<int> openqr::QRCode::BitConvertToGray(Matrix<int> mat) { Matrix<int>temp(mat); //Matrix<int>temp(dataAreaMask); for(int i=0;i<temp.getColNumber();++i) for (int j = 0; j < temp.getRowNumber(); ++j) { if (temp(i, j)==1)//1 is black temp(i, j) = 0;//Gray: Black:0 White:255 else if(temp(i,j)==0) temp(i, j) = 255; } Matrix<int>tempBig(400, 400); for(int x=0;x<temp.getColNumber();++x) for (int y = 0; y < temp.getRowNumber(); ++y) { for (int i = 16 * x; i < 16 * x + 16; ++i) for (int j = 16 * y; j < 16 * y + 16; ++j) tempBig(i, j) = temp(x, y); } return tempBig; } bool openqr::QRCode::GenerateQRCode(const std::string & message) { MatrixDataInitlize(); PlaceMessage(message); std::string LvQ_formatInfoString[8] = { "011010101011111","011000001101000", "011111100110001","011101000000110","010010010110100","010000110000011", "010111011011010","010101111101101" }; std::vector<Matrix<int>> maskedData(8); int evaluteCount[8] = { 0 }; int bestMaskNumber = 0; int minCount = 9999999; //Data masking for (int i = 0; i < 8; ++i) { maskedData[i].Resize(25, 25, 0); Matrix<int> dataMaskingPatterns = DataMasking(i); for (int x = 0; x < 25; ++x) { for (int y = 0; y < 25; ++y) { maskedData[i](x, y) = functionPatterns(x, y) ^ dataMaskingPatterns(x, y); } } int pos = 0; for (int y = 0; y <= 6; ++y) maskedData[i](8, y) = LvQ_formatInfoString[i][pos++] - '0'; for (int x = 17; x <25; ++x) maskedData[i](x, 16) = LvQ_formatInfoString[i][pos++] - '0'; pos = 0; for (int x = 0; x <= 8; ++x) { if (x != 6) maskedData[i](x, 16) = LvQ_formatInfoString[i][pos++] - '0'; } for (int y = 17; y <25; ++y) { if (y != 18) maskedData[i](8, y) = LvQ_formatInfoString[i][pos++] - '0'; } //Evalute all 8 penalties and confirm best MaskID evaluteCount[i] = EvaluteMaskQuality(maskedData[i]); if (evaluteCount[i] < minCount) { minCount = evaluteCount[i]; bestMaskNumber = i; } } maskMode = bestMaskNumber; functionPatterns = maskedData[bestMaskNumber]; return true; } std::string openqr::QRCode::DecodeQRCode(Matrix<int> mat) { if (mat.getColNumber() != 400 || mat.getRowNumber() != 400) throw("Matrix size unfit"); BinaryzationBigMat(mat); Demasking(); return DecodeCore(); } void openqr::QRCode::GenerateDataMaskTest() { for (int i = 0; i < 8; ++i) { Matrix<int> temp = DataMasking(i); ImageIO io; std::string fileName = std::to_string(i); fileName += ".bmp"; io.ImageSave(fileName, BitConvertToGray(temp)); } } void openqr::QRCode::GenerateQRCodeTest() { std::string message = "MrK"; MatrixDataInitlize(); PlaceMessage(message); std::string LvQ_formatInfoString[8] = { "011010101011111","011000001101000", "011111100110001","011101000000110","010010010110100","010000110000011", "010111011011010","010101111101101" }; std::vector<Matrix<int>> maskedData(8); int evaluteCount[8] = { 0 }; int bestMaskNumber = 0; int minCount = 9999999; for (int i = 0; i < 8; ++i) { maskedData[i].Resize(25, 25, 0); Matrix<int> dataMaskingPatterns = DataMasking(i); for (int x = 0; x < 25; ++x) { for (int y = 0; y < 25; ++y) { maskedData[i](x, y) = functionPatterns(x, y) ^ dataMaskingPatterns(x, y); } } int pos = 0; for (int y = 0; y <=6 ; ++y) { maskedData[i](8, y) = LvQ_formatInfoString[i][pos++]-'0'; } for (int x = 17; x <25; ++x) maskedData[i](x, 16) = LvQ_formatInfoString[i][pos++] - '0'; pos = 0; for (int x = 0; x <=8; ++x) { if (x != 6) maskedData[i](x, 16) = LvQ_formatInfoString[i][pos++]-'0'; } for (int y = 17; y <25; ++y) { if (y != 18) maskedData[i](8, y) = LvQ_formatInfoString[i][pos++] - '0'; } ImageIO io; std::string fileName = std::to_string(i); fileName = "data"+fileName+".bmp"; io.ImageSave(fileName, BitConvertToGray(maskedData[i])); //io.ImageSave("mask"+std::to_string(i)+".bmp", BitConvertToGray(dataMaskingPatterns)); //Evalute all 8 penalties and confirm best MaskID evaluteCount[i] = EvaluteMaskQuality(maskedData[i]); if (evaluteCount[i] < minCount) { minCount = evaluteCount[i]; bestMaskNumber = i; } } maskMode=bestMaskNumber; std::cout << "Mask Mode is: "<<maskMode << std::endl; functionPatterns=maskedData[bestMaskNumber]; } std::string openqr::QRCode::DecodeQRCodeTest(Matrix<int> mat) { //binaryzation MatrixDataInitlize(); functionPatterns.Resize(25, 25); maskMode = -1; const int threshold = 16 * 16 * 255 / 2; for (int x = 0; x < 400; x += 16) { for (int y = 0; y < 400; y += 16) { int totalGray = 0; for(int i=0;i<16;++i) for (int j = 0; j < 16; ++j) { totalGray += mat(x + i, y + j); } if (totalGray > threshold) { functionPatterns(x / 16, y / 16) = 0; } else { functionPatterns(x / 16, y / 16) = 1; } } } //Find mask mode //Asuming both of the mask mode codeword is correct std::string LvQ_formatInfoString[8] = { "011010101011111","011000001101000", "011111100110001","011101000000110","010010010110100","010000110000011", "010111011011010","010101111101101" }; std::string maskCodeword; for (int y = 0; y <= 6; ++y) maskCodeword+=functionPatterns(8, y)+'0'; for (int x = 17; x <25; ++x) maskCodeword+=functionPatterns(x, 16)+'0'; for(int i=0;i<8;++i) if (maskCodeword == LvQ_formatInfoString[i]) { maskMode = i; break; } //Demasking Matrix<int> mask = DataMasking(maskMode); for (int x = 0; x < 25; ++x) { for (int y = 0; y < 25; ++y) { functionPatterns(x, y) ^= mask(x, y); } } //Read message+Ecc std::string finalBits; for (int x = 24; x >= 7; x -= 2) { if (x % 4 == 0)//upwards { for (int y = 0; y < 25; ++y) { if (dataAreaMask(x, y) == 1) finalBits+=functionPatterns(x, y) + '0'; if (dataAreaMask(x - 1, y) == 1) finalBits+=functionPatterns(x - 1, y)+ '0'; } } else//downwards { for (int y = 24; y >= 0; --y) { if (dataAreaMask(x, y) == 1) finalBits+=functionPatterns(x, y) + '0'; if (dataAreaMask(x - 1, y) == 1) finalBits+=functionPatterns(x - 1, y) + '0'; } } } //After the Vertical Timing Pattern for (int x = 5; x >= 0; x -= 2) { if (x % 4 == 1)//upwards { for (int y = 0; y < 25; ++y) { if (dataAreaMask(x, y) == 1) finalBits+=functionPatterns(x, y) + '0'; if (dataAreaMask(x - 1, y) == 1) finalBits+=functionPatterns(x - 1, y) + '0'; } } else//downwards { for (int y = 24; y >= 0; --y) { if (dataAreaMask(x, y) == 1) finalBits+=functionPatterns(x, y) + '0'; if (dataAreaMask(x - 1, y) == 1) finalBits += functionPatterns(x - 1, y) + '0'; } } } //Correcting the message const int MessageLength = 22; const int EccLength = 22; uint8_t encoded[44]; for (int i = 0; i < 44; ++i) { std::string temp = finalBits.substr(8 * i, 8); std::bitset<8>tempBit(temp); encoded[i] = tempBit.to_ulong(); } RS::ReedSolomon<MessageLength, EccLength> rsDecoder; uint8_t repaired[22]; rsDecoder.Decode(encoded, repaired); std::string repairedMessage; for (int i = 0; i < 22; ++i) { std::bitset<8>tempBit(repaired[i]); repairedMessage += tempBit.to_string(); } //Decode Alphanumeric Mode codeword if (repairedMessage.substr(0, 4) != "0010") throw("Not supported encoded mode.\nOnly support Alphanumeric Mode"); std::bitset<9> characterCount(repairedMessage.substr(4, 9)); int messageSize = characterCount.to_ulong(); std::string finalMessage; //Starts form repairedMessage[13] DataDecoder decoder; int i = 0; for (; i < messageSize - 1; i+=2) { //All the letters are combined two by two. Each of the combination cost 11 bits std::bitset<11>tempBits(repairedMessage.substr(13 + 11 * (i / 2), 11)); int temp = tempBits.to_ulong(); finalMessage += decoder.ReverseMap(temp / 45) + decoder.ReverseMap(temp % 45); } //One letter in the end, 6 bits //last one letter if (i == messageSize - 1) { std::bitset<6>tempBits(repairedMessage.substr(13 + 11 * (i / 2), 6)); int temp = tempBits.to_ulong(); finalMessage += decoder.ReverseMap(temp); } std::cout << finalMessage; return finalMessage; } void openqr::QRCode::MatrixDataInitlize() { GenerateFunctionPatterns(); GenerateDataAreaMask(); } //Use 2-Q specification void openqr::QRCode::GenerateFunctionPatterns() { functionPatterns.Resize(25, 25, 100);//Default 100 to test AddFinderPatterns(0,24); AddFinderPatterns(0,6); AddFinderPatterns(25-7,24); AddSeparators(); AddAlignmentPatterns(18,6); ReserveFormatArea(); AddTimingPatterns(); //Add dark module functionPatterns(8, 7) = 1; //ReserveVersionArea(); } void openqr::QRCode::AddFinderPatterns(int x, int y) { for (int i = 0; i < 7; ++i) for (int j = 0; j < 7; ++j) functionPatterns(x + i, y - j) = 0; for (int i = 0; i < 7; ++i) { functionPatterns(x + i, y) = 1; functionPatterns(x + i, y - 6) = 1; } for (int j = 1; j < 6; ++j) { functionPatterns(x, y - j) = 1; functionPatterns(x + 6, y - j) = 1; } for (int i = 2; i <= 4; ++i) for (int j = 2; j <= 4; ++j) functionPatterns(x + i, y - j) = 1; } void openqr::QRCode::AddSeparators() { for (int x = 0; x <= 7; ++x) { functionPatterns(x, 7) = 0; functionPatterns(x, 17) = 0; } for (int yCount = 0; yCount < 7; ++yCount) { functionPatterns(7, yCount) = 0; functionPatterns(7, 18 + yCount) = 0; } for (int x = 17; x < 25; ++x) functionPatterns(x, 17) = 0; for (int y = 17; y < 25; ++y) functionPatterns(17, y) = 0; } void openqr::QRCode::AddAlignmentPatterns(int centerx,int centery) { for (int i = -2; i <= 2; ++i) for (int j = -2; j <= 2; ++j) functionPatterns(centerx + i, centery + j) = 0; functionPatterns(centerx, centery) = 1; for (int i = -2; i <= 2; ++i) { functionPatterns(centerx + i, centery + 2) = 1; functionPatterns(centerx + i, centery - 2) = 1; } for (int i = -1; i <= 1; ++i) { functionPatterns(centerx - 2, centery + i) = 1; functionPatterns(centerx + 2, centery + i) = 1; } } void openqr::QRCode::AddTimingPatterns() { for (int i = 1; i <= 9; ++i) functionPatterns(6, 7 + i) = i % 2; for (int i = 1; i <= 9; ++i) functionPatterns(7 + i, 18) = i % 2; } //Only For Version2 std::string openqr::QRCode::GenerateFinalBits(const std::string & message) { DataEncoder dataEncoder; std::string encodeWith2_QStandard = dataEncoder.Encode2_Q(message); const int MessageLength = 22; uint8_t EncodeCoeff[22]; for (int i = 0; i < 22; ++i) { std::string temp = encodeWith2_QStandard.substr(8 * i, 8); std::bitset<8>tempBit(temp); //std::cout << temp << " " << tempBit.to_ulong() << std::endl; EncodeCoeff[i] = tempBit.to_ulong(); } const int EccLength = 22; uint8_t* encoded = new uint8_t[EccLength + MessageLength]; RS::ReedSolomon<MessageLength, EccLength> rsencoder; rsencoder.Encode(EncodeCoeff, encoded); int standardEncoded[44]; std::string finalBits; for (int i = 0; i < 44; ++i) { standardEncoded[i] = encoded[i]; std::bitset<8>tempBit(standardEncoded[i]); finalBits += tempBit.to_string(); } //for (int i = 0; i < 44; ++i) //{ // std::string temp = finalBits.substr(8 * i, 8); // std::bitset<8>tempBit(temp); // std::cout << temp << " " << tempBit.to_ulong() << std::endl; //} //Add remainder bits finalBits += "0000000"; delete[] encoded; encoded = nullptr; return finalBits; } //Use gray 180 stand for reservation void openqr::QRCode::ReserveFormatArea() { for (int y = 0; y <= 6; ++y) functionPatterns(8, y) = 180; for (int x = 17; x < 25; ++x) functionPatterns(x, 16) = 180; for (int x = 0; x <= 8; ++x) functionPatterns(x, 16) = 180; for (int y = 17; y < 25; ++y) functionPatterns(8, y)=180; } void openqr::QRCode::ReserveVersionArea() { for (int x = 0; x < 6; ++x) for (int y = 8; y <= 10; ++y) functionPatterns(x, y) = 50; for (int x = 14; x <= 16; ++x) for (int y = 19; y < 25; ++y) functionPatterns(x, y) = 50; } void openqr::QRCode::GenerateDataAreaMask() { dataAreaMask.Resize(25, 25, 0); for(int i=0;i<25;++i) for (int j = 0; j < 25; ++j) { if (functionPatterns(i, j) == 100) dataAreaMask(i, j) = 1; } } void openqr::QRCode::PlaceMessage(const std::string & message) { std::string finalBits = GenerateFinalBits(message); int nowPos = 0; for (int x = 24; x >= 7; x -= 2) { if (x % 4 == 0)//upwards { for (int y = 0; y < 25; ++y) { if (functionPatterns(x, y) == 100) functionPatterns(x, y) = finalBits[nowPos++] - '0'; if (functionPatterns(x - 1, y) == 100) functionPatterns(x - 1, y) = finalBits[nowPos++] - '0'; } } else//downwards { for (int y = 24; y >= 0; --y) { if (functionPatterns(x, y) == 100) functionPatterns(x, y) = finalBits[nowPos++] - '0'; if (functionPatterns(x - 1, y) == 100) functionPatterns(x - 1, y) = finalBits[nowPos++] - '0'; } } } //After the Vertical Timing Pattern for (int x = 5; x >= 0; x -= 2) { if (x % 4 == 1)//upwards { for (int y = 0; y < 25; ++y) { if (functionPatterns(x, y) == 100) functionPatterns(x, y) = finalBits[nowPos++] - '0'; if (functionPatterns(x - 1, y) == 100) functionPatterns(x - 1, y) = finalBits[nowPos++] - '0'; } } else//downwards { for (int y = 24; y >= 0; --y) { if (functionPatterns(x, y) == 100) functionPatterns(x, y) = finalBits[nowPos++] - '0'; if (functionPatterns(x - 1, y) == 100) functionPatterns(x - 1, y) = finalBits[nowPos++] - '0'; } } } } void openqr::QRCode::AddFormatInformation() { AddFormatInformation(maskMode); } void openqr::QRCode::AddFormatInformation(int bestMaskID) { std::string LvQ_formatInfoString[8] = { "011010101011111","011000001101000", "011111100110001","011101000000110","010010010110100","010000110000011", "010111011011010","010101111101101" }; int pos = 0; for (int y = 0; y < 7; ++y) { functionPatterns(8, y) = LvQ_formatInfoString[bestMaskID][pos++]; } for (int x = 17; x < 25; ++x) functionPatterns(x, 16) = LvQ_formatInfoString[bestMaskID][pos++]; pos = 0; for (int x = 0; x <= 8; ++x) { if (x != 6) functionPatterns(x, 16) = LvQ_formatInfoString[bestMaskID][pos++]; } for (int y = 17; y < 25; ++y) { if(y!=18) functionPatterns(8, y) = LvQ_formatInfoString[bestMaskID][pos++]; } } void openqr::QRCode::MaskingEvalute() { std::vector<Matrix<int>> maskedData(8); int bestMaskNumber = 0; for (int i = 0; i < 8; ++i) { maskedData[i].Resize(25, 25, 0); Matrix<int> dataMaskingPatterns = DataMasking(i); for (int x = 0; x < 25; ++x) { for (int y = 0; y < 25; ++y) { maskedData[i](x, y) = functionPatterns(x, y) ^ dataMaskingPatterns(x, y); } } //ImageIO io; //std::string fileName = std::to_string(i); //fileName += "data.bmp"; //io.ImageSave(fileName, BitConvertToGray(maskedData[i])); //Evalute all 8 penalties and confirm best MaskID //maskMode=bestMaskNumber; //functionPattrens=maskedData[bestMaskNumber]; } } int openqr::QRCode::EvaluteMaskQuality(Matrix<int> masked) { int total = 0; //Penalty Rule 1 int penalty1 = 0; //Check rows for (int y = 0; y < 25; ++y) { int first = 0, last = 0; for (int x = 1; x < 25; ++x) { if (masked(x, y) == masked(x - 1, y)) last = x; else { if (last - first >= 4) penalty1 += last - first - 1; else { first = x; last = x; } } } //x==24. Boundary conditions if (last - first >= 4) penalty1 += last - first - 1; } //Check column for (int x = 0; x < 25; ++x) { int first = 0, last = 0; for (int y = 1; y < 25; ++y) { if (masked(x, y) == masked(x , y - 1)) last = y; else { if (last - first >= 4) penalty1 += last - first - 1; else { first = y; last = y; } } } //y==24 if (last - first >= 4) penalty1 += last - first - 1; } //Penalty Rule 2 int penalty2 = 0; for (int x = 0; x < 24; ++x) { for (int y = 0; y < 24; ++y) { if (masked(x, y) == masked(x, y + 1) && masked(x + 1, y) == masked(x, y) && masked(x, y) == masked(x + 1, y + 1)) penalty2 += 3; } } //Penalty Rule 3 int penalty3 = 0; const int rulePattern[2][11] = { {1,0,1,1,1,0,1,0,0,0,0},{0,0,0,0,1,0,1,1,1,0,1} }; //Check row for (int y = 0; y < 25; ++y) { for (int x = 0; x <= 14; ++x) { for (int index = 0; index < 2; ++index) { bool flag = true; for (int i = 0; i < 11; ++i) { if (masked(x + i, y) != rulePattern[index][i]) { flag = false; break; } } if (flag) penalty3 += 40; } } } //Check column for (int x = 0; x < 25; ++x) { for (int y = 0; y <= 14; ++y) { for (int index = 0; index < 2; ++index) { bool flag = true; for (int i = 0; i < 11; ++i) { if (masked(x , y + i) != rulePattern[index][i]) { flag = false; break; } } if (flag) penalty3 += 40; } } } //Penalty Rule 4 int penalty4 = 0; const int totalMods = 25 * 25; int darkMods = 0; for (int x = 0; x < 25; ++x) for (int y = 0; y < 25; ++y) darkMods += masked(x, y); double darkRatio = 100 * darkMods / totalMods;// darkRatio% int darkRatioInt = static_cast<int>(darkRatio); int d5 = darkRatioInt / 5; int prev = d5 * 5; int next = d5 * 5 + 5; prev = abs(prev - 50) / 5; next = abs(next - 50) / 5; penalty4 = (prev > next ? next : prev) * 10; total = penalty1 + penalty2 + penalty3 + penalty4; return total; } openqr::Matrix<int> openqr::QRCode::DataMasking(int maskNumber) { int row = 24; int column = 24; Matrix<int> mask(25, 25, 0); switch (maskNumber) { case 0: for (int x = 0; x < 25; ++x) for (int y = 0; y < 25; ++y) { int col = x; int row = 24 - y; if ((row + col) % 2 == 0) mask(x, y) = 1; } break; case 1: for (int x = 0; x < 25; ++x) for (int y = 0; y < 25; ++y) { int col = x; int row = 24 - y; if (row % 2 == 0) mask(x, y) = 1; } break; case 2: for (int x = 0; x < 25; ++x) for (int y = 0; y < 25; ++y) { int col = x; int row = 24 - y; if (col % 3 == 0) mask(x, y) = 1; } break; case 3: for (int x = 0; x < 25; ++x) for (int y = 0; y < 25; ++y) { int col = x; int row = 24 - y; if ((row+col) % 3 == 0) mask(x, y) = 1; } break; case 4: for (int x = 0; x < 25; ++x) for (int y = 0; y < 25; ++y) { int col = x; int row = 24 - y; if ((row/2 + col/3) % 2 == 0) mask(x, y) = 1; } break; case 5: for (int x = 0; x < 25; ++x) for (int y = 0; y < 25; ++y) { int col = x; int row = 24 - y; if (((row*col)%2)+((row*col)%3) == 0) mask(x, y) = 1; } break; case 6: for (int x = 0; x < 25; ++x) for (int y = 0; y < 25; ++y) { int column = x; int row = 24 - y; if ((((row * column) % 2) + ((row * column) % 3))% 2 == 0) mask(x, y) = 1; } break; case 7: for (int x = 0; x < 25; ++x) for (int y = 0; y < 25; ++y) { int column = x; int row = 24 - y; if ((((row + column) % 2) + ((row * column) % 3)) % 2 == 0) mask(x, y) = 1; } break; } for(int i=0;i<25;++i) for (int j = 0; j < 25; ++j) { mask(i, j) = mask(i, j)&dataAreaMask(i, j); } return mask; } inline std::string openqr::QRCode::DecodeCore() { //Read message+Ecc std::string finalBits; for (int x = 24; x >= 7; x -= 2) { if (x % 4 == 0)//upwards { for (int y = 0; y < 25; ++y) { if (dataAreaMask(x, y) == 1) finalBits += functionPatterns(x, y) + '0'; if (dataAreaMask(x - 1, y) == 1) finalBits += functionPatterns(x - 1, y) + '0'; } } else//downwards { for (int y = 24; y >= 0; --y) { if (dataAreaMask(x, y) == 1) finalBits += functionPatterns(x, y) + '0'; if (dataAreaMask(x - 1, y) == 1) finalBits += functionPatterns(x - 1, y) + '0'; } } } //After the Vertical Timing Pattern for (int x = 5; x >= 0; x -= 2) { if (x % 4 == 1)//upwards { for (int y = 0; y < 25; ++y) { if (dataAreaMask(x, y) == 1) finalBits += functionPatterns(x, y) + '0'; if (dataAreaMask(x - 1, y) == 1) finalBits += functionPatterns(x - 1, y) + '0'; } } else//downwards { for (int y = 24; y >= 0; --y) { if (dataAreaMask(x, y) == 1) finalBits += functionPatterns(x, y) + '0'; if (dataAreaMask(x - 1, y) == 1) finalBits += functionPatterns(x - 1, y) + '0'; } } } //Correcting the message const int MessageLength = 22; const int EccLength = 22; uint8_t encoded[44]; for (int i = 0; i < 44; ++i) { std::string temp = finalBits.substr(8 * i, 8); std::bitset<8>tempBit(temp); encoded[i] = tempBit.to_ulong(); } RS::ReedSolomon<MessageLength, EccLength> rsDecoder; uint8_t repaired[22]; rsDecoder.Decode(encoded, repaired); std::string repairedMessage; for (int i = 0; i < 22; ++i) { std::bitset<8>tempBit(repaired[i]); repairedMessage += tempBit.to_string(); } //Decode Alphanumeric Mode codeword if (repairedMessage.substr(0, 4) != "0010") throw("Not supported encoded mode.\nOnly support Alphanumeric Mode"); std::bitset<9> characterCount(repairedMessage.substr(4, 9)); int messageSize = characterCount.to_ulong(); std::string finalMessage; //Starts form repairedMessage[13] DataDecoder decoder; int i = 0; for (; i < messageSize - 1; i += 2) { //All the letters are combined two by two. Each of the combination cost 11 bits std::bitset<11>tempBits(repairedMessage.substr(13 + 11 * (i / 2), 11)); int temp = tempBits.to_ulong(); finalMessage += decoder.ReverseMap(temp / 45) + decoder.ReverseMap(temp % 45); } //One letter in the end, 6 bits //last one letter if (i == messageSize - 1) { std::bitset<6>tempBits(repairedMessage.substr(13 + 11 * (i / 2), 6)); int temp = tempBits.to_ulong(); finalMessage += decoder.ReverseMap(temp); } return finalMessage; } //std::string openqr::QRCode::DecodeCore(Matrix<int> mat) //{ // if (mat.getRowNumber() != 25 || mat.getColNumber() != 25) // throw("Mat size unfit"); // //Read message+Ecc // std::string finalBits; // for (int x = 24; x >= 7; x -= 2) // { // if (x % 4 == 0)//upwards // { // for (int y = 0; y < 25; ++y) // { // if (dataAreaMask(x, y) == 1) // finalBits += mat(x, y) + '0'; // if (dataAreaMask(x - 1, y) == 1) // finalBits += mat(x - 1, y) + '0'; // } // } // else//downwards // { // for (int y = 24; y >= 0; --y) // { // if (dataAreaMask(x, y) == 1) // finalBits += mat(x, y) + '0'; // if (dataAreaMask(x - 1, y) == 1) // finalBits += mat(x - 1, y) + '0'; // } // } // } // //After the Vertical Timing Pattern // for (int x = 5; x >= 0; x -= 2) // { // if (x % 4 == 1)//upwards // { // for (int y = 0; y < 25; ++y) // { // if (dataAreaMask(x, y) == 1) // finalBits += mat(x, y) + '0'; // if (dataAreaMask(x - 1, y) == 1) // finalBits += mat(x - 1, y) + '0'; // } // } // else//downwards // { // for (int y = 24; y >= 0; --y) // { // if (dataAreaMask(x, y) == 1) // finalBits += mat(x, y) + '0'; // if (dataAreaMask(x - 1, y) == 1) // finalBits += mat(x - 1, y) + '0'; // } // } // } // //Correcting the message // const int MessageLength = 22; // const int EccLength = 22; // uint8_t encoded[44]; // for (int i = 0; i < 44; ++i) // { // std::string temp = finalBits.substr(8 * i, 8); // std::bitset<8>tempBit(temp); // encoded[i] = tempBit.to_ulong(); // } // RS::ReedSolomon<MessageLength, EccLength> rsDecoder; // uint8_t repaired[22]; // rsDecoder.Decode(encoded, repaired); // std::string repairedMessage; // for (int i = 0; i < 22; ++i) // { // std::bitset<8>tempBit(repaired[i]); // repairedMessage += tempBit.to_string(); // } // //Decode Alphanumeric Mode codeword // if (repairedMessage.substr(0, 4) != "0010") // throw("Not supported encoded mode.\nOnly support Alphanumeric Mode"); // std::bitset<9> characterCount(repairedMessage.substr(4, 9)); // int messageSize = characterCount.to_ulong(); // std::string finalMessage; // //Starts form repairedMessage[13] // DataDecoder decoder; // int i = 0; // for (; i < messageSize - 1; i += 2) // { // //All the letters are combined two by two. Each of the combination cost 11 bits // std::bitset<11>tempBits(repairedMessage.substr(13 + 11 * (i / 2), 11)); // int temp = tempBits.to_ulong(); // finalMessage += decoder.ReverseMap(temp / 45) + decoder.ReverseMap(temp % 45); // } // //One letter in the end, 6 bits // //last one letter // if (i == messageSize - 1) // { // std::bitset<6>tempBits(repairedMessage.substr(13 + 11 * (i / 2), 6)); // int temp = tempBits.to_ulong(); // finalMessage += decoder.ReverseMap(temp); // } //} void openqr::QRCode::BinaryzationBigMat(Matrix<int> mat) { //binaryzation MatrixDataInitlize(); functionPatterns.Resize(25, 25); maskMode = -1; const int threshold = 16 * 16 * 255 / 2; for (int x = 0; x < 400; x += 16) { for (int y = 0; y < 400; y += 16) { int totalGray = 0; for (int i = 0; i<16; ++i) for (int j = 0; j < 16; ++j) { totalGray += mat(x + i, y + j); } if (totalGray > threshold) { functionPatterns(x / 16, y / 16) = 0; } else { functionPatterns(x / 16, y / 16) = 1; } } } } void openqr::QRCode::Demasking() { //Find mask mode //Asuming both of the mask mode codeword is correct std::string LvQ_formatInfoString[8] = { "011010101011111","011000001101000", "011111100110001","011101000000110","010010010110100","010000110000011", "010111011011010","010101111101101" }; std::string maskCodeword; for (int y = 0; y <= 6; ++y) maskCodeword += functionPatterns(8, y) + '0'; for (int x = 17; x <25; ++x) maskCodeword += functionPatterns(x, 16) + '0'; for (int i = 0; i<8; ++i) if (maskCodeword == LvQ_formatInfoString[i]) { maskMode = i; break; } //Demasking Matrix<int> mask = DataMasking(maskMode); for (int x = 0; x < 25; ++x) { for (int y = 0; y < 25; ++y) { functionPatterns(x, y) ^= mask(x, y); } } } <file_sep>/OpenQR/IImageIO.hpp #pragma once #include"IImageIn.hpp" #include"IImageOut.hpp" #include"Matrix.hpp" #include<string> namespace openqr { template<typename T> class IImageIO:public IImageIn<T>,public IImageOut<T> { public: IImageIO(); //Return a Matrix contains gray scale image virtual Matrix<T> ImageRead(const std::string& filePath)override= 0; //Unnecessary function, but need to overload virtual bool ImageSave(const std::string& filePath,Matrix<T>& mat)override = 0; ~IImageIO(); }; template<typename T> inline IImageIO<T>::IImageIO() { } template<typename T> inline IImageIO<T>::~IImageIO() { } } <file_sep>/OpenQR/ImageIO.hpp #pragma once ///This field contains all *ImageIO.hpp #include"BMPImageIO.hpp" //.... #include"core.h" #include<string> #include<algorithm> namespace openqr { class ImageIO { public: ImageIO(); template<typename T> Matrix<T> ImageRead(const std::string& filePath); template<typename T> bool ImageSave(const std::string& filePath, Matrix<T> mat); ~ImageIO(); private: enum ImageType { BMP, JPG, GIF, PNG, UNKNOWN }; private: ImageType ImageTypeCheck(const std::string& filePath) { std::string fileSuffix = filePath.substr(filePath.find_last_of(".") + 1); transform(fileSuffix.begin(), fileSuffix.end(), fileSuffix.begin(), ::tolower); ImageType fileType; if (fileSuffix == "bmp") fileType = ImageType::BMP; else fileType=ImageType::UNKNOWN; return fileType; } template<typename T> IImageIO<T>* ImageTypeSet(ImageType& type); }; inline ImageIO::ImageIO() { } inline ImageIO::~ImageIO() { } template<typename T> inline Matrix<T> ImageIO::ImageRead(const std::string & filePath) { ImageType type = ImageTypeCheck(filePath); IImageIO<T>* imageProcesser=ImageTypeSet<T>(type); Matrix<T> matImage = imageProcesser->ImageRead(filePath); delete imageProcesser; imageProcesser = nullptr; return matImage; } template<typename T> inline bool ImageIO::ImageSave(const std::string & filePath,Matrix<T> mat) { ImageType type = ImageTypeCheck(filePath); IImageIO<T>* imageProcesser = ImageTypeSet<T>(type); bool saveFlag = imageProcesser->ImageSave(filePath, mat); delete imageProcesser; imageProcesser = nullptr; return saveFlag; } template<typename T> inline IImageIO<T>* ImageIO::ImageTypeSet(ImageType & type) { if (type == ImageType::BMP) return new BMPImageIO<T>(); else return nullptr; } }<file_sep>/OpenQR/QRCode.h #pragma once #include<cmath> #include"core.h" #include"DataEncoder.h" #include"SupFunction.h" #include<string> #include<bitset> namespace openqr { class QRCode { public: QRCode(); QRCode(const std::string& message); ~QRCode(); Matrix<int> BitConvertToGray(); Matrix<int> BitConvertToGray(Matrix<int> mat); bool GenerateQRCode(const std::string& message); //Only accept 400*400 mat std::string DecodeQRCode(Matrix<int> mat); //This function is used for general usage //TODO: finish this function //inline std::string DecodeCore(Matrix<int> mat); //Test functions public: void GenerateDataMaskTest(); void GenerateQRCodeTest(); std::string DecodeQRCodeTest(Matrix<int> mat); //Vars //private: public: Matrix<int>functionPatterns; Matrix<int>dataAreaMask; int maskMode; //Initlize functions private: void MatrixDataInitlize(); void GenerateFunctionPatterns();//Use 2-Q specification void AddFinderPatterns(int x,int y); void AddSeparators(); void AddAlignmentPatterns(int centerx,int centery); void AddTimingPatterns(); //Only For Version2 std::string GenerateFinalBits(const std::string& message); /* *Use gray 180 stand for reservation *Use this function before Adding Timing Patterns */ void ReserveFormatArea(); /* *Use gray 50 stand for reservation */ void ReserveVersionArea(); /* * This function must be used * instantly after the GenerateFunctionPatterns() is called */ void GenerateDataAreaMask(); void PlaceMessage(const std::string& message); void AddFormatInformation(); void AddFormatInformation(int bestMaskID); //Data masking functions private: void MaskingEvalute(); int EvaluteMaskQuality(Matrix<int> masked); Matrix<int> DataMasking(int maskNumber); //Decode functions private: //Accept 2Q standard QRCode inline std::string DecodeCore(); //Chage functionPatterns to standard 25*25 and binary matrix inline void BinaryzationBigMat(Matrix<int> mat); void Demasking(); }; } <file_sep>/OpenQR/Matrix.hpp #pragma once #include<vector> #include <iostream> #include <typeinfo> namespace openqr { template<typename T> class Matrix { public: ///default MatrixType: MatDouble Matrix(); Matrix(int rows, int cols, T defaultVal=0); Matrix(const Matrix&); Matrix& operator=(const Matrix&); //ATTENTION!!!!! //y cord //¡ü //¡ü //¡ü //¡ü //¡ü //¡¤ ¡ú ¡ú ¡ú ¡ú ¡ú ¡ú ¡ú ¡ú ¡ú ¡ú ¡ú ¡ú x cord //start from (0,0) //range x¡Ê[0, this.getColNumber()] //range y¡Ê[0, this.getRowNumber()]; inline T& operator()(int x,int y){return data[y][x]; } inline int getRowNumber(){return rowNumber;} inline int getColNumber(){return colNumber;} friend std::ostream& operator<<(std::ostream& os,Matrix& mat) { os<<"[ "; for(int i=0;i<mat.rowNumber;++i) { if(i!=0) os<<" "; for(int j=0;j<mat.colNumber;++j) os<<mat(i,j)<<" "; if(i!=mat.rowNumber-1) os<<std::endl; } os<<"]"<<std::endl; return os; } void Resize(int rows, int cols, T defaultVal = 0); ~Matrix(); private: std::vector<std::vector<T> >data; int rowNumber; int colNumber; inline void setRowColNumber(int row,int col); }; template<typename T> Matrix<T>::Matrix() :Matrix(0, 0) { } template<typename T> Matrix<T>::Matrix(int rows, int cols,T defaultVal) { Resize(rows, cols, defaultVal); } template<typename T> Matrix<T>::Matrix(const Matrix &rMat) { data = rMat.data; setRowColNumber(rMat.rowNumber,rMat.colNumber); } template<typename T> Matrix<T>& Matrix<T>::operator=(const Matrix &rMat) { data=rMat.data; setRowColNumber(rMat.rowNumber,rMat.colNumber); return *this; } template <typename T> void Matrix<T>::setRowColNumber(int row, int col) { rowNumber=row; colNumber=col; } //Set all value in this matrix to defaltval template<typename T> inline void Matrix<T>::Resize(int rows, int cols, T defaultVal) { data=std::vector<std::vector<T>>(rows, std::vector<T>(cols, defaultVal)); setRowColNumber(rows, cols); } template<typename T> Matrix<T>::~Matrix() { } } <file_sep>/OpenQR/DataDecoder.h #pragma once #include<string> #include<bitset> #include<vector> #include<algorithm> #include<cctype> #include"core.h" class DataDecoder { public: DataDecoder(); ~DataDecoder(); std::string ReverseMap(int i); }; <file_sep>/OpenQR/DataDecoder.cpp #include "DataDecoder.h" DataDecoder::DataDecoder() { } DataDecoder::~DataDecoder() { } std::string DataDecoder::ReverseMap(int i) { if (i < 0 || i>44) throw("para i Out of range"); std::string result; if (i >= 0 && i <= 9) { result += i + '0'; return result; } if (i >= 10 && i <= 35) { result += i - 10 + 'A'; return result; } const char* mapChar = " $%*+-./:"; if (i <= 44 && i >= 36) { result += mapChar[i - 36]; return result; } } <file_sep>/OpenQR/IImageOut.hpp #pragma once #include<string> #include"Matrix.hpp" namespace openqr { template<typename T> class IImageOut { public: IImageOut(); virtual bool ImageSave(const std::string& filePath,Matrix<T>& mat)=0; ~IImageOut(); }; template<typename T> inline IImageOut<T>::IImageOut() { } template<typename T> inline IImageOut<T>::~IImageOut() { } } <file_sep>/OpenQR/FFTCore.cpp // // Created by DxxK on 2017/11/21. // #include "FFTCore.h" const std::complex<double> I(0, 1); const double PI = 3.14159265358979323846; int reverseBits(unsigned short digitsCount, int value) { if (value >> digitsCount > 0) return -1; int res = 0; for (int d = 0; d < digitsCount; d++) { res = (res * 2 + (value % 2)); value /= 2; } return res; } void DiscreteFourierFast(const std::complex<double>* f, int i_max, std::complex<double>* F, fourier_transform_direction ftd) { if (i_max <= 0 || ((i_max & (i_max - 1)) != 0)) throw INCORRECT_SPECTRUM_SIZE_FOR_FFT; double norm, exp_dir; switch (ftd) { case ftdFunctionToSpectrum: norm = 1; exp_dir = -1; break; case ftdSpectrumToFunction: norm = 1.0 / i_max; exp_dir = 1; break; default: throw UNSUPPORTED_FTD; } int NN = i_max, digitsCount = 0; while (NN >>= 1) digitsCount++; // Allocating 2 buffers with n std::complex values std::complex<double>** buf = new std::complex<double>* [2]; for (int i = 0; i < 2; i++) { buf[i] = new std::complex<double>[i_max]; } // Grouping function values according to the binary-reversed index order int cur_buf = 0; for (int i = 0; i < i_max; i++) { buf[cur_buf][i] = f[reverseBits(digitsCount, i)]; } int exp_divider = 1; int different_exps = 2; int values_in_row = i_max / 2; int next_buf = 1; /* * Butterfly transfrom * Base 2 */ for (int step = 0; step < digitsCount; step++) { for (int n = 0; n < different_exps; n++) { std::complex<double> xp = exp((double)(exp_dir * PI * n / exp_divider) * I); for (int k = 0; k < values_in_row; k++) { std::complex<double>* pf = &buf[cur_buf][2 * k + (n % (different_exps / 2)) * (values_in_row * 2)]; buf[next_buf][n * values_in_row + k] = (*pf) + (*(pf + 1)) * xp; } } exp_divider *= 2; different_exps *= 2; values_in_row /= 2; cur_buf = next_buf; next_buf = (cur_buf + 1) % 2; } // Norming, saving the result for (int i = 0; i < i_max; i++) { F[i] = norm * buf[cur_buf][i]; } // Freeing our temporary buffers for (int i = 0; i < 2; i++) { delete [] buf[i]; } delete [] buf; } void DiscreteFourierFast2D(const std::complex<double>* f, int i_max, int j_max, std::complex<double>* F, fourier_transform_direction ftd) { std::complex<double>* phi = new std::complex<double>[i_max * j_max]; for (int m = 0; m < j_max; m++) { DiscreteFourierFast(&f[i_max * m], i_max, &phi[i_max * m], ftd); } std::complex<double>* phi_t = new std::complex<double>[j_max * i_max]; for (int p = 0; p < i_max; p++) for (int q = 0; q < j_max; q++) { phi_t[p * j_max + q] = phi[q * i_max + p]; } std::complex<double>* F_t = phi; for (int i = 0; i < i_max; i++) { DiscreteFourierFast(&phi_t[j_max * i], j_max, &F_t[j_max * i], ftd); } for (int q = 0; q < j_max; q++) for (int p = 0; p < i_max; p++) { F[q * i_max + p] = F_t[p * j_max + q]; } delete [] F_t; delete [] phi_t; } std::vector<std::complex<double>> FastFourierTransform(const std::complex<double>* input, int inputNumber, fourier_transform_direction ftd) { std::vector<std::complex<double>> outputVec; if(!(inputNumber & (inputNumber - 1)) != 0) { std::complex<double>* output; output=new std::complex<double>[inputNumber]; DiscreteFourierFast(input,inputNumber,output,ftd); outputVec.assign(output,output+inputNumber); } else { int iMax=log2(inputNumber)+1; iMax=1<<iMax; std::complex<double>* inputWithPow2=new std::complex<double>[iMax]; std::complex<double>* outputWithPow2=new std::complex<double>[iMax]; for(int i=0;i<inputNumber;++i) inputWithPow2[i]=input[i]; for(int i=inputNumber;i<iMax;++i) inputWithPow2[i]=0; DiscreteFourierFast(inputWithPow2,iMax,outputWithPow2,ftd); outputVec.assign(outputWithPow2,outputWithPow2+iMax); delete[] inputWithPow2; delete[] outputWithPow2; } return outputVec; } //TODO: Finish fast convolution, //TODO: remember the result's degree is lPoly's Degree + rPoly's degree std::vector<std::complex<double>> FastConvolution(const std::vector<std::complex<double>> &lPoly, const std::vector<std::complex<double>> &rPoly) { // std::vector<std::complex<double>> fftL,fftR; // fftL=FastFourierTransform(&lPoly[0],lPoly.size(),ftdFunctionToSpectrum); // fftR=FastFourierTransform(&rPoly[0],rPoly.size(),ftdFunctionToSpectrum); } <file_sep>/OpenQR/core.h #pragma once #include"Matrix.hpp" #include"IImageIO.hpp" #include"IImageIn.hpp" #include"IImageOut.hpp" #include"ImageIO.hpp" #include"QRCode.h"<file_sep>/OpenQR/Application.cpp #include<iostream> #include<vector> #include <complex> #include <cmath> #include"core.h" #include "SupFunction.h" using namespace std; using namespace openqr; int main() { QRCode qrGen; ImageIO io; qrGen.GenerateQRCode("sdlyyxy"); // io.ImageSave("scanQR.bmp",qrGen.BitConvertToGray()); // io.ImageSave("scanQR.bmp", qrGen.BitConvertToGray()); Matrix<int> qrPic = io.ImageRead<int>("scanQR.bmp"); QRCode qrScan; for(int i=0;i<16;++i) for (int j = 0; j < 16; ++j) { qrPic(12 * 16 + i, 12 * 16 + j) = ~qrPic(12 * 16 + i, 12 * 16 + j); qrPic(13 * 16 + i, 12 * 16 + j) = ~qrPic(13 * 16 + i, 12 * 16 + j); qrPic(15 * 16 + i, 18 * 16 + j) = ~qrPic(15 * 16 + i, 18 * 16 + j); qrPic(14 * 16 + i, 13 * 16 + j) = ~qrPic(14 * 16 + i, 13 * 16 + j); } io.ImageSave("scanQRchanged.bmp", qrPic); cout<<qrScan.DecodeQRCode(qrPic); // ImageIO io; // Matrix<int> changedQRPic = io.ImageRead<int>("scanQR.bmp"); // QRCode qrScan; // cout << qrScan.DecodeQRCode(changedQRPic); return 0; }<file_sep>/OpenQR/BMPImageIO.hpp #pragma once #include "core.h" #include <string> #include <cstdlib> #include "bmp.h" namespace openqr { template<typename T> class BMPImageIO :public IImageIO<T> { public: BMPImageIO(); ///return a Matrix contains converted to gray bitmap virtual Matrix<T> ImageRead(const std::string& filePath)override; virtual bool ImageSave(const std::string& filePath,Matrix<T>& mat)override; ~BMPImageIO(); private: Matrix<T> Convert2Gray(); void ConstructNewBMP(BMP* bmp,Matrix<T>& mat); private: BMP bmpData; }; template<typename T> BMPImageIO<T>::BMPImageIO() { } template<typename T> Matrix<T> openqr::BMPImageIO<T>::ImageRead(const std::string & filePath) { bmpData.load(filePath); return Convert2Gray(); } template<typename T> bool openqr::BMPImageIO<T>::ImageSave(const std::string & filePath,Matrix<T>& mat) { BMP* bmpSaveFile=new BMP(); ConstructNewBMP(bmpSaveFile,mat); if (bmpSaveFile->pixels == nullptr) return false; BYTE* ImgValue_s = bmpSaveFile->pixels; int height = bmpSaveFile->info->biHeight; int width = bmpSaveFile->info->biWidth; for (int y = 0; y <height; y++) { for (int x = 0; x < width; x++) { BYTE gray = mat(x,y); ImgValue_s[3 * (width*y + x) + 2] = gray; ImgValue_s[3 * (width*y + x) + 1] = gray; ImgValue_s[3 * (width*y + x) + 0] = gray; } } bool saveFlag=bmpSaveFile->save(filePath); delete bmpSaveFile; return saveFlag; } template<typename T> BMPImageIO<T>::~BMPImageIO() { } template<typename T> inline Matrix<T> BMPImageIO<T>::Convert2Gray() { Matrix<T> grayImg(bmpData.rows, bmpData.cols,-5); BYTE R, G, B; T gray; BYTE* ImgValue_s = bmpData.pixels; int height = bmpData.rows; int width = bmpData.cols; for (int y = 0; y <height; y++) { for (int x = 0; x < width; x++) { R = ImgValue_s[3 * (width*y + x) + 2]; G = ImgValue_s[3 * (width*y + x) + 1]; B = ImgValue_s[3 * (width*y + x) + 0]; //cout << (int)R << " " << (int)G << " " << (int)B << endl; gray = (R * 11 + G * 16 + B * 5) / 32; // define gray color grayImg(x,y) = gray; } } return grayImg; } template <typename T> void BMPImageIO<T>::ConstructNewBMP(BMP* bmpSaveFile,Matrix<T>& mat) { bmpSaveFile->head=new BITMAPFILEHEADER; bmpSaveFile->info = new BITMAPINFOHEADER; bmpSaveFile->head->bfType=0x4d42; //Only save 3 channels bmp image. In other words, biBitCount=24. bmpSaveFile->head->bfSize= 54+mat.getColNumber()*mat.getRowNumber()*3; bmpSaveFile->head->bfReserved1=0; bmpSaveFile->head->bfReserved2=0; bmpSaveFile->head->bfOffBits=54; bmpSaveFile->info->biSize=40; bmpSaveFile->info->biWidth=mat.getColNumber(); bmpSaveFile->info->biHeight=mat.getRowNumber(); bmpSaveFile->info->biPlanes=1; bmpSaveFile->info->biBitCount=24; bmpSaveFile->info->biCompression=0; bmpSaveFile->info->biSizeImage=mat.getRowNumber()*mat.getColNumber()*3; bmpSaveFile->info->biXPelsPerMeter=4724; bmpSaveFile->info->biYPelsPerMeter=4724; bmpSaveFile->info->biClrUsed=0; bmpSaveFile->info->biClrImportant=0; bmpSaveFile->rows=bmpSaveFile->info->biHeight; bmpSaveFile->cols=bmpSaveFile->info->biWidth; bmpSaveFile->channels=3; bmpSaveFile->palette= nullptr; bmpSaveFile->pixels=new BYTE[mat.getColNumber()*mat.getRowNumber()*3]; } } <file_sep>/OpenQR/CMakeLists.txt cmake_minimum_required(VERSION 3.7) project(OpenQR) set(CMAKE_CXX_STANDARD 11) #file(GLOB_RECURSE rw_module_source_list . "*.cpp" "*.c" "*.h" "*.hpp" "*.inl") #aux_source_directory(. rw_module_source_list) set(rw_module_source_list Application.cpp BMPImageIO.hpp DataDecoder.cpp DataDecoder.h core.h IImageIn.hpp IImageIO.hpp IImageOut.hpp bmp.cpp bmp.h ImageIO.hpp SupFunction.h Matrix.hpp FFTCore.h FFTCore.cpp DataEncoder.cpp DataEncoder.h Examples.cpp Examples.h poly.hpp QRCode.cpp QRCode.h rs.hpp gf.hpp) add_executable(OpenQR ${rw_module_source_list})<file_sep>/OpenQR/DataEncoder.cpp #include "DataEncoder.h" DataEncoder::DataEncoder() { } DataEncoder::~DataEncoder() { } std::string DataEncoder::Encode2_Q(const std::string & message) { if (message.size() > 29) throw("SIZE_OUT_OF_RANGE"); const int bitLength = 22 * 8; std::string anModeCode = AlphanumericModeEncoding(message); std::bitset<9> characterCount(message.size()); std::string appendModeIndi = "0010"+characterCount.to_string()+anModeCode; //Add a Terminator of 0s if Necessary int deltaLength = bitLength - appendModeIndi.length(); if (deltaLength <= 4) { for (int i = 0; i < deltaLength; ++i) appendModeIndi += "0"; } else appendModeIndi += "0000"; //Add More 0s to Make the Length a Multiple of 8 int mod8 = appendModeIndi.length() % 8; for (int i = 0; i < 8 - mod8; ++i) appendModeIndi += "0"; //Add Pad Bytes if the String is Still too Short const std::string repeat1 = "11101100"; const std::string repeat2 = "00010001"; int deltaBit = bitLength - appendModeIndi.length(); for (int i = 0; i < deltaBit / 8; ++i) { if (i % 2 == 0) appendModeIndi += repeat1; else appendModeIndi += repeat2; } return appendModeIndi; } std::string DataEncoder::AlphanumericModeEncoding(std::string message) { std::string result; std::transform(message.begin(), message.end(),message.begin(), ::toupper); int i = 0; for (; i < message.length()-1; i += 2) { unsigned long long temp = 45 * Map(message[i]) + Map(message[i + 1]); std::bitset<11> biTemp(temp); result += biTemp.to_string(); //result += " "; } if (i == message.length() - 1) { unsigned long long temp = Map(message[i]); std::bitset<6> biTemp(temp); result += biTemp.to_string(); //result += " "; } return result; } unsigned long long DataEncoder::Map(char a) { if (a <= '9'&&a >= '0') return a - '0'; if (a <= 'Z'&&a >= 'A') return a - 55; else { for (int i = 0; i <= 9; ++i) if (a == mapChar[i]) return i + 36; } return 100; } <file_sep>/OpenQR/Examples.h #pragma once void BMPIOTest(); void ImageIOTest(); void FastFourierTransTest(); void GenerateRsCodeword();<file_sep>/OpenQR/DataEncoder.h /* * Encode original data to fit QRCode version 2, EC level Q */ #pragma once #include<string> #include<bitset> #include<vector> #include<algorithm> #include<cctype> #include"core.h" class DataEncoder { public: DataEncoder(); ~DataEncoder(); std::string Encode2_Q(const std::string& message); private: std::string AlphanumericModeEncoding(std::string message); unsigned long long Map(char a); const char* mapChar = " $%*+-./:"; }; <file_sep>/OpenQR/IImageIn.hpp #pragma once #include<string> #include"Matrix.hpp" namespace openqr { template<typename T> class IImageIn { public: IImageIn(); virtual Matrix<T> ImageRead(const std::string& filePath) = 0; ~IImageIn(); }; template<typename T> inline IImageIn<T>::IImageIn() { } template<typename T> inline IImageIn<T>::~IImageIn() { } }
3826d9fbae0f001e1a5be78ebbee9f85b96572c0
[ "C", "CMake", "C++" ]
20
C
MrJaxK/OpenQR
aa5f1e1abd497c96660ab56e200b317496e5b410
88a83220e0b328d01a73b44daf37d015a06338bd
refs/heads/master
<repo_name>sergiosanchezs/Pythonbasic<file_sep>/Test.py ''' Client Requirements Functionalities: - Schedule Event - Display all event in month - Display overlapping events - Delete event - Modify event - Year from 2000 to 2025. ''' # from CalendarClasses import Event, Day, Month from CalendarClasses import * e1 = Event(12, 10, 14, 10, 'Meegin with Co-op advisor', 'Cestar College') e2 = Event(10, 4, 16, 10, 'Graduation', 'Lambton College') e3 = Event(20, 00, 22, 00, 'Watching Movie', 'Fairview Mall') e4 = Event(7, 0, 8, 00, 'Meeting for breakfast', 'Restaurant') d = Day('Monday', 12, 'October') d.addEvent(e1) d.addEvent(e2) # d.displayAllEvents() d2 = Day('Wednesday', 14, 'October') d2.addEvent(e3) d2.addEvent(e4) m = Month('October', 10) m.addDay(d) m.addDay(d2) m.displayEvents() <file_sep>/CalendarClasses.py class Event: def __init__(self, start_hr, start_min, finish_hr, finish_min, description, location): self.start_hr = start_hr self.start_min = start_min self.finish_hr = finish_hr self.finish_min = finish_min self.description = description self.location = location def displayEvent(self): return (''' --> From {}:{} To {}:{} Description: {} Location: {} -----------------------------------------''' .format(self.start_hr, self.start_min, self.finish_hr, self.finish_min, self.description, self.location)) # result = 'From ' + str(self.start_hr) + ':' + str(self.start_min) # result += ' To ' + str(self.start_hr) + ':' + str(self.start_min) + '\n' # result += 'Description: ' + self.description + '\n' # result += 'Location: ' + self.location + '\n' # result += '---------------------------------------------------' # return result class Day: def __init__(self, name, day_of_month, month_belong_to): self.name = name self.day_of_month = day_of_month self.month_belong_to = month_belong_to self.events = [] def addEvent(self, event): self.events.append(event) def displayAllEvents(self): print('\nAll events scheduled for: {}, {} {}'.format(self.name, self.day_of_month, self.month_belong_to)) for i in self.events: print(i.displayEvent()) class Month: def __init__(self, name, month_of_year): self.name = name self.month_of_year = month_of_year if month_of_year == 2: self.number_of_days = 28 elif month_of_year == 1 or month_of_year == 3 or month_of_year == 5 or month_of_year == 7 or month_of_year == 8 or month_of_year == 10 or month_of_year == 12: self.number_of_days = 31 else: self.number_of_days = 30 self.days =[] * self.number_of_days def addDay(self, day): self.days.insert(day.day_of_month-1, day) def displayEvents(self): # print('\nAll events scheduled for the month {}'.format(self.name)) for i in self.days: i.displayAllEvents() class Year: def __init__(self, year_number): self.year_number = year_number self.months = [] * 12 def addMonth(self, month): self.months.insert(month, month.month_of_year - 1) class Calendar: def __init__(self): self.years = [] def addYear(self, year): self.years.append(year) def initializeCalendar(self): for i in range(2000, 2025): y = Year(i) self.years.append(y) def addEvent(self): pass def DisplayAllEventsInMonth(self): pass def displayOverlappingEvents(self): pass def removeEvent(self): pass def editEvent(self): pass <file_sep>/Sergio_Calendar/Test.py from CalendarClasses import * c = Calendar() c.initializeCalendar() c.addEvent(12, 10, 14, 20, 'Meegin with Co-op advisor', 'Cestar College', 15, 12, 2019) print('END') <file_sep>/TeacherCalendar/CalendarClasses.py class Event: def __init__(self, start_hr, start_min, finish_hr, finish_min, description, location): self.start_hr = start_hr self.start_min = start_min self.finish_hr = finish_hr self.finish_min = finish_min self.description = description self.location = location def displayEvent(self): result = "From " + str(self.start_hr) + ":" + str(self.start_min) result += " To " + str(self.finish_hr) + ":" + str(self.finish_min) + "\n" result += "Description: " + str(self.description) + "\n" result += "Location: " + str(self.location) + "\n" result += "------------------------------------------------------------" return result class Day: def __init__(self, day_of_month): #self.name = name self.day_of_month = day_of_month self.events = [] # self.month_belong_to = month_belong_to def addEvent(self, event): self.events.append(event) def displayAllEvents(self): if len(self.events) > 0: print("All events scheduled for " + str(self.day_of_month) ) for i in self.events: print(i.displayEvent()) class Month: number_of_days = 30 def __init__(self, name, month_of_year): self.name = name self.month_of_year = month_of_year if month_of_year == 2: number_of_days = 28 elif month_of_year == 1 or month_of_year == 3 or month_of_year == 5 or month_of_year == 7 or month_of_year == 8 or month_of_year == 10 or month_of_year == 12: number_of_days = 31 else: number_of_days = 30 days = [] * number_of_days def addDay(self, day): self.days.insert(day.day_of_month-1, day) def displayEvents(self): for i in self.days: i.displayAllEvents() class Year: months = [Month] * 12 def __init__(self, year_number): self.year_number = year_number class Calendar: def __init__(self): self.years = [Year] * 25 def addYear(self, year): self.years.add(year) def initializeCalendar(self): #Creating years for i in range(2000, 2025): y = Year(i) self.years.append(y) my_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] for y in range(0, 25): for m in range(1, 13): tmp_month = Month(my_months[m], m) self.years[y].months.append(tmp_month) # Creating days and appending them to month for d in range(1, tmp_month.number_of_days): tmp_day = Day(d) tmp_month.days.append(tmp_day) def addEvent(self, start_hr, start_min, finish_hr, finish_min, description, location, dd, mm, yy): referred_year = self.years[yy - 2000] referred_month = referred_year.months[mm-1] referred_day = referred_month.days[dd-1] myEvent = Event(start_hr, start_min, finish_hr, finish_min, description, location) referred_day.addEvent(myEvent) print("Event added successfully") def displayAllEventsInMonth(self, mm, yy): referred_year = self.years[yy - 2000] referred_month = referred_year.months[mm - 1] for i in range(0, referred_month.number_of_days): referred_day = referred_month.days[i] referred_day.displayAllEvents() #def displayOverlappingEvents(self): #To be developed #def removeEvent(self): #To be developed #def editEvent(self): #To be developed <file_sep>/TeacherCalendar/Test.py from CalendarCLasses import * c = Calendar() c.initializeCalendar() c.addEvent(12, 10, 14, 30, "Graduation", "CeStar", 11, 5, 2019) c.addEvent(13, 10, 15, 10, "MidTerm", "Lambton", 9, 2, 2020) c.displayAllEventsInMonth(11, 2019)
a99ff6c76879abcd29e74c3ec46cafbe3efe2741
[ "Python" ]
5
Python
sergiosanchezs/Pythonbasic
dd77c71b5342f0709406f45a0e9d375552c784a9
de9577adfb155f99bc56d0a9bd69f797e7c3455f
refs/heads/main
<file_sep># -*- coding: utf-8 -*- """ Created on Tue Apr 16 21:58:19 2019 @author: dgns """ import cv2 import numpy as np import pandas as pd import matplotlib.pyplot as plt import random from os import listdir df_train = pd.read_csv('C:/Users/<NAME>/Desktop/train.csv') ## ana veri çağırıldı df_train.info() Y_train_orig = df_train['label'].values ## veriden etiketleri ayır X_train_orig = df_train.drop('label', axis=1).values ## veriden etiketleri ayır # Veriyi test val train için böl X_train= X_train_orig[0:14000,:].T X_val = X_train_orig[14000:28000,:].T X_test = X_train_orig[28000:42000,:].T Y = Y_train_orig.reshape(1, Y_train_orig.shape[0]) ## matris düzenlendi Y_train = Y[:,0:14000] Y_val = Y[:,14000:28000] Y_test = Y[:,28000:42000] Y_train_onehot = np.zeros((Y_train.max()+1, Y_train.shape[1])) Y_train_onehot[Y_train, np.arange(Y_train.shape[1])] = 1 print("Shape of Y_train_onehot:", Y_train_onehot.shape) #df_test = pd.read_csv('C:/Users/dgns/Desktop/test.csv') #X_test = df_test.values.T #X_test = X_test / 255. #X_test.shape ############################################################################## ##### fonksiyonlar def relu(z): z_relu = np.maximum(z, 0) activation_cache = (z) return z_relu, activation_cache def relu_derivative(z): z_derivative = np.zeros(z.shape) z_derivative[z > 0] = 1 return z_derivative def softmax(z): z_exp = np.exp(z - np.max(z)) z_softmax = z_exp / np.sum(z_exp, axis=0) activation_cache = (z) return z_softmax, activation_cache ###### parametreler ayarlanıyor def initialize_parameters(layers_dims): L = len(layers_dims) - 1 parameters = {} caches = {} for l in range(1, L+1): parameters["W"+str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * (1 / layers_dims[l-1]) parameters["b"+str(l)] = np.zeros((layers_dims[l], 1)) ## sıfır matrisi biaslar için oluştu return parameters ##### ileri propagasyon fonksiyonları ağırlık çarpımı ve bias toplamı hesabı def linear_forward(A_prev, W, b): Z = np.dot(W, A_prev) + b cache = (A_prev, W, b) return Z, cache ### aktivasyon ileri propagasyonu hesabı def activation_forward(A_prev, W, b, activation): Z, linear_cache = linear_forward(A_prev, W, b) if activation == 'relu': A, activation_cache = relu(Z) elif activation == 'softmax': A, activation_cache = softmax(Z) cache = (linear_cache, activation_cache) return A, cache ### ileri propagasyon modeli def L_forward_propagate(X, parameters): caches = [] L = len(parameters) // 2 A_prev = X for l in range(1, L): A, cache = activation_forward(A_prev, parameters["W"+str(l)], parameters["b"+str(l)], 'relu') A_prev = A caches.append(cache) AL, cache = activation_forward(A_prev, parameters["W"+str(L)], parameters["b"+str(L)], 'softmax') caches.append(cache) return AL, caches ###### hata hesaplama def compute_cost(Y, AL): m = Y.shape[1] cost = (1/m) * np.sum((AL - Y)*(AL - Y)) # cost = -(1/m) * np.sum(Y * np.log(AL) + (1-Y) * np.log(1-AL)) return cost ##### geri propagasyon fonksiyonları def linear_backward(dZ, linear_cache): (A_prev, W, b) = linear_cache m = A_prev.shape[1] dW = (1/m) * np.dot(dZ, A_prev.T) db = (1/m) * np.sum(dZ, axis=1, keepdims=True) dA_prev = np.dot(W.T, dZ) return dW, db, dA_prev def activation_backward(Y, cache, activation, A=0, dA=0): (linear_cache, activation_cache) = cache (Z) = activation_cache if activation == 'relu': dZ = dA * relu_derivative(Z) elif activation == 'softmax': dZ = A - Y dW, db, dA_prev = linear_backward(dZ, linear_cache) return dW, db, dA_prev def L_backward_propagate(X, Y, AL, parameters, caches): m = Y.shape[1] L = len(parameters) // 2 grads = {} cache = caches[L-1] dW, db, dA_prev = activation_backward(Y, cache, 'softmax', A = AL) grads["dW"+str(L)] = dW grads["db"+str(L)] = db dA = dA_prev for l in range(L-1, 0, -1): cache = caches[l-1] dW, db, dA_prev = activation_backward(Y, cache, 'relu', dA = dA) grads["dW"+str(l)] = dW grads["db"+str(l)] = db dA = dA_prev return grads ######## parametreler güncelleniyor def update_parameters(parameters, grads, learning_rate): L = len(parameters) // 2 params = {} for l in range(1, L+1): params["W"+str(l)] = parameters["W"+str(l)] - learning_rate * grads["dW"+str(l)] params["b"+str(l)] = parameters["b"+str(l)] - learning_rate * grads["db"+str(l)] return params ######### tahmin fonksiyonu def predict(X, parameters): A2, _ = L_forward_propagate(X, parameters) Y_predict = np.argmax(A2, axis=0) Y_predict = Y_predict.reshape(1, Y_predict.shape[0]) return Y_predict ######## yapau sinirağı modeli def model(X, Y, epochs=75, mini_batch_size=48, learning_rate=0.011): layers_dims = [X.shape[0], 64, 32, 16, Y.shape[0]] ### katman boyutları costs = [] beta = 0.9 parameters = initialize_parameters(layers_dims) ### parametreler ayarlanıyor for i in range(0, epochs): print("Epoch", i+1, ":") m = X.shape[1] permutation = np.random.permutation(m) X_shuffle = X[:, permutation] Y_shuffle = Y[:, permutation] num_mini_batch = m // mini_batch_size ## veri bölünür avg_cost = 0 for j in range(0, num_mini_batch): k = np.arange(0,28000,dtype=np.float) k[:] = 0.00 X_mini_batch = X_shuffle[:, (j*mini_batch_size) : (j+1)*mini_batch_size] Y_mini_batch = Y_shuffle[:, (j*mini_batch_size) : (j+1)*mini_batch_size] AL, caches = L_forward_propagate(X_mini_batch, parameters) cost = compute_cost(Y_mini_batch, AL) grads = L_backward_propagate(X_mini_batch, Y_mini_batch, AL, parameters, caches) parameters = update_parameters(parameters, grads, learning_rate) if cost <= 0.005: break if j % 5 == 0: op = "Cost(%5d/%5d): %3.6f" % ((j+1) * mini_batch_size, m, cost) print(op, end='\r') avg_cost = beta * avg_cost + (1 - beta) * cost costs.append(avg_cost) if m % mini_batch_size != 0: X_mini_batch = X_shuffle[:, (num_mini_batch*mini_batch_size):] Y_mini_batch = Y_shuffle[:, (num_mini_batch*mini_batch_size):] AL, caches = L_forward_propagate(X_mini_batch, parameters) cost = compute_cost(Y_mini_batch, AL) grads = L_backward_propagate(X_mini_batch, Y_mini_batch, AL, parameters, caches) parameters = update_parameters(parameters, grads, learning_rate) op = "Cost(%5d/%5d): %3.6f" % (m, m, cost) print(op, end='\r') if cost <= 0.005: break avg_cost = beta * avg_cost + (1 - beta) * cost costs.append(avg_cost) print() return parameters, costs , caches parameters, costs ,caches = model(X_train, Y_train_onehot, epochs=75, mini_batch_size=48) Y_train_predict = predict(X_train, parameters) Y_val_predict = predict(X_val,parameters) Y_test_predict = predict(X_test, parameters) Y_test_predict.shape def accuracy(Y2, Y_pred): tp = np.sum((Y2 == Y_pred).astype(int)) return tp / Y2.shape[1] acc = accuracy(Y_train, Y_train_predict) acc2 = accuracy(Y_val, Y_val_predict) acc3 = accuracy(Y_test, Y_test_predict) print("Accuracy on training data:", acc) print("Accuracy on val data:", acc2) print("Accuracy on test data:", acc3) ### testten resim çağırma dn = random.randint(0,14000) a = X_test[:,dn] a = a.reshape(28,28) plt.imshow(a) print("Y_test_predict:", Y_test_predict[0,dn]) fig = plt.figure() dn1 =random.randint(0,14000) p11 = X_test[:,dn1] p11 = p11.reshape(28,28) ax11 =plt.subplot(221) plt.imshow(p11) ax11.title.set_text(Y_test_predict[0,dn1]) dn2 =random.randint(0,14000) p21 = X_test[:,dn2] p21 = p21.reshape(28,28) ax21 =plt.subplot(222) plt.imshow(p21) ax21.title.set_text(Y_test_predict[0,dn2]) dn31 =random.randint(0,14000) p31 = X_test[:,dn31] p31 = p31.reshape(28,28) ax31 =plt.subplot(223) plt.imshow(p31) ax31.title.set_text(Y_test_predict[0,dn31]) dn4 =random.randint(0,14000) p41 = X_test[:,dn4] p41 = p41.reshape(28,28) ax41 =plt.subplot(224) plt.imshow(p41) ax41.title.set_text(Y_test_predict[0,dn4]) ############# kendi test verimizi düzenleyip ysa ya veririz. X_test2 = X_test[:,0] def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.2126, 0.7152, 0.0722]) path = "C:/Users/<NAME>/Desktop/7" images=listdir(path) img55 =[] for i in range (len(images)): img55 = cv2.imread("C:/Users/<NAME>/Desktop/7/"+images[i]) dim3 = (28, 28) resized = cv2.resize(img55, dim3, interpolation = cv2.INTER_AREA) graynrm = rgb2gray(resized) ## gray = rgb2gray(resized) gray= abs(graynrm-255) graynrm= (gray- np.min(gray)) / (np.max(gray)-np.min(gray)) for l in range (0,28): for b in range (0,28): if graynrm[l,b]< 0.2 : graynrm[l,b] = 0 else : graynrm[l,b] = 1 result=np.array(graynrm).flatten() X_test2=np.column_stack((X_test2, result)) Y_test_predict2 = predict(X_test2,parameters) fig = plt.figure() aa1= random.randint(0,len(images)) p1 = X_test2[:,aa1] p1 = p1.reshape(28,28) ax1 =plt.subplot(221) plt.imshow(p1) ax1.title.set_text(Y_test_predict2[0,aa1]) aa2= random.randint(0,len(images)) p2 = X_test2[:,aa2] p2 = p2.reshape(28,28) ax2 =plt.subplot(222) plt.imshow(p2) ax2.title.set_text(Y_test_predict2[0,aa2]) aa3=random.randint(0,len(images)) p3 = X_test2[:,aa3] p3 = p3.reshape(28,28) ax3 = plt.subplot(223) ax3.title.set_text(Y_test_predict2[0,aa3]) plt.imshow(p3) aa4=random.randint(0,len(images)) p4 = X_test2[:,aa4] p4 = p4.reshape(28,28) ax4 = plt.subplot(224) ax4.title.set_text(Y_test_predict2[0,aa4]) plt.imshow(p4) #plt.subplot_tool() plt.show() plt.plot(range(0, len(costs)*5, 5), costs) <file_sep>Bu çalışmada geri yayılımlı yapay sinir ağı modeli kullanılarak, rakam fotoğraflarından oluşan The MNIST database of handwritten digits isimli veri seti yardımıyla sınıflandırma yapılmıştır.Veri seti eğitim, onaylama ve test aşamasında kullanılmak üzere üç parçaya ayırılmıştır. Bu veriler her biri 28 satır ve sütundan oluşan matris şeklindeki görüntülerdir.Model Python 3.6 üzerinde kurulmuş ve test edilmiştir. Satır 300den sonrası kendi fotoğraflarımız ile deneme yapmak içindir. In this study, using the back propagation artificial neural network model, the classification was made with the help of the data set named The MNIST database of handwritten digits, which consists of numeral photographs. The data set was divided into three parts to be used in training, validation and testing stages. This data is a matrix-shaped image of 28 rows and columns each. The model was built and tested on Python 3.6. After line 300 is for testing with our own photos.
ca89770173fdc2123a5b52e7ecb0d8e97369a6e6
[ "Markdown", "Python" ]
2
Python
dogans20/-Digit-Classification-with-NN
e66289cf3672aa5dcb01a1eb802fb2cd6d2dfeb9
e101e14c1b48568a28a0e984025f1d1fd259779b
refs/heads/master
<repo_name>osalvetti/baseDe-Datos<file_sep>/README.md # baseDe-Datos Instrucciones para ejecurar el script: Al ejecutarlo desde la herramienta de Query del postgreSQL comentariar la linea --connect "Cajero" ejecutarlo en dos pasadas la primera para crear la base de datos la segunda una vez creada para crear las tablas. <file_sep>/Ordenes.sql -- -- PostgreSQL database dump -- -- Dumped from database version 9.3.5 -- Dumped by pg_dump version 9.3.5 -- Started on 2018-12-12 19:38:47 -05 SET statement_timeout = 0; SET lock_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SET check_function_bodies = false; SET client_min_messages = warning; DROP DATABASE "Cajero"; -- -- TOC entry 2201 (class 1262 OID 6225005) -- Name: Cajero; Type: DATABASE; Schema: -; Owner: postgres -- CREATE DATABASE "Cajero" WITH TEMPLATE = template0 ENCODING = 'UTF8' LC_COLLATE = 'C' LC_CTYPE = 'C'; ALTER DATABASE "Cajero" OWNER TO postgres; \connect "Cajero" SET statement_timeout = 0; SET lock_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SET check_function_bodies = false; SET client_min_messages = warning; -- -- TOC entry 5 (class 2615 OID 2200) -- Name: public; Type: SCHEMA; Schema: -; Owner: postgres -- CREATE SCHEMA public; ALTER SCHEMA public OWNER TO postgres; -- -- TOC entry 2202 (class 0 OID 0) -- Dependencies: 5 -- Name: SCHEMA public; Type: COMMENT; Schema: -; Owner: postgres -- COMMENT ON SCHEMA public IS 'standard public schema'; -- -- TOC entry 171 (class 3079 OID 12018) -- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: -- CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog; -- -- TOC entry 2204 (class 0 OID 0) -- Dependencies: 171 -- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: -- COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language'; SET search_path = public, pg_catalog; SET default_tablespace = ''; SET default_with_oids = false; -- -- TOC entry 170 (class 1259 OID 6225033) -- Name: billetes2; Type: TABLE; Schema: public; Owner: postgres; Tablespace: -- CREATE TABLE billetes2 ( denominacion integer NOT NULL, cantidad integer ); ALTER TABLE public.billetes2 OWNER TO postgres; -- -- TOC entry 2196 (class 0 OID 6225033) -- Dependencies: 170 -- Data for Name: billetes2; Type: TABLE DATA; Schema: public; Owner: postgres -- INSERT INTO billetes2 (denominacion, cantidad) VALUES (20000, 0); INSERT INTO billetes2 (denominacion, cantidad) VALUES (10000, 0); INSERT INTO billetes2 (denominacion, cantidad) VALUES (50000, 3); -- -- TOC entry 2088 (class 2606 OID 6225037) -- Name: pk_billetes2; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace: -- ALTER TABLE ONLY billetes2 ADD CONSTRAINT pk_billetes2 PRIMARY KEY (denominacion); -- -- TOC entry 2203 (class 0 OID 0) -- Dependencies: 5 -- Name: public; Type: ACL; Schema: -; Owner: postgres -- REVOKE ALL ON SCHEMA public FROM PUBLIC; REVOKE ALL ON SCHEMA public FROM postgres; GRANT ALL ON SCHEMA public TO postgres; GRANT ALL ON SCHEMA public TO PUBLIC; -- Completed on 2018-12-12 19:38:48 -05 -- -- PostgreSQL database dump complete --
78062f6a37fc4ed5bbc82e0f9fd0c977aa84df0e
[ "Markdown", "SQL" ]
2
Markdown
osalvetti/baseDe-Datos
23037defdb3de1f1124262304be1a05ec8b318a1
99cea7fc56d4d104518bca4cec0fb483decfd054
refs/heads/master
<repo_name>erhanaytac/SafariCourse<file_sep>/src/Customer/Customer.kt package Customer data class CustomerKot(var ID: Int, var Name: String, var eMail: String) fun main(args: Array<String>){ val customer1 = CustomerKot(1, "Erhan", "<EMAIL>") val customer2 = CustomerKot(2, "Veli", "<EMAIL>") val customer3 = customer1 if(customer1 == customer2){ println("They are the same!") } val customer4 = customer2.copy(eMail = "<EMAIL>") println(customer3.ID) println(customer1.Name) println(customer4.eMail) }<file_sep>/src/Basics/Safari Course.kt package Basics /*fun Classes.main(args: Array<String>){ var myString = "Not Empty" val result = if (myString != ""){ println("Not Empty") 10 } else {println("Is Empty")} println(result) } fun Classes.main(args: Array<String>){ val result = "Value" val whenValue = when (result){ "Value" -> { println("It's a Value.") println("Second statement") "Returnin grom first when case" } is String ->{ println("Excellent!") "Remove that" } else ->{ println("It came to this?") "This warning is now gone!" } } println(whenValue) } package SafariCourse import Main.someUtility as someAdditionalFunction fun Classes.main(args: Array<String>) { print("Hello!") someAdditionalFunction("Name") } */<file_sep>/src/tidbits/NotANumberException.kt package tidbits import java.io.BufferedReader import java.io.FileReader class NotANumberException: Throwable(){ } fun chckIsNumber(obj: Any){ when (obj){ !is Int, Long, Float, Double -> throw NotANumberException() } } fun main(args: Array<String>){ val buffer = BufferedReader(FileReader("input.txt")) val result = try{ val chars = CharArray(30) buffer.read(chars, 0, 40) } catch (e: IndexOutOfBoundsException){ println("Exception handled") -1 } finally{ println("Closing") buffer.close() -2 } println(result) }<file_sep>/src/Functions/Functions.kt package Functions fun hello(): Unit{ println(" ---Hello!---\n") } fun throwingException(): Nothing{ throw Exception("This function throws an exception") } fun returnsAFour(): Int{ return 4 } fun takingString(name: String){ println(name) } fun sum(x: Int, y: Int, z: Int = 0, w: Int = 0): Int{ return x + y + z } fun printDetails(name: String, email: String = "", phone: String){ println("Name: $name \neMail: $email \nPhone: $phone") } fun printStrings(vararg strings: String){ reallyPrintingStrings(*strings) } private fun reallyPrintingStrings(vararg strings: String) { for (string in strings) { println(string) } } fun main(args: Array<String>){ hello() val value = returnsAFour() takingString("Kotlin Words: ${sum(x = 1, y = 2, z = 3)}\n\n") sum(1, 2, 3) sum(1, 2) printDetails("Kotlinhan", phone = "568546", email = "<EMAIL>") printStrings("\n1") printStrings("1 2") printStrings("1 2 3") printStrings("1 2 3 4") printStrings("1 2 3 4 5") printStrings("1 2 3 4") printStrings("1 2 3") printStrings("1 2") printStrings("1") }<file_sep>/src/tidbits/Tuples.kt package tidbits import Customer.CustomerKot fun capitalAndPopulation(country: String): Pair<String, Long>{ return Pair("Madrid", 5200000) } fun countryInformation(country: String): Triple<String, String, Long>{ return Triple("Madrid", "Europe", 52000000) } fun main(args: Array<String>){ val result = capitalAndPopulation("Madrid") //println(result.first) //println(result.second) val countryInfo = countryInformation("Spain") countryInfo.third val (capital, continent, population) = countryInformation("Madrid") val (id, name, email) = CustomerKot(1, "Erhan", "<EMAIL>") val listCapitalsAndCountries = listOf(Pair("Madrid", "Spain"), "Paris" to "France") for ((capital2, country) in listCapitalsAndCountries){ println("$capital2 - $country") } }<file_sep>/src/Classes/EnumClasses.kt package Classes enum class Priority(val value: Int){ MINOR(-1){ override fun text(): String { throw UnsupportedOperationException("Not Implemented.") //To change body of created functions use File - Settings - File Templates } }, NORMAL(0){ override fun text(): String { throw UnsupportedOperationException("Not Implemented.") //To change body of created functions use File - Settings - File Templates } }, MAJOR(1){ override fun text(): String{ return "[MAJOR PRIORITY]" } override fun toString(): String { return " Major Priority" } }, CRITICAL(10){ override fun text(): String { throw UnsupportedOperationException("Not Implemented.") //To change body of created functions use File - Settings - File Templates } }; abstract fun text(): String } fun main(args: Array<String>){ val priority = Priority.MAJOR println(priority) println(priority.text()) }<file_sep>/src/tidbits/Constants.kt package tidbits val CopyrightAuthor = "<NAME>" object Copyright { val author = "<NAME>" } fun main(args: Array<String>){ Copyright.author CopyrightAuthor //println(CopyrightAuthor) }<file_sep>/src/Inheritance/GenericRepository.kt import Classes.Customer class CustomerGenericRepository<I>: Repository<I>{ override fun getById(id: Int): I{ throw UnsupportedOperationException("Not Implemented!\n\nCRITICAL PRIORITY!\n") } override fun getAll(): List<I>{ throw UnsupportedOperationException("Not Implemented") } } interface Repo{ fun <I> getById(id: Int): I fun <E> getAll(): List<E> } class MyRepo: Repo{ override fun <I> getById(id: Int): I { throw UnsupportedOperationException("Not Implemented") } override fun <I> getAll(): List<I>{ throw UnsupportedOperationException("Not Implemented") } } interface Repository<I>{ fun getById(id: Int): I fun getAll(): List<I> } fun main (args: Array<String>){ val customerRepo = CustomerGenericRepository<Customer>() val customer = customerRepo.getById(2) val customers = customerRepo.getAll() //println(customer) //println(customers) }<file_sep>/src/Inheritance/Generics.kt /*package Inheritance import Customer.CustomerKot interface Repository<I>{ fun getById(id: Int): I fun getAll(): List<I> } fun main (args: Array<String>){ val customerRepo = GenericRepository<CustomerKot>() val customer = customerRepo.getById(10) val customers = customerRepo.getAll() }*/<file_sep>/KotlinNull/Null/NullSafety.kt package Null class Service{ fun evaluate(){ } } class ServiceProvider{ fun createServices(): Service {} } fun main(args: Array<String>){ val message: String = "Message" val nullMessage: String? = null val inferredNull = null println(nullMessage!!.length) val sp = createServiceProvider() sp?.createServices()?.evaluate() } private fun createServiceProvider(): ServiceProvider? = ServiceProvider()
29a992ac6f0d4e816987975130dfc0522c4d8406
[ "Kotlin" ]
10
Kotlin
erhanaytac/SafariCourse
910d3bf5e3d703a43944de25fe1492db5188b6d1
94fb67098dc6d07a936fb260911ff6c7699d8090
refs/heads/master
<repo_name>AdamLithgow/Accounting-Fair-Project<file_sep>/phpsrc/logic.php <?php require_once("pdo.php"); $studentid; //Bring in the interview table data so we can work with it $query = "SELECT idstudents, count(idstudents) FROM interviews WHERE priorityLevel != 0 group by idstudents order by idstudents"; $rs=getRecordSet($query,$param); //TODO - Comment out in final prod displayRecordSet($rs); //this is printing the table currently. foreach($rs as $row) { $studentid = $row['idstudents']; if($studentid != 1) { //logic for discarding time slots if($row['count(idstudents)'] > 5) { //get number of non-sponsor interviews to take $interviewsToSelect = 5 - runQuery("SELECT i.idstudents, count(idstudents) FROM interviews AS i INNER JOIN comprep AS cr ON i.idcompRep = cr.idcompRep INNER JOIN company AS c ON cr.idcompany = c.idcompany WHERE c.isSponsor = 1 AND i.idstudents = $studentid ORDER BY idinterviews"); //echo "<br>interviewstoselect = ".$interviewsToSelect; //echo "student = ".$studentid; //select top rows from $rs equal to a count of $interviewsToSelect $dataSet = runQuery("SELECT i.* FROM interviews AS i INNER JOIN comprep AS cr on i.idcomprep = cr.idcomprep INNER JOIN company AS c ON cr.idcompany = c.idcompany WHERE c.isSponsor = 0 and i.idstudents = $studentid ORDER BY idinterviews DESC LIMIT $interviewsToSelect; "); //echo "this is dataset"; // displayRecordSet($dataSet); //update excess records as time slot 7 (rejected) foreach($dataSet as $entry) { //echo "entry = "; //print_r($entry); $arr['idinterviews'] = $entry['idinterviews']; $arr['idtimeSlot'] = 7; $arr['idcompRep'] = $entry['idcompRep']; $arr['idstudents'] = $entry['idstudents']; $arr['priorityLevel'] = $entry['priorityLevel']; //echo "I am updating".$entry['idinterviews']; //print_r($arr); updateRecord("interviews", $arr, "idinterviews", $entry['idinterviews']); } } } } //assign time slots for sponsors assignStudents(); function assignStudents() { $query = " SELECT i.*, c.isSponsor FROM interviews AS i INNER JOIN comprep AS cr ON i.idcompRep = cr.idcompRep INNER JOIN company AS c ON cr.idcompany = c.idcompany WHERE priorityLevel != 0 AND idstudents != 1 AND idtimeSlot = 6 ORDER BY c.isSponsor DESC, i.priorityLevel "; /* if($isSponsor == true) { //query the interviews table for all interviews where the comprep's company is a sponsor $parms[0] = 1; } else { //query the interviews table for all interviews where the comprep's company is NOT a sponsor $parms[0] = 0; } */ //retrieve the data $records = getRecordSet($query, $parms); //echo "displaying thing for assignStudents"; displayRecordSet($records); foreach($records as $data) { if($data['idstudents'] != 1){ $availableRepSlot; $idtimeSlot = $data['idtimeSlot']; $id = $data['idinterviews']; $idcompRep = $data['idcompRep']; $idstudents = $data['idstudents']; $priorityLevel = $data['priorityLevel']; //check for rep's first available time slot /* for($j = 1; $j < 6; $j++) { echo "<br>code inside first foreach reached"; //check if time slot with id equal to $j has a current interview. if it returns empty, there isn't one if(mysqli_num_rows(runQuery("SELECT * FROM interviews WHERE idcompRep = $idcompRep AND idtimeSlot = $j")) == 0) { echo "<br>code inside if reached"; $availableRepSlot = $j; break; } else { echo "<br>code inside else reached"; continue; } echo "<br>code reached"; } //check if rep's open slot is availble for student too for($k = 1; $k < 6; $k++) { echo "<br>inside second for loop reached"; if(mysqli_num_rows(runQuery("SELECT * FROM interviews WHERE idstudents = $idstudents AND idtimeSlot = $availableRepSlot")) == 0) { //time slot is available for both rep and student so update the record with updated time slot id $idtimeSlot = $k; $array['idinterviews'] = $id; $array['idtimeSlot'] = $idtimeSlot; $array['idcompRep'] = $idcompRep; $array['idstudents'] = $idstudents; $array['priorityLevel'] = $priorityLevel; echo "right before record update reached"; updateRecord("interviews", $array, "idinterviews", $id); echo "fetch updated record"; $sample = getRecord("interviews", "idinterviews", $id); print_r($sample); break; } else { //** check for student's next available slot and verify against rep's available slots continue; } } */ for($j = 1; $j < 6; $j++) { //check if time slot with id equal to $j has a current interview. if it returns empty, there isn't one if(mysqli_num_rows(runQuery("SELECT * FROM interviews WHERE idcompRep = $idcompRep AND idtimeSlot = $j")) == 0 && mysqli_num_rows(runQuery("SELECT * FROM interviews WHERE idstudents = $idstudents AND idtimeSlot = $j")) == 0) { echo mysqli_num_rows(runQuery("SELECT * FROM interviews WHERE idcompRep = $idcompRep AND idtimeSlot = $j")); //time slot is available for both rep and student so update the record with updated time slot id $idtimeSlot = $j; $array['idinterviews'] = $id; $array['idtimeSlot'] = $idtimeSlot; $array['idcompRep'] = $idcompRep; $array['idstudents'] = $idstudents; $array['priorityLevel'] = $priorityLevel; //updateRecord("interviews", $array, "idinterviews", $id); break; } } } } } //sort students by who has most interviews ?><file_sep>/phpsrc/Interview_Edit.php <?php //echo "signin.php"; require_once("pdo.php"); //echo "signin.php v3"; //******* Edit if Ready ******* if(isset($_POST['state'])){ $state = $_POST['state']; } if($state == 1) { $id = $_SESSION['pk']; //Student 1 is *Actually* required so we will go through and do this one first if(isset($_POST['student1'])){ $student1 =$_POST['student1']; if(strlen($student1)=="None Selected"){ $post=0; $msg = "You must select at least one student"; } } else{ $post=0; $msg = "You must select at least one student"; } //post student 1 to DB if($post==1){ $arr= array("null",6,$id,$student1,1); //print_r($arr); $result=insertRecord("interviews", $arr); echo "<br>result=$result"; if($result>0){ $msg = "Student Added."; } } if($post==1){ //update the account to the db $arr= array("null",$student1,$student2,$student3,$student4,$student5); //print_r($arr); $array['student1'] = $student1; $array['student2'] = $student2; $array['student3'] = $student3; $array['student4'] = $student4; $array['student5'] = $student5; $result = updateRecord("interviews",$array,"idinterview",$id); echo "<br>result=$result"; if($result>0){ $msg = "Interview Updated"; }else{ $msg = "Error Updating Interview"; } } } //******* Display the Form ******* //get record to display echo "<h2>Edit Interview</h2>"; if(isset($_GET['i'])){ $id = $_GET['i']; } else{ echo "error, interview not found"; exit; } //create query $rs = getRecord("interviews","idinterviews",$id); //print_r($rs); if(count($rs)==0){ echo "<br>interview not found"; exit; } //display record $studentid = $rs['idstudents']; $slot = $rs['idtimeSlot']; $rs = getRecord("students","idstudents",$studentid); $student = $rs['studentName']; $schoolid = $rs['idschool']; $rs = getRecord("school","idschool",$school); $school = $rs['schoolname']; $rs = getRecord("timeslot","idtimeSlot",$slot); $slot = $rs['slotTime']; ?> <!DOCTYPE HTML> <html> <head> <title>Edit Interview</title> </head> <body> <form action='index.php?p=Interview_View' method="post"> <input type="hidden" name="auth" value=10> <input type="hidden" name="state" value=1> <table> <tr> <td colspan=2><?php $msg ?></td> </tr> <tr> <td>Student Name: </td> <td> <select name = student> <?php $temp = buildQuickList("Select idstudents, studentName From students", 'studentName','idstudents', $studentid); echo $temp; ?> </td> </tr> <tr> <td>Time Slot: </td> <td><input type="text" name="slot" size="40" maxlen="40" value='<?php echo $slot; ?>' disabled></td> </tr> <tr> <td colspan=2><input type='submit' value='create'></td> </tr> </table> </form> </body> </html><file_sep>/phpsrc/Student_View.php <?php //echo "signin.php"; require_once("pdo.php"); //echo "signin.php v3"; //******* Display the Form ******* //get record to display echo "<h2>View Student</h2>"; if(isset($_GET['i'])){ $id = $_GET['i']; } else{ echo "error, student not found"; exit; } //create query $query = "SELECT * FROM students WHERE idstudent=? AND idschool=?"; $parms[0] = $_SESSION['idstudent']; $parms[1] = $id; $rs = getRecordSet($query,$parms); //print_r($rs); if(count($rs)==0){ echo "<br>student not found"; exit; } //displayRecordSet($rs); foreach($rs as $row){ //now we have it } $student = $row['student']; $school = $row['school']; ?> <!DOCTYPE html> <html> <head> <title>View Student</title> </head> <body> <form action='index.php?p=Student_View' method=post> <input type='hidden' name='auth' value=10> <input type='hidden' name='state' value=1> <table> <tr> <td colspan=2><?php $msg ?></td> </tr> <tr> <td>Student Name: </td> <td><input type="text" name='student' disabled></td> </tr> <tr> <td>Student School: </td> <td> <select name = school disabled> <?php $temp = buildQuickList("Select idschool, schoolname From school", 'schoolname','idschool'); echo $temp; ?> </td> </tr> </table> </form> </body> </html><file_sep>/phpsrc/mystudents.php <?php require_once("phpsrc/safer.php"); require_once("phpsrc/pdo.php"); //$proceed = safer(10); //if(safer(10) == false){ // echo "<br>You are not authorized to this page....<br>"; //exit; //} echo "<h2>My Requested Interviews</h2>"; echo "idtimeSlot == 6 means not assigned to a time slot<br>"; $id = $_SESSION['pk']; $query = "Select * from interviews where idcompRep = '$id'"; //echo "query = $query"; $result = runQuery($query); displayRecordSetE($result,"Student_Edit","Student_Del","Student_View","Student_Create","idinterviews"); /* samples for using pdo are below displayRecordSet(getTableStructure("users")); println(" "); displayRecordSet(runQuery("Select * from users")); $email="<EMAIL>"; $username="<NAME>"; $authority=99; $password="<PASSWORD>"; $arr = array($email, $username, $authority, $password); insertRecord("users", $arr, false); displayRecordSet(runQuery("Select * from users")); $array['password']="<PASSWORD>"; $array['authority']=42; updateRecord("users", $array, "email", "<EMAIL>"); displayRecordSet(runQuery("Select * from users")); displayRecordSet(getTableStructure("loans")); */ ?> <file_sep>/phpsrc/Student_Create.php <?php //echo "signin.php"; require_once("pdo.php"); //get the values from the form $state = 0; if(isset($_POST['state'])){ $state=$_POST['state']; } $post = 1; $msg = ""; //validate inputs if($state == 1) { $id = $_SESSION['pk']; //verify student name input if(isset($_POST['student'])){ $student =$_POST['student']; if(strlen($student)==""){ $post=0; $msg = "You must enter a student name"; } } else{ $post=0; $msg = "You must enter a student name"; } //verify school input if(isset($_POST['school'])){ $school =$_POST['school']; if(strlen($school)=="None Selected"){ $post=0; $msg = "You must select a school"; } } else{ $post=0; $msg = "You must select a school"; } //post student 1 to DB if($post==1){ $arr= array("null",$school,$student); //how to find out id from school //print_r($arr); $result=insertRecord("students", $arr); echo "<br>result=$result"; if($result>0){ $msg = "Student Added."; } } } //******* Display the Form ******* if($result==1){ echo "<h2>Students Requested</h2>"; exit; } ?> <!DOCTYPE html> <html> <head> <title>Create Student</title> </head> <body> <form action='index.php?p=Student_Create' method=post> <input type='hidden' name='auth' value=10> <input type='hidden' name='state' value=1> <table> <tr> <td colspan=2><?php $msg ?></td> </tr> <tr> <td>Student Name: </td> <td><input type="text" name='student'></td> </tr> <tr> <td>Student School: </td> <td> <select name = school> <?php $temp = buildQuickList("Select idschool, schoolname From school", 'schoolname','idschool'); echo $temp; ?> </td> </tr> <tr> <td colspan=2><input type='submit' value='create'></td> </tr> </table> </form> </body> </html> <file_sep>/phpsrc/Interview_View.php <?php //echo "signin.php"; require_once("pdo.php"); //echo "signin.php v3"; //******* Display the Form ******* //get record to display echo "<h2>View Interview</h2>"; if(isset($_GET['i'])){ $id = $_GET['i']; } else{ echo "error, interview not found"; exit; } //create query $rs = getRecord("interviews","idinterviews",$id); //print_r($rs); if(count($rs)==0){ echo "<br>interview not found"; exit; } //displayRecordSet($rs); $student = $rs['idstudents']; $slot = $rs['idtimeSlot']; $rs = getRecord("students","idstudents",$student); $student = $rs['studentName']; $school = $rs['idschool']; $rs = getRecord("school","idschool",$school); $school = $rs['schoolname']; $rs = getRecord("timeslot","idtimeSlot",$slot); $slot = $rs['slotTime']; ?> <!DOCTYPE HTML> <html> <head> <title>View Interview</title> </head> <body> <form action='index.php?p=Interview_View' method="post"> <input type="hidden" name="auth" value=10> <input type="hidden" name="state" value=1> <table> <tr> <td colspan=2><?php $msg ?></td> </tr> <tr> <td>Student Name: </td> <td><input type="text" name="student" size="40" maxlen="40" value='<?php echo $student; ?>' disabled></td> </tr> <tr> <td>School: </td> <td><input type="text" name="school" size="40" maxlen="40" value='<?php echo $school; ?>' disabled></td> </tr> <tr> <td>Time Slot: </td> <td><input type="text" name="slot" size="40" maxlen="40" value='<?php echo $slot; ?>' disabled></td> </tr> </table> </form> </body> </html><file_sep>/phpsrc/School_Create.php <?php //echo "signin.php"; require_once("pdo.php"); //get the values from the form $state = 0; if(isset($_POST['state'])){ $state=$_POST['state']; } $post = 1; $msg = ""; //validate inputs if($state == 1) { $id = $_SESSION['pk']; //verify school name input if(isset($_POST['schoolname'])){ $schoolname =$_POST['schoolname']; if(strlen($schoolname)==""){ $post=0; $msg = "You must enter a school name"; } } else{ $post=0; $msg = "You must enter a school name"; } //post school 1 to DB if($post==1){ $arr= array("null",$schoolname); //print_r($arr); $result=insertRecord("school", $arr); echo "<br>result=$result"; if($result>0){ $msg = "School Added."; } } } //******* Display the Form ******* if($result==1){ echo "<h2>School Added</h2>"; exit; } ?> <!DOCTYPE html> <html> <head> <title>Create School</title> </head> <body> <form action='index.php?p=School_Create' method=post> <input type='hidden' name='auth' value=10> <input type='hidden' name='state' value=1> <table> <tr> <td colspan=2><?php $msg ?></td> </tr> <tr> <td>School Name: </td> <td><input type="text" name='schoolname'></td> </tr> <tr> <td colspan=2><input type='submit' value='create'></td> </tr> </table> </form> </body> </html> <file_sep>/phpsrc/testpdo.php <?php //test pdo require_once("pdo.php"); echoln("testing pdo"); //getRecord(table, pkfield, pkvalue) echoln(" "); echoln("retrieve a record..."); $row = getRecord("users","username","test"); print_r($row); echoln(" "); //getRecordSet(query, parameters) echoln(" "); echoln("retrieve a recordset with parameters..."); $query = "select * from users where username=? and password=?"; $parms[0]="<PASSWORD>"; $parms[1]="test"; $row = getRecordSet($query,$parms); print_r($row); displayRecordSet($row); echoln(" "); //runQuery(query) echoln(" "); echoln("run a query with no parameters"); $query = "select * from users"; $rs = runQuery($query); foreach($rs as $row) print_r($row); echoln(" "); //displayRecordSet(result) echoln(" "); echoln("display a record set (result from runQuery or getRecordSet)"); $query = "select * from users"; $rs = runQuery($query); displayRecordSet($rs); echoln(" "); //getTableStructure(tablename) echoln(" "); echoln("displaya table structure"); displayRecordSet(getTableStructure("users")); echoln(" "); //insertRecord(tablename, recordArray, autoincrement value) // for autoincrement pk: $result = insertRecord("customers",$array); // for non incrementing pk: $result = insertRecord("books",$array, false); // pkfield must be listed first //add a user $username="verdetj"; $password="<PASSWORD>"; $name="<NAME>"; $authlevel=10; $arr = array($username, $password, $name, $authlevel); print_r($arr); echoln(" "); echoln("Insert a record with no autoincrementing key"); $success = insertRecord("users",$arr,false); echoln("result of insert = ".$success); displayRecordSet(runQuery("Select * from users")); echoln(" "); //add a user $testid="does not matter"; $testname="testing"; $testnumber=42; $arr = array($testid,$testname,$testnumber); print_r($arr); echoln(" "); echoln("Insert a record with autoincrementing key"); $success = insertRecord("testAuto",$arr); echoln("result of insert = ".$success); displayRecordSet(runQuery("Select * from testAuto")); echoln(" "); // //now update the added records echoln(" "); echoln("update password on verdetj "); $password = "<PASSWORD>"; $record["password"]=$<PASSWORD>; updateRecord("users",$record,"username","verdetj"); displayRecordSet(runQuery("Select * from users")); echoln(" "); // //now delete the extra records echoln(" "); echoln("delete verdetj "); delRecord("users","username","verdetj"); displayRecordSet(runQuery("Select * from users")); echoln(" "); //lets delete the records from testAuto as well echoln(" "); echoln("delete all records from testAuto where testName='testing'"); delRecords("testAuto","testName","testing"); displayRecordSet(runQuery("Select * from testAuto")); echoln(" "); ?><file_sep>/phpsrc/Account_Create.php <?php //echo "signin.php"; require_once("pdo.php"); //echo "signin.php v3"; //lets get the values from the form $state = 0; if(isset($_POST['state'])){ $state=$_POST['state']; } $post = 1; $msg = ""; //validate email if($state == 1) { //validate the inputs //~~~~~~ email ~~~~~~~ if(isset($_POST['email'])){ $email=$_POST['email']; if(strlen($email)==0){ $post=0; $msg = "invalid email"; } } else{ $post=0; $msg = "invalid email"; } //~~~~~~ repName ~~~~~~~ if(isset($_POST['repName'])){ $repName=$_POST['repName']; if(strlen($repName)==0){ $post=0; $msg = "invalid repName"; } } else{ $post=0; $msg = "invalid repName"; } //~~~~~~ password ~~~~~~~ if(isset($_POST['pass'])){ $pass=$_POST['pass']; if(strlen($pass)==0){ $post=0; $msg = "invalid password"; } } else{ $post=0; $msg = "invalid password"; } //~~~~~~ comp ~~~~~~~ if(isset($_POST['comp'])){ $comp=$_POST['comp']; if(strlen($comp)==0){ $post=0; $msg = "invalid company"; } } else{ $post=0; $msg = "invalid company"; } if($post==1){ //post the account to the db //pk, compID, repName, email auth pass $arr= array("null",$comp, $repName,$email,10,$pass); $result=insertRecord("comprep", $arr); //echo "result=$result"; if($result == 1){ echo "Account created successfully."; } } } ?> <!DOCTYPE html> <html> <head> <title>Create Account</title> </head> <body> <form action='index.php?p=Account_Create' method=post> <input type='hidden' name='auth' value=10> <input type='hidden' name='state' value=1> <table> <tr> <td colspan=2><?php $msg ?></td> </tr> <tr> <td>Full Name: </td> <td><input type='text' name='repName' size=40 maxlen=40 ></td> </tr> <tr> <td>Company: </td> <td> <select name = comp> <?php $temp = buildQuickList("Select idcompany, companyName From company", 'companyName','idcompany'); echo $temp; ?> </td> </tr> <tr> <td>Email: </td> <td><input type='text' name='email' size=40 maxlen=40></td> </tr> <tr> <td>Password: </td> <td><input type='password' name='pass' size=40 maxlen=40></td> </tr> <tr> <td colspan=2><input type='submit' value='create'></td> </tr> </table> </form> </body> </html><file_sep>/phpsrc/signin.php <?php //echo "signin.php"; require_once("pdo.php"); echo"admin account credentials: user = '<EMAIL>' pass = '<PASSWORD>' <br> please use create account to test other things :)"; //echo "signin.php v3"; //lets get the values from the form $firstTrip = 0; $post = 1; $msg = ""; //validate username if(isset($_POST['email'])){ $username = $_POST['email']; $firstTrip = 1; } else{ $username = ""; $post = 0; } if(strlen($username)<1 && $firstTrip == 1){ $msg = "User name not entered. "; $post = 0; //exit; } if(isset($_POST['pass'])){ $password = $_POST['pass']; $firstTrip = 1; } else{ $password = ""; $post = 0; } if(strlen($password)<1 && $firstTrip == 1){ $msg = "*Password not entered."; $post = 0; //exit; } //echo "<br>email = $username"; //echo "<br>password = $password"; //echo "<br>post = $post"; //echo "<br>"; //set up the query string if($post == 1){ $query = "select * from comprep where email=? and pass = ?"; $parm[0] = $username; $parm[1] = $password; $parm[2] = $primarykey; //echo "test"; $rs = getRecordSet($query,$parm); //displayRecordSet($rs); $c = sizeof($rs); //echo "<br>return value =".sizeof($rs); //print_r($rs); if($c == 0){ unset($rs); } } //message if not found if($firstTrip == 1){ if($c==0){ //failed attempt echo "<br>invalid login, please try again"; include("htmlsrc\signin.html"); } else{ //successful login //set up the session variables $row = $rs[0]; $_SESSION['user'] = $row['email']; $_SESSION['auth'] = $row['auth']; $_SESSION['pk'] = $row['idcompRep']; //load the main page echo "<h2>Welcome, ".$_SESSION['user']." to the Accounting Organzier System</h2>"; //this if statement sends the normal user to myInterviews and the admin to the assignInterviews pages. if($_SESSION['auth'] < 20) echo "<h3><a href=index.php?p=myinterviews>Click here to continue</a>"; else echo "<h3><a href=index.php?p=logic>Click here to continue</a>"; } } else{ //first attempt include ("htmlsrc\signin.html"); } ?> <file_sep>/phpsrc/Company_Create.php <?php //echo "signin.php"; require_once("pdo.php"); //get the values from the form $state = 0; if(isset($_POST['state'])){ $state=$_POST['state']; } $post = 1; $msg = ""; //validate inputs if($state == 1) { $id = $_SESSION['pk']; //verify company name input if(isset($_POST['companyname'])){ $companyname =$_POST['companyname']; if(strlen($companyname)==""){ $post=0; $msg = "You must enter a company name"; } } else{ $post=0; $msg = "You must enter a company name"; } //verify company info input if(isset($_POST['companyinfo'])){ $companyinfo =$_POST['companyinfo']; if(strlen($companyinfo)==""){ $post=0; $msg = "You must enter intern majors looking for"; } } else{ $post=0; $msg = "You must enter intern majors looking for"; } //verify priorityLevel input (will always have a value due to drop down menu) if(isset($_POST['priorityLevel'])){ $priorityLevel =$_POST['priorityLevel']; } //post company 1 to DB if($post==1){ $arr= array("null",$companyname,$companyinfo,$priorityLevel); //print_r($arr); $result=insertRecord("company", $arr); //echo "<br>result=$result"; if($result>0){ $msg = "Company Added."; } } } //******* Display the Form ******* if($result==1){ echo "<h2>Company Added</h2>"; exit; } ?> <!DOCTYPE html> <html> <head> <title>Create Company</title> </head> <body> <form action='index.php?p=Company_Create' method=post> <input type='hidden' name='auth' value=10> <input type='hidden' name='state' value=1> <table> <tr> <td colspan=2><?php $msg ?></td> </tr> <tr> <td>Company Name: </td> <td><input type="text" name='companyname'></td> </tr> <tr> <td>Interns Majors Looking For: </td> <td><input type="text" name='companyinfo'></td> </tr> <tr> <td>Is This A Sponsor Company?: </td> <td> <select name='priorityLevel'> <option value = "0">No</option> <option value = "1">Yes</option> </select> </td> </tr> <tr> <td colspan=2><input type='submit' value='create'></td> </tr> </table> </form> </body> </html> <file_sep>/phpsrc/Interview_Create.php <?php //echo "signin.php"; require_once("pdo.php"); echo "Please be careful and do not hit submit or enter until you select the 5 students (or less), in priority order, for your requested interviews. Once you hit submit, there is no way to edit. Sorry for any inconvenience that this may cause."; $qu = "Select count(*) as howmany From interviews where idcomprep = ".$_SESSION['pk']." and priorityLevel = 1";//query $rs2 = runQuery($qu); //echo "<br>array="; //displayRecordSet($rs2); foreach($rs2 as $rs3) $howmany = $rs3['howmany']; $trouble = 0; //send users to edit if they have already done this page. if($howmany > 0){ echo "<h3>You may no longer add interviews</h3>"; //hide table "trouble" with JS $trouble = 1; } //TODO IN CODING CLUB - Make it so that if they select less than 5 students it does not mess up. At this point, it looks like gold plating to me and I have a paper to write. //get the values from the form $state = 0; if(isset($_POST['state'])){ $state=$_POST['state']; } $post = 1; $msg = ""; //validate no repeat entries if(!($student1 != $student2 && $student3 != $student1 && $student3 != $student2 && $student4 != $student1 && $student4 != $student2 && $student4 != $student3 && $student5 != $student1 && $student5 != $student2 && $student5 != $student3 && $student5 != $student4)){ $post = 0; echo "<h2>Error: Cannot Select Same Student Twice</h2>"; } //validate inputs if($state == 1) { $id = $_SESSION['pk']; //Student 1 is *Actually* required so we will go through and do this one first if(isset($_POST['student1'])){ $student1 =$_POST['student1']; if(strlen($student1)==1){ $post=0; $msg = "You must select at least one student"; } } else{ $post=0; $msg = "You must select at least one student"; } //post student 1 to DB if($post==1){ $arr= array("null",6,$id,$student1,1); //print_r($arr); $result=insertRecord("interviews", $arr); //echo "<br>result=$result"; if($result>0){ $msg = "Student Added."; } } //~~~~ student2-5 are not required fields~~~ if(isset($_POST['student2'])){ $student2 =$_POST['student2']; if(!(strlen($student2)==1) && $post == 1){ $arr= array("null",6,$id,$student2,2); $result=insertRecord("interviews", $arr); $msg = "Students Added."; } } if(isset($_POST['student3'])){ $student3 =$_POST['student3']; if(!(strlen($student3)==1) && $post == 1) { $arr= array("null",6,$id,$student3,3); $result=insertRecord("interviews", $arr); } } if(isset($_POST['student4'])){ $student4 =$_POST['student4']; if(!(strlen($student4)==1) && $post == 1){ $arr= array("null",6,$id,$student4,4); $result=insertRecord("interviews", $arr); } } if(isset($_POST['student5'])){ $student5 =$_POST['student5']; if(!(strlen($student5)==1) && $post == 1){ $arr= array("null",6,$id,$student5,5); $result=insertRecord("interviews", $arr); } } } //******* Display the Form ******* if($result==1){ echo "<h2>Interviews Requested</h2>"; exit; }else{ echo "<br><h2>Error: Please Try Again</h2>"; } ?> <html> <head> <title>Create Interview</title> </head> <body> <form action='index.php?p=Interview_Create' method=post> <input type='hidden' name='auth' value=10> <input type='hidden' name='state' value=1> <table id = "trouble"> <tr> <td colspan=2><?php $msg ?></td> </tr> <?php if($trouble == 0) { for($k=1; $k<6; $k++){ echo"<tr>"; echo"<td>Student ".$k.": </td>"; echo"<td>"; echo"<select name = student".$k.">"; $temp = buildQuickList("Select idstudents, studentName From students", 'studentName','idstudents'); echo $temp; echo"</td>"; echo"</tr>"; } echo"<tr>"; echo"<td colspan=2><input type='submit' value='create'></td>"; echo"</tr>"; }?> </table> </form> </body> </html><file_sep>/phpsrc/signin3_old.php <?php require_once("pdo.php"); //echo "signin.php v3"; //lets get the values from the form $firstTrip = 0; $post = 1; $msg = ""; //validate username if(isset($_POST['user'])){ $username = $_POST['user']; $firstTrip = 1; } else{ $username = ""; $post = 0; } if(strlen($username)<1 && $firstTrip == 1){ $msg = "*User name not entered. "; //exit; } if(isset($_POST['pass'])){ $password = $_POST['pass']; $firstTrip = 1; } else{ $password = ""; $post = 0; } if(strlen($password)<1 && $firstTrip == 1){ $msg = "*Password not entered."; //exit; } //echo "<br>username = $username"; //echo "<br>password = $<PASSWORD>"; //set up the query string if($post == 1){ $query = "select * from users where username=? and password = ?"; $parm[0] = $username; $parm[1] = $password; //echo "test"; $rs = runQuery($query,$parm); //echo "<br>return value =".sizeof($rs); //print_r($rs); if(sizeof($rs) == 0){ unset($rs); } } $c=0; //echo "<br> - returned record:"; //print_r($rs); //display the records on the screen if(isset($rs)){ //echo "<br>print records"; $c=1; foreach($rs as $row){ foreach($row as $key=>$val){ //echo "<br>$key = $val"; } } } //message if not found if($firstTrip == 1){ if($c==0){ //failed attempt echo "<br>invalid login, please try again"; include("signin2.html"); } else{ //successful login include("home.html"); } } else{ //first attempt include ("signin2.html"); } ?>
8f13070331876507a23abcf851d284e1a2927bae
[ "PHP" ]
13
PHP
AdamLithgow/Accounting-Fair-Project
1418e2c5bd01f5aa0bda4b9c8af26047ecde7de5
471859dcc43f6601c6f926b5b43b9e44a25872bc
refs/heads/master
<repo_name>Forita/h1b_statistics<file_sep>/input/README.md Input data could be found [here](https://www.foreignlaborcert.doleta.gov/performancedata.cfm) under the __Disclosure Data__ tab (i.e., files listed in the __Disclosure File__ column with ".xlsx" extension). In this repo, we use "H-1B_FY14_Q4.xlsx", "H-1B_Disclosure_Data_FY15_Q4.xlsx" and "H-1B_Disclosure_Data_FY16.xlsx" as input data. <file_sep>/README.md # h1b_statistics A newspaper editor was researching immigration data trends on H1B(H-1B, H-1B1, E-3) visa application processing over the past years, trying to identify the occupations and states with the most number of approved H1B visas. She has found statistics available from the US Department of Labor and its Office of Foreign Labor Certification Performance Data. But while there are ready-made reports for 2018 and 2017, the site doesn’t have them for past years. In this repo, we create a mechanism to analyze past years data, specificially calculate two metrics: Top 10 Occupations and Top 10 States for certified visa applications. <file_sep>/src/h1b_counting.py import pandas as pd df1 = pd.read_excel('./input/H-1B_FY14_Q4.xlsx') df2 = pd.read_excel('./input/H-1B_Disclosure_Data_FY15_Q4.xlsx') df3 = pd.read_excel('./input/H-1B_Disclosure_Data_FY16.xlsx') df_2014 = df1[['LCA_CASE_NUMBER', 'STATUS', 'LCA_CASE_EMPLOYER_STATE', 'LCA_CASE_SOC_CODE', 'LCA_CASE_SOC_NAME']] df_2015 = df2[['CASE_NUMBER', 'CASE_STATUS', 'EMPLOYER_STATE', 'SOC_CODE', 'SOC_NAME']] df_2016 = df3[['CASE_NUMBER', 'CASE_STATUS', 'EMPLOYER_STATE', 'SOC_CODE', 'SOC_NAME']] df_2014.columns = ['CASE_NUMBER', 'CASE_STATUS', 'EMPLOYER_STATE', 'SOC_CODE', 'SOC_NAME'] df = pd.concat([df_2014, df_2015, df_2016]) # total number of certified visa applications totalCert = sum(df.CASE_STATUS == 'CERTIFIED') print(totalCert) # top 10 occupations occup = df.groupby('SOC_NAME') df_cert = occup.apply(lambda x: sum(x.CASE_STATUS == 'CERTIFIED')) df_cert = df_cert.sort_values(ascending=False) top_occup = pd.DataFrame() top_occup['NUMBER_CERTIFIED_APPLICATIONS'] = df_cert[:10] top_occup ['PERCENTAGE'] = df_cert[:10] / totalCert top_occup.reset_index(level=0, inplace=True) top_occup['PERCENTAGE'] = pd.Series(["{0:.2f}%".format(val * 100) for val in top_occup['PERCENTAGE']], index = top_occup.index) top_occup.columns = ['TOP_OCCUPATIONS', 'NUMBER_CERTIFIED_APPLICATIONS', 'PERCENTAGE'] # top 10 states state = df.groupby('EMPLOYER_STATE') df_state = state.apply(lambda x: sum(x.CASE_STATUS == 'CERTIFIED')) df_state = df_state.sort_values(ascending=False) top_state = pd.DataFrame() top_state['NUMBER_CERTIFIED_APPLICATIONS'] = df_state[:10] top_state ['PERCENTAGE'] = df_state[:10] / totalCert top_state.reset_index(level=0, inplace=True) top_state['PERCENTAGE'] = pd.Series(["{0:.2f}%".format(val * 100) for val in top_state['PERCENTAGE']], index = top_state.index) top_state.columns = ['TOP_STATES', 'NUMBER_CERTIFIED_APPLICATIONS', 'PERCENTAGE'] # output top_occup.to_csv('./output/top_10_occupations.txt', index=None, sep=';', mode='a') top_state.to_csv('./output/top_10_states.txt', index=None, sep=';', mode='a')
d8bd791b0f060e841b59442c762d2212fdf0283c
[ "Markdown", "Python" ]
3
Markdown
Forita/h1b_statistics
e2cd78fa70f3a0cd997a88d4f24affa5ebf708b5
88ed9569c70558983796f5ea7d44bf837f1be139
refs/heads/master
<file_sep>import json import io import re import os from os import walk from os import path import subprocess from shutil import copyfile from shutil import rmtree import glob class Struct(object): pass def parseConfig(configName='config.json'): data = json.load(open(configName)) config = Struct() config.applycationPath = data["ExectOutputPath"] config.binFilePath = data["BinFilePath"] config.recalcFilePath = data["FolderWithRecalculated"] config.txtFilePath = data["TxtFile"] config.regex = data["RegEx"] config.actions = set(data["Actions"]) return config; def getSetOfMatchedNamesInFile(file, regex): filenames = set() for line in file: curStr = str(line.strip('\n')) matched = re.search(config.regex, curStr); if(matched): filenames.add(matched.group(1).lower()) return filenames; def getFileNamesAndFullFN(filesPath): fileNames = [] fullFileNames = [] exclude = {'.svn'} for root, dirs, files in walk(filesPath): dirs[:] = [d for d in dirs if d not in exclude] for file in files: fullFileNames.append(path.join(root, file)) fileNames.append(file.lower()); return (fileNames, fullFileNames); def removeFolder(path): rmtree(path) def copyFile(filenamesAndFullFnTuple, filesToCheck, dirName): for fN, fullFN in filenamesAndFullFnTuple: if fN in filesToCheck: copyfile(fullFN, dirName+'\\' + fN) def execute(dirName, appPath): curFilePath = os.path.dirname(os.path.realpath(__file__)) subprocess.call([appPath, '-path:' +curFilePath+'\\' + dirName]) def getFileNameSetInDir(pathToFile): foundFiles = {} exclude = {'.svn'} for root, dirs, files in walk(pathToFile): dirs[:] = [d for d in dirs if d not in exclude] for file in files: file = file.lower() foundFiles[file] = path.join(root, file) return foundFiles def copyFileThatExistInSet(filenameSet, dirFrom): exclude = {'.svn'} for root, dirs, files in walk(dirFrom): dirs[:] = [d for d in dirs if d not in exclude] for file in files: file = file.lower() if(file in filenameSet): fullPath = path.join(root, file) copyfile(fullPath, filenameSet[file]) def getNewestFolderInPath(pathToFile): return max(glob.glob(os.path.join(pathToFile, '*/')), key=os.path.getmtime); config = parseConfig(); tmpDirName= "TempBinFiles" file = io.open(config.txtFilePath,'r', encoding='utf-16') diffFilenames = getSetOfMatchedNamesInFile(file, config.regex) fileNames, fullFileNames = getFileNamesAndFullFN(config.binFilePath) if("copySource" in config.actions): if os.path.exists(tmpDirName): removeFolder(tmpDirName) os.makedirs(tmpDirName) copyFile(zip(fileNames, fullFileNames), diffFilenames, tmpDirName) if("calculate" in config.actions): execute(tmpDirName, config.applycationPath) if("copyResult" in config.actions): folderWithDifferent = getNewestFolderInPath(config.recalcFilePath) + 'different'; if os.path.exists(folderWithDifferent): binNames = getFileNameSetInDir(config.binFilePath) copyFileThatExistInSet(binNames, folderWithDifferent) if("removeTmp" in config.actions): removeFolder(tmpDirName) <file_sep>from os import walk from os import path from shutil import copyfile import argparse parser = argparse.ArgumentParser() parser.add_argument('--from', dest="fromF") parser.add_argument('--to', dest="to") parser.add_argument('--ext', dest="ext") args = parser.parse_args() def findAllFilesWithExtension(fromPath, extension): res = [] for root, dirs, files in walk(fromPath): for file in files: if file.endswith("." + extension): res.append((file, path.join(root, file))) return res allFiles = findAllFilesWithExtension(args.fromF, args.ext); for file in allFiles: copyfile(file[1], args.to+'\\' + file[0])
883e1017be2334fe1e90d78f55c41e5192fd5900
[ "Python" ]
2
Python
triaxTeam/useful-scripts
ed3a2e53df85cedf7253eca4b95426769c887a97
e652d36a0bebfd6b80cf05e77dd6ec58b76372b5
refs/heads/main
<file_sep>import { StatusBar } from 'expo-status-bar'; import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import Contato from './src/Pages/Contato'; import Home from './src/Pages/Home'; import Quemsomos from './src/Pages/QuemSomos'; import Fotos from './src/Pages/Fotos'; const Stack = createStackNavigator(); export default function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={Home} /> <Stack.Screen name="Quemsomos" component={Quemsomos} /> <Stack.Screen name="Fotos" component={Fotos} /> <Stack.Screen name="Contato" component={Contato} /> </Stack.Navigator> </NavigationContainer> ); } <file_sep>import React from 'react'; import { View, Text, Image, StyleSheet, Dimensions, TouchableOpacity } from 'react-native'; import estilo from '../Estilos/estilo' import Menu from '../../Components/menu' const Home = ({navigation}) => { return ( <View style={estilo.container}> <Image source={require('../../../assets/images/dog-cat.jpg')} style={estilo.imagem} /> <Text>Página inicial</Text> <Menu navigation={navigation} /> </View> ) } export default Home<file_sep>import React from 'react'; import { View, Text, Image, StyleSheet, Dimensions, TouchableOpacity } from 'react-native'; import Menu from '../../Components/menu'; import estilo from '../Estilos/estilo' const Contato = ({navigation}) => { return ( <View style={estilo.container}> <Image source={require('../../../assets/images/panda.jpg')} style={estilo.imagem} /> <Text>Contato</Text> <Menu navigation={navigation} /> </View> ) } export default Contato<file_sep>import React, {Fragment} from 'react'; import { Text, TouchableOpacity } from 'react-native'; import estilo from '../Pages/Estilos/estilo' const Menu = ({navigation}) => { return ( <Fragment> <TouchableOpacity onPress={() => navigation.navigate('Home')}> <Text style={estilo.botao}>Home</Text> </TouchableOpacity> <TouchableOpacity onPress={() => navigation.navigate('Quemsomos')}> <Text style={estilo.botao}>Quem somos</Text> </TouchableOpacity> <TouchableOpacity onPress={() => navigation.navigate('Fotos')}> <Text style={estilo.botao}>Fotos</Text> </TouchableOpacity> <TouchableOpacity onPress={() => navigation.navigate('Contato')}> <Text style={estilo.botao}>Contato</Text> </TouchableOpacity> </Fragment> ) } export default Menu
a85bfba9fc9a011fc1acb2f50040873a1b533bd5
[ "JavaScript" ]
4
JavaScript
mozartbrito/navegacao-react-native
1adb95eab3b6b0780fbf21d310f920322d71d731
b9704b4bd867dc49ce6d079b9a44c6f4d2303dbe
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using AIsOfCatan.Log; using MS.Internal.Xml.XPath; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TroyXnaAPI; using AIsOfCatan.API; namespace AIsOfCatan { class MapScreen : TXAScreen { private GameState latestGameState; //private DateTime lastLogPoll; private readonly GUITile[][] board = new GUITile[7][]; private readonly List<int> omitted = new List<int> { 0, 5, 6, 12, 32, 38, 39, 44 }; private readonly List<GUIRoad> roads = new List<GUIRoad>(); private readonly List<GUIPiece> pieces = new List<GUIPiece>(); private readonly GUILogList<GUIBufferTextBlock> gamelog; private readonly GUIRobber robber; public MapScreen(GameState initial) { latestGameState = initial; for (int i = 0; i < board.Length; i++) { board[i] = new GUITile[Board.GetRowLength(i)]; for (int j = 0; j < board[i].Length; j++) { bool omit = OmittedTile(GetTerrainIndex(i, j)); GUITile tile = new GUITile(j, i, latestGameState.Board.GetTile(i, j), omit); AddDrawableComponent(tile); board[i][j] = tile; } } //Entire Screen size: GraphicsAdapter.DefaultAdapter.CurrentDisplayMode const int logWidth = 350; //int gameH = graphics.Viewport.Height; //int gameW = graphics.Viewport.Width; const int screenWidth = 1280; const int screenHeight = 720; //Debug.WriteLine(string.Format("width {0}, height {1}", gameW, gameH)); gamelog = new GUILogList<GUIBufferTextBlock>(new Vector2((screenWidth-logWidth)/TXAGame.SCALE, 1/TXAGame.SCALE),screenHeight-2, logWidth-1); //AddButton(new TXAButton(new Vector2(750 / TXAGame.SCALE, 50 / TXAGame.SCALE), "Debug Log"), InsertText); AddDrawableComponent(gamelog); robber = new GUIRobber(GetRobberPos()); AddDrawableComponent(robber); latestGameState.GetLatestEvents(int.MaxValue).Skip(gamelog.Count).ForEach(a => InsertLogEvent(a.ToString())); //lastLogPoll = DateTime.Now; //Test Roads and pieces UpdateGameState(initial); } private void InsertLogEvent(string logText) { GUIBufferTextBlock textB = new GUIBufferTextBlock(new Vector2(0,-25)) {Text = logText}; gamelog.AddToList(textB); } public void UpdateGameState(GameState state) { Console.WriteLine("UpdateGameState called"); latestGameState = state; #region Roads Dictionary<Edge, int> allRoads = latestGameState.Board.GetAllRoads(); foreach (KeyValuePair<Edge, int> road in allRoads) { int tile1 = road.Key.FirstTile; int tile2 = road.Key.SecondTile; if (roads.Exists(r => r.Tile1 == tile1 && r.Tile2 == tile2)) { continue; } Edge t1Coord = GetTerrainCoords(tile1); Edge t2Coord = GetTerrainCoords(tile2); Vector2 diffVector = board[t2Coord.FirstTile][t2Coord.SecondTile].Position / TXAGame.SCALE - board[t1Coord.FirstTile][t1Coord.SecondTile].Position / TXAGame.SCALE; Vector2 placeVector = (board[t1Coord.FirstTile][t1Coord.SecondTile].Position/TXAGame.SCALE)+(diffVector/2); float rotation = 0; const float value = (float) (Math.PI/3); if (diffVector.X < 0) { rotation = value*2; } else if (diffVector.X < diffVector.Y) { rotation = value; } GUIRoad newRoad = new GUIRoad(placeVector,rotation,road.Value, tile1, tile2); newRoad.Visible = true; AddDrawableComponent(newRoad); } #endregion #region Pieces Dictionary<Intersection, Piece> piecelist = state.Board.GetAllPieces(); foreach (KeyValuePair<Intersection, Piece> piece in piecelist) { int t1 = piece.Key.FirstTile; int t2 = piece.Key.SecondTile; int t3 = piece.Key.ThirdTile; GUIPiece alreadyPiece = pieces.FirstOrDefault(e => e.Tile1 == t1 && e.Tile2 == t2 && e.Tile3 == t3); if (alreadyPiece != null) { if (alreadyPiece.Type == Token.Settlement && piece.Value.Token == Token.City) { alreadyPiece.Type = Token.City; } continue; } Vector2 diffVector = t1 + 1 == t2 ? new Vector2(GUITile.TileWidth()/2, GUITile.TileHeight()/4) : new Vector2(0, GUITile.TileHeight()/2); Edge t1C = GetTerrainCoords(t1); Vector2 placePos = board[t1C.FirstTile][t1C.SecondTile].Position/TXAGame.SCALE + diffVector; GUIPiece newPiece = new GUIPiece(placePos, piece.Value.Player, piece.Value.Token, t1, t2, t3); newPiece.Visible = true; pieces.Add(newPiece); AddDrawableComponent(newPiece); } #endregion #region Robber robber.UpdateRobberPosition(GetRobberPos()); #endregion #region GameLog latestGameState.GetLatestEvents(int.MaxValue).Skip(gamelog.Count).ForEach(a => InsertLogEvent(a.ToString())); //Console.WriteLine(events.Count); //events.ForEach(a => InsertLogEvent(a.ToString())); //lastLogPoll = DateTime.Now; #endregion } private Vector2 GetRobberPos() { int robberTile = latestGameState.Board.GetRobberLocation(); Edge robberCoord = GetTerrainCoords(robberTile); return board[robberCoord.FirstTile][robberCoord.SecondTile].Position/TXAGame.SCALE; } private Edge GetTerrainCoords(int index) { int row = 0; bool longrow = false; while (index >= (longrow ? 7 : 6)) { row++; index -= longrow ? 7 : 6; longrow = !longrow; } return new Edge(row, index); } internal static int GetTerrainIndex(int row, int col) { int index = 0; bool longrow = false; while (row > 0) { row--; index += longrow ? 7 : 6; longrow = !longrow; } return index + col; } private bool OmittedTile(int index) { return omitted.Contains(index); } internal static Color GetPlayerColor(int i) { switch (i) { case 0: return Color.White; case 1: return Color.RoyalBlue; case 2: return Color.Red; case 3: return Color.Orange; default: return Color.Black; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TroyXnaAPI; namespace AIsOfCatan.GUI { class GUIPlayerBox : TXADrawableComponent { public GUIPlayerBox(Vector2 position, Texture2D texture) : base(position, texture) { } protected override void DoUpdate(GameTime time) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.API { public class Edge { public int FirstTile { get; private set; } public int SecondTile { get; private set; } public Edge(int first, int second) { FirstTile = first < second ? first : second; SecondTile = first < second ? second : first; } public int[] ToArray() { return new int[] { FirstTile, SecondTile}; } public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is Edge)) return false; Edge that = (Edge)obj; return this.FirstTile == that.FirstTile && this.SecondTile == that.SecondTile; } public override int GetHashCode() { return FirstTile << 16 | SecondTile; } public override string ToString() { return "[" + FirstTile + "," + SecondTile + "]"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class PlayKnightLogEvent : LogEvent { public int Player { get; private set; } public PlayKnightLogEvent(int player) { Player = player; } public override string ToString() { return "Player " + Player + " plays a Knight"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TroyXnaAPI; namespace AIsOfCatan.GUI { class GUIPlayerInfo : TXADrawableComponent { public GUIPlayerInfo(Vector2 position) : base(position, TXAGame.WHITE_BASE) { //Text Agent Name Line, largest of the fonts //Text Agent Desc Line, smaller font //Text: Knights //Text Knight amount //Text: Long Road //Text Road Length //Text: Points //Text Point Amount //List Develop Cards //picture Bricks //Text amount bricks //picture Grain //Text amount grain //picture Ore //Text amount ore //picture lumber //Text amount lumber //picture Wool //Text amount wool } protected override void Draw(SpriteBatch batch) { //Text Agent Name Line, largest of the fonts //Text Agent Desc Line, smaller font //Text: Knights //Text Knight amount //Text: Long Road //Text Road Length //Text: Points //Text Point Amount //List Develop Cards //picture Bricks //Text amount bricks //picture Grain //Text amount grain //picture Ore //Text amount ore //picture lumber //Text amount lumber //picture Wool //Text amount wool base.Draw(batch); } protected override void DoUpdate(GameTime time) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.API; namespace AIsOfCatan { public interface IGameActions { /// <summary> /// Play a knight development card /// This allows you to move the robber to another tile and draw a card from an opponent with a building on the tile /// If you don't have a knight on your hand a InsufficientResourcesException is thrown /// A knight is automatically removed from your hand /// The largest army special card is relocated if playing this knight causes it to be /// Notice! You may only play one development card in each turn. This includes both the BeforeDiceRoll and PerformTurn methods /// </summary> /// <returns>The new state of the game after the robber has been moved and resources changed hands</returns> GameState PlayKnight(); /// <summary> /// Play a road building development card /// This allows you to build two roads free of charge /// If you don't have a RoadBuilding card on your hand a InsufficientResourcesException is thrown /// If you don't have any road pieces left a IllegalActionException is thrown /// If you try to place a road at a position where a road is already present a IllegalBuildPositionException is thrown /// If you only have one road piece left, the position to place it must be passed as firstTile1, secondTile1 (the others are ignored) /// Notice! You may only play one development card in each turn. This includes both the BeforeDiceRoll and PerformTurn methods /// </summary> /// <param name="firstEdge">The first edge to build a road along.</param> /// <param name="firstEdge">The second edge to build a road along.</param> /// <returns>The new state of the game after the roads are built</returns> GameState PlayRoadBuilding(Edge firstEdge, Edge secondEdge); /// <summary> /// Play a year of plenty development card /// This allows you to draw two resources cards of your own choice from the bank /// If you don't have a YearOfPlenty card on your hand a InsufficientResourcesException is thrown /// If the resource bank doesn't have enough cards to fulfill the request a NoMoreCardsException is thrown /// Notice! You may only play one development card in each turn. This includes both the BeforeDiceRoll and PerformTurn methods /// </summary> /// <param name="resource1">The type of resource for the first card</param> /// <param name="resource2">The type of resource for the second card</param> /// /// <returns>The new state of the game after the resources have been drawn</returns> GameState PlayYearOfPlenty(Resource resource1, Resource resource2); /// <summary> /// Play a Monopoly development card /// This will make all players give all their resources of the type you choose to you /// If you don't have a Monopoly card on your hand a InsufficientResourcesException is thrown /// All resources of the given type is removed from players hands and all given to the playing player /// Notice! You may only play one development card in each turn. This includes both the BeforeDiceRoll and PerformTurn methods /// </summary> /// <param name="resource">The resource to get monopoly on</param> /// <returns>The new state of the game after the resources have changed hands</returns> GameState PlayMonopoly(Resource resource); /// <summary> /// Propose a trade with the other players /// </summary> /// <param name="give">A list of possible combinations of resources you want to trade away</param> /// <param name="take">A list of possible combinations of resources you want to get in return</param> /// <returns>A dictionary of PlayerID => ITrade telling what the other players responded. /// If you wish to complete a trade call Trade(otherPlayer) with the id of the player you wish to trade with</returns> Dictionary<int, ITrade> ProposeTrade(List<List<Resource>> give, List<List<Resource>> take); /// <summary> /// Complete a proposed trade with a given player /// </summary> /// <param name="otherPlayer">The id of the player you wish to trade with</param> /// <returns>The updated game state after trading</returns> GameState Trade(int otherPlayer); /// <summary> /// Trades resources with the bank for the specific wanted resource at fixed rates. /// The player needs to have 4 of the resource (3 if he has a 3for1 harbor or 2 if he has the specific resource's harbor) /// in order for the trade to be valid. /// If you don't have enough resources a InsufficientResourcesException is thrown /// </summary> /// <param name="giving">The resource to pay</param> /// <param name="receiving">The resource to receive</param> /// <returns>The new state of the game after the resources have been paid and received</returns> GameState TradeBank(Resource giving, Resource receiving); /// <summary> /// Draw a development card from the pile at the cost of (1 x Grain, 1 x Wool, 1 x Ore) /// If you don't have enough resources a InsufficientResourcesException is thrown /// If the development card stack is empty a NoMoreCardsException is thrown /// Resources to pay for the card are removed from your hand and returned to the resource bank /// </summary> /// <returns>The drawn development card</returns> GameState DrawDevelopmentCard(); /// <summary> /// Build a settlement on the board at the cost of (1 x Lumber, 1 x Brick, 1 x Wool, 1 x Grain) /// If you don't have enough resources to build a settlement a InsufficientResourcesException is thrown /// If you try to build too close to another building, or not connected to one of your roads a IllegalBuildPosition is thrown /// If you don't have any more settlement pieces left to place a IllegalActionException is thrown /// The required resources are taken from your hand and placed back at the resource bank /// If the settlement is placed at a harbor, the harbor can be used immediately (rules p. 7 - footnote 12) /// </summary> /// <param name="intersection">The intersection to build at</param> /// <returns>The state of the game after the settlement has been placed</returns> GameState BuildSettlement(Intersection intersection); /// <summary> /// Upgrade an existing settlement to a city at the cost of (2 x Grain, 3 x Ore) /// If you don't have enough resources to build a city a InsufficientResourcesException is thrown /// If you try to build at a position where you don't have a settlement a IllegalBuildPosition is thrown /// If you don't have any more city pieces left to place a IllegalActionException is thrown /// The required resources are taken from your hand and placed back at the resource bank /// The settlement previously on the location is given back to you and can be placed again later /// </summary> /// <param name="intersection">The intersection to upgrade at</param> /// <returns>The state of the game after the settlement has been upgraded to a city</returns> GameState BuildCity(Intersection intersection); /// <summary> /// Build a road on the board at the cost of (1 x Lumber, 1 x Brick) /// If you don't have enough resources to build a road an InsufficientResourcesException is thrown /// If you try to build at a position not connected to another or your roads, settlements or cities an IllegalBuildPositionException is thrown /// If you don't have any more road pieces left to place an IllegalActionException is thrown /// </summary> /// <param name="edge">The edge to build a road at</param> /// <returns>The state of the game after the road has been built</returns> GameState BuildRoad(Edge edge); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.API; namespace AIsOfCatan { class StarterAgent : IAgent { private const bool silent = true; private int id; public void Reset(int assignedId) { id = assignedId; if (!silent) Console.WriteLine("IAgent reset with id " + id); } public string GetName() { return "Starter Agent #"+id; } public string GetDescription() { return ""; } public void PlaceStart(IGameState state, IStartActions actions) { if (!silent) Console.WriteLine(id + ": Place starts"); var spos = FindBestIntersection(state.Board.GetAllIntersections() .Where(i => state.Board.GetPiece(i) == null && state.Board.HasNoNeighbors(i)), state.Board); actions.BuildSettlement(spos); actions.BuildRoad(FindBestRoad(spos, state.Board)); } public void BeforeDiceRoll(IGameState state, IGameActions actions) { // We don't play knights before dice roll } public int MoveRobber(IGameState state) { if (!silent) Console.WriteLine(id + ": Move robber"); // get locations not connected to ours List<int> options = new List<int>(45); for (int i = 0; i < 45; i++) options.Add(i); int choice = options.Where(t => state.Board.GetTile(t).Terrain != Terrain.Water && state.Board.GetTile(t).Terrain != Terrain.Desert && t != state.Board.GetRobberLocation()) // legal .OrderBy(t => OwnTileValue(t, state.Board) - OpponentTileValue(t, state.Board)).First(); // own value - opponent value, lowest is best for us return choice; } public int ChoosePlayerToDrawFrom(IGameState state, int[] validOpponents) { if (!silent) Console.WriteLine(id + ": Choosing opponent to draw from"); return validOpponents.OrderBy(o => state.GetPlayerScore(o)).First(); // steal from highest points } public Resource[] DiscardCards(IGameState state, int toDiscard) { if (!silent) Console.WriteLine(id + ": Choosing cards to discard"); List<Resource> chosenDiscard = new List<Resource>(toDiscard); List<Resource> hand = state.GetOwnResources().ToList(); while (chosenDiscard.Count < toDiscard) { // pick one of the type we have most of Resource pick = hand.OrderByDescending(r => hand.Count(c => c == r)).First(); chosenDiscard.Add(pick); hand.Remove(pick); } return chosenDiscard.ToArray(); } public void PerformTurn(IGameState state, IGameActions actions) { if (!silent) Console.WriteLine(id + ": Performing main turn"); for (bool changed = true; changed; ) { changed = false; var resources = state.GetOwnResources(); //Build city if (state.GetCitiesLeft(id) > 0 && resources.Count(r => r == Resource.Grain) >= 2 && resources.Count(r => r == Resource.Ore) >= 3) { var pos = state.Board.GetPossibleCities(id); if (pos.Length > 0) { changed = true; state = actions.BuildCity(FindBestIntersection(pos,state.Board)); } } //Build settlement if (!changed && state.GetSettlementsLeft(id) > 0 && resources.Contains(Resource.Grain) && resources.Contains(Resource.Wool) && resources.Contains(Resource.Lumber) && resources.Contains(Resource.Brick)) { var pos = state.Board.GetPossibleSettlements(id); if (pos.Length > 0) { changed = true; state = actions.BuildSettlement(FindBestIntersection(pos,state.Board)); } } //Build road if (!changed && state.GetRoadsLeft(id) > 0 && resources.Contains(Resource.Lumber) && resources.Contains(Resource.Brick)) { var pos = state.Board.GetPossibleRoads(id); if (pos.Length > 0) { changed = true; state = actions.BuildRoad(FindBestRoad(pos, state.Board)); } } //Trade players if (!changed && Enum.GetValues(typeof(Resource)).Cast<Resource>().Any(r => resources.Count(res => res == r) > 2)) { // trade 1 of most for 1 missing List<List<Resource>> give = resources.OrderByDescending(r => resources.Count(res => res == r)) .GroupBy(r => resources.Count(res => res == r)).First().Distinct() .Select(r => { var list = new List<Resource>(); list.Add(r); return list; }).ToList(); List<List<Resource>> take = Enum.GetValues(typeof(Resource)).Cast<Resource>() .OrderBy(r => resources.Count(res => res == r)) .GroupBy(r => resources.Count(res => res == r)).First() .Select(r => { var list = new List<Resource>(); list.Add(r); return list; }).ToList(); if (give.Count > 0 && take.Count > 0) { Dictionary<int,ITrade> answers = actions.ProposeTrade(give, take); if (answers.Count > 0) { // trade with lowest score int otherPlayer = answers.OrderBy(kv => state.GetPlayerScore(kv.Key)).First().Key; state = actions.Trade(otherPlayer); changed = true; } } } //Trade bank foreach (Resource give in Enum.GetValues(typeof(Resource))) { if (changed) break; if (resources.Count(r => r == give) > 4) { foreach (Resource take in Enum.GetValues(typeof(Resource))) { if (changed) break; if (resources.Count(r => r == take) == 0 && state.ResourceBank[(int)take] > 0) { state = actions.TradeBank(give, take); changed = true; } } } } } } public ITrade HandleTrade(IGameState state, ITrade offer, int proposingPlayerId) { // accept if convert extras to needed and opponent < 7 points List<Resource> extras = new List<Resource>(); foreach (Resource r in Enum.GetValues(typeof(Resource))) { int extra = state.GetOwnResources().Count(res => res == r) - 1; for (int i = 0; i < extra; i++) extras.Add(r); } // good offer? var valid = offer.Give.Where(o => o.All(r => o.Count(cur => cur == r) <= extras.Count(e => e == r))); if (valid.Count() == 0) return offer.Decline(); // take the one with least cards to give, and then by most duplicates List<Resource> bestGive = valid.OrderBy(o => o.Count) .ThenByDescending(o => state.GetOwnResources().Sum(r => state.GetOwnResources().Count(res => res == r))) .First(); // find best "take" (cards we get) kind of the opposite of above List<Resource> bestTake = offer.Take.OrderBy(o => o.Count) .ThenBy(o => state.GetOwnResources().Sum(r => state.GetOwnResources().Count(res => res == r))) .First(); return offer.Respond(bestGive, bestTake); } // PRIVATE HELPERS // private int Chances(int roll) { return 6 - Math.Abs(7 - roll); } private int GetScore(Intersection inter, IBoard board) { return Chances(board.GetTile(inter.FirstTile).Value) + Chances(board.GetTile(inter.SecondTile).Value) + Chances(board.GetTile(inter.ThirdTile).Value); } private double GetScore(Edge e, IBoard board) { Intersection[] adjacentFree = board.GetAdjacentIntersections(e).Where(i => board.HasNoNeighbors(i)).ToArray(); if (adjacentFree.Length > 0) { return adjacentFree.Average(i => GetScore(i, board)); } return 0.0; } private Intersection FindBestIntersection(IEnumerable<Intersection> enumerable, IBoard board) { return enumerable.OrderByDescending(i => DifferentTypes(i,board)).ThenByDescending(i => GetScore(i,board)).First(); } private int DifferentTypes(Intersection inter, IBoard board) { return inter.ToArray().Select(i => board.GetTile(i).Terrain).Where(t => t != Terrain.Water && t != Terrain.Desert).Distinct().Count(); } private IEnumerable<Intersection> GetEnds(Intersection inter, IBoard board) { return board.GetAdjacentEdges(inter).SelectMany(e => board.GetAdjacentIntersections(e)).Where(i => !i.Equals(inter)); } private Edge GetEdgeBetween(Intersection first, Intersection second) { int[] result = first.ToArray().Where(i => second.ToArray().Contains(i)).ToArray(); if (result.Length < 2) return null; return new Edge(result[0], result[1]); } private Edge FindBestRoad(Intersection from, IBoard board) { // find the best neighbor intersection and takes the edge to that return GetEdgeBetween(FindBestIntersection(GetEnds(from, board),board),from); } private Edge FindBestRoad(IEnumerable<Edge> edges, IBoard board) { // best edge ordered by highest average of possible values on edges ends return edges.OrderBy(e => GetScore(e,board)).Last(); } private int OpponentTileValue(int tile, IBoard board) { int value = 0; foreach (Intersection i in board.GetAdjacentIntersections(tile)) { Piece curPiece = board.GetPiece(i); if (curPiece != null && curPiece.Player != id) { value += curPiece.Token == Token.City ? 2 : 1; } } return Chances(board.GetTile(tile).Value) * value; } private int OwnTileValue(int tile, IBoard board) { int value = 0; foreach(Intersection i in board.GetAdjacentIntersections(tile)){ Piece curPiece = board.GetPiece(i); if (curPiece != null && curPiece.Player == id) { value += curPiece.Token == Token.City ? 2 : 1; } } return Chances(board.GetTile(tile).Value) * value; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.API; namespace AIsOfCatan.Log { public class BuildPieceLogEvent : LogEvent { public int Player { get; private set; } public Token Piece { get; private set; } public Intersection Position { get; private set; } public BuildPieceLogEvent(int player, Token piece, Intersection position) { Player = player; Piece = piece; this.Position = position; } public override string ToString() { return "Player " + Player + " build " + Piece.ToString() + " at "+Position; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.API { public class Harbor { public HarborType Type { get; private set; } public Edge Position { get; private set; } public Harbor(HarborType type, Edge position) { this.Type = type; this.Position = position; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.API { public class Tile { public Terrain Terrain { get; private set; } public int Value { get; internal set; } public Tile(Terrain terrain, int value) { this.Terrain = terrain; this.Value = value; } public override string ToString() { return "[" + Terrain.ToString() + " : " + Value + "]"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { class AgentActionException : Exception { public bool StopGame { get; private set; } public AgentActionException(bool stopGame = false) { StopGame = stopGame; } public AgentActionException(string msg, bool stopGame = false) : base(msg) { StopGame = stopGame; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { /// <summary> /// Thrown when a player tries to buy something but haven't got sufficient resources /// </summary> class InsufficientResourcesException : AgentActionException { public InsufficientResourcesException() { } public InsufficientResourcesException(string message) : base(message) { } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using AIsOfCatan.Log; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using TroyXnaAPI; namespace AIsOfCatan { /// <summary> /// This is the main type for your game /// </summary> public class GUIControl : TXAGame { //GraphicsDeviceManager graphics; //SpriteBatch spriteBatch; GameState state; private TXAScreen startScreen; private List<LogEvent> logList; public GUIControl(GameState st) { state = st; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { /* board = new Board(0); board = board.PlaceRoad(16, 22, 1); board = board.PlaceRoad(23, 24, 2); board = board.PlaceRoad(28, 35, 3); board = board.PlacePiece(8, 14, 15, new Board.Piece(Token.Settlement, 2)); board = board.PlacePiece(28, 29, 35, new Board.Piece(Token.City, 3)); board = board.MoveRobber(23); logList = new List<LogEvent>(); logList.Add(new BuyDevLogEvent(2)); logList.Add(new RollLogEvent(1, 2)); state = new GameState(board, null, null, null, 0, logList); */ SCALE = 0.5f; base.Initialize(); graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; graphics.ApplyChanges(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); ARIAL = Content.Load<SpriteFont>("Arial"); TEXTURES.Add("T_Desert", Content.Load<Texture2D>("DesertTile")); TEXTURES.Add("T_Fields", Content.Load<Texture2D>("FieldsTile")); TEXTURES.Add("T_Forest", Content.Load<Texture2D>("ForestTile")); TEXTURES.Add("T_Hills", Content.Load<Texture2D>("HillsTile")); TEXTURES.Add("T_Mountains", Content.Load<Texture2D>("MountainsTile")); TEXTURES.Add("T_Pasture", Content.Load<Texture2D>("PastureTile")); TEXTURES.Add("T_Water", Content.Load<Texture2D>("WaterTile")); TEXTURES.Add("TO_Number", Content.Load<Texture2D>("NumberTile")); TEXTURES.Add("TO_Road", Content.Load<Texture2D>("RoadToken")); TEXTURES.Add("TO_Settle", Content.Load<Texture2D>("HouseToken")); TEXTURES.Add("TO_City", Content.Load<Texture2D>("CityToken")); TEXTURES.Add("TO_Robber", Content.Load<Texture2D>("Robber")); base.LoadContent(); startScreen = new MapScreen(state); screenManager.AddScreen("map", startScreen); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } //private long counter = 2000; /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit //if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) // this.Exit(); // TODO: Add your update logic here /* counter -= gameTime.ElapsedGameTime.Milliseconds; if (counter < 0) { Console.WriteLine("New Log event added"); logList.Add(new RollLogEvent(1, 9)); state = new GameState(board, null, null, null, 0, logList); NewGameState(state); counter += 2000; }*/ base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { // TODO: Add your drawing code here base.Draw(gameTime); } public void NewGameState(GameState state) { //assert CurrentScreen is always MapScreen MapScreen ms = screenManager.CurrentScreen as MapScreen; ms.UpdateGameState(state); } } } <file_sep>catan ========================================================== The Settlers of Catan AI Framework ---------------------------------------------------------- This project is intended as an experiment at making a framework for competing at the game of Settlers of Catan by Mayfair Games using AI's. The project is made in C# using Visual Studio 2010 and XNA 4.0. It can be found here: http://www.microsoft.com/en-us/download/details.aspx?id=23714 http://www.microsoft.com/visualstudio/eng/downloads#d-2010-express ---------------------------------------------------------- RUNNING A MATCH ---------------------------------------------------------- ???? ---------------------------------------------------------- AGENTS ---------------------------------------------------------- To create an AI you must implement the Agent interface. Each time it is your AI's turn, it will recieve an object containing everything visible about the board and the players, this includes: * The board and everything on it. * The players and what you can see without revealing secrets (hand count, development card count, number of played knights, etc.) * Your own hand and unused development cards. * Game log. The given object is also what you'll use to perform chosen actions in the game, this includes: * Playing development card. * Rolling the dice. * Proposing a trade. * Trading with the bank. * Building roads, settlements and cities. * Buying development cards. <img src="https://docs.google.com/drawings/d/1RH69Vucy1VBqW0YaUUklK9THl8kOxvpyc3Oe4-oKl4g/pub?w=960&amp;h=720"> ---------------------------------------------------------- GUI ---------------------------------------------------------- First proposal for a completed GUI: https://www.dropbox.com/s/my9ca3re0werlwr/Udkast%20til%20GUI.pdn Requires Paint.net. The 'Tab' layers are meant for viewing seperately from the rest ---------------------------------------------------------- TRADING ---------------------------------------------------------- The trickies thing about this game compared to other board games is that you have trades that can go back and forth. This dynamic is solved by having the following flow in a trade where the other AI's will get involved aswell: 1. Current player proposes a trade (can include wildcards) 2. The other players will see the trade and can accept (3a) or propose a counter-offer (without wildcards) (3b). 3a. The current player can choose between all players who accepted the offer, or cancel the trade. 3b. The current player can then accept a counter-offer or cancel the trade. <file_sep>using System; using System.Collections.Generic; using AIsOfCatan.API; namespace AIsOfCatan { /// <summary> /// This is the model of a game board of Settlers of Catan with everything that is placed on it. The methods needed for this structure is divided into four categories: /// Rule Enforcements: Methods for easy evaluation of certain necessary game statistics like longest road and validity of building positions. /// Basic Getters: Methods for observing everything on the board, both static information (tiles, numbers and harbors) and the current status of players' pieces. /// Traversal: To ease the traversal of the board for any agent with methods for getting the intersections at the ends of an edge, and the edges going from an intersection. /// Board Manipulation: The IBoard is immutable so all methods for placing pieces, roads etc. should return a new copy with the wanted change. /// </summary> public interface IBoard { #region Rule Enforcement /// <summary> /// Tells if a specific intersection is free for building. /// </summary> /// <param name="intersection">The intersection to look at.</param> /// <returns>True if the intersections if free, else false.</returns> bool CanBuildPiece(Intersection intersection); /// <summary> /// Tells if a specific edge contains no road. /// </summary> /// <param name="index1">The edge to look at.</param> /// <returns>True if there is no road on the given edge, else false.</returns> bool CanBuildRoad(Edge edge); /// <summary> /// Get the longest road on this board /// </summary> /// <returns>Dictionary of playerID -> longest road length of that player</returns> Dictionary<int, int> GetLongestRoad(); /// <summary> /// Gets the length of the given player's longest road. /// </summary> /// <param name="playerID">The player's ID.</param> /// <returns>The length of the player's longest road.</returns> int GetPlayersLongestRoad(int playerID); /// <summary> /// Checks if the given intersection has no pieces build at the /// directly connected intersections (Distance Rule). /// </summary> /// <param name="index1">The intersection to check for.</param> /// <returns>Returns true if the given intersection has no direct neighboring intersections /// containing settlements or cities, else false.</returns> bool HasNoNeighbors(Intersection intersection); /// <summary> /// Finds all possible edges where the given player can legally build roads. /// </summary> /// <param name="playerID">The player to find edges for.</param> /// <returns>An array of edges where the given player can legally build a road.</returns> Edge[] GetPossibleRoads(int playerID); /// <summary> /// Finds all possible intersections where the given player can legally build /// a settlement (i.e it is currently unoccupied). /// </summary> /// <param name="playerID">The player to find intersections for.</param> /// <returns>An array of intersections where the given player can legally /// build a settlement.</returns> Intersection[] GetPossibleSettlements(int playerID); /// <summary> /// Finds all possible intersections where the given player has a settlement. /// </summary> /// <param name="playerID">The player to find intersections for.</param> /// <returns>An array of intersections where the given player can legally /// upgrade a settlement to a city.</returns> Intersection[] GetPossibleCities(int playerID); #endregion #region Basic Getters /// <summary> /// Gives the type of terrain and dice value for a given index of the board. /// </summary> /// <param name="index">The index to check terrain for.</param> /// <returns>A Tile object containing the terrain type and dice value.</returns> Tile GetTile(int index); /// <summary> /// Give the type of terrain and dice value for the given coordinates of the board. /// </summary> /// <param name="row">The row of the tile.</param> /// <param name="column">The column of the tile. Even row numbers have a length /// of 6 and uneven has a length of 7.</param> /// <returns>A Tile object containing the terrain type and dice value.</returns> Tile GetTile(int row, int column); /// <summary> /// Gives a list of all legal intersections on the board. If this method /// proves too slow it should be modified to only calculate the intersections /// once. /// </summary> /// <returns>An array containing all intersections entirely or partly on land.</returns> Intersection[] GetAllIntersections(); /// <summary> /// Gives a list of all legal edges on the board. /// </summary> /// <returns>An array containing all edges around land tiles.</returns> Edge[] GetAllEdges(); /// <summary> /// Gives the game piece at the intersection between three different tiles. /// </summary> /// <param name="intersection">The intersection on the board to look.</param> /// <returns>The Piece object at the location, containing the type of token /// (Settlement or City) and the owning player id. If the location is empty /// it will return null.</returns> Piece GetPiece(Intersection intersection); /// <summary> /// Get all pieces built adjacent to the given tile index. /// </summary> /// <param name="index">The location of the tile.</param> /// <returns>A list of all the valid Pieces.</returns> Piece[] GetPieces(int index); /// <summary> /// Gives a (copy) of the dictionary holding all settlements and cities /// currently build on the board. /// </summary> /// <returns>A dictionary with all settlements and cities on the board.</returns> Dictionary<Intersection, Piece> GetAllPieces(); /// <summary> /// Gives the id of the player who has build a road at the requested edge. /// </summary> /// <param name="edge">The edge where the road should be.</param> /// <returns>The player id of the player who has build a road here. If empty it returns -1.</returns> int GetRoad(Edge edge); /// <summary> /// Gives a (copy) of the dictionary holding all roads currently build on the board. /// </summary> /// <returns>A dictionary with all roads on the board.</returns> Dictionary<Edge, int> GetAllRoads(); /// <summary> /// Gives an array (size 9) of Harbors containing positions (edges) and /// HarborType's for those positions. /// </summary> /// <returns>The array of Harbors on the board.</returns> Harbor[] GetHarbors(); /// <summary> /// Gives an array of Harbors that the given player has a settlement or /// city adjacent to. /// </summary> /// <param name="playerID">The player's ID.</param> /// <returns>An array of (unique) HarborTypes that the given player has.</returns> HarborType[] GetPlayersHarbors(int playerID); /// <summary> /// Gives the current location of the Robber token. /// </summary> /// <returns>The index on the board currently containing the robber.</returns> int GetRobberLocation(); #endregion #region Traversal /// <summary> /// Gives all edges (places to build roads) adjacent to the given intersection. Edges /// between two water tiles are excluded. /// </summary> /// <param name="intersection">The intersection.</param> /// <returns>An array of edges with the (up to three) edges next to the intersection.</returns> Edge[] GetAdjacentEdges(Intersection intersection); /// <summary> /// Gives all edges (places to build roads) adjacent to the given tile index. Edges /// between two water tiles are excluded. /// </summary> /// <param name="tileIndex">Tile tile index.</param> /// <returns>An array of edges with the (up to six) edges next to the tile.</returns> Edge[] GetAdjacentEdges(int tileIndex); /// <summary> /// Gives all intersections (places to build settlements and cities) /// adjacent to the given edge. /// </summary> /// <param name="edge">The edge to look at.</param> /// <returns>An array of Intersections with the (up to two) intersections at the ends of the edge.</returns> Intersection[] GetAdjacentIntersections(Edge edge); /// <summary> /// Gives all intersections (places to build settlements and cities) /// adjacent to the give tile index. /// </summary> /// <param name="tileIndex">The tile index.</param> /// <returns>An array of Intersections with the (up to six) intersections around the tile.</returns> Intersection[] GetAdjacentIntersections(int tileIndex); /// <summary> /// Gets all tiles that are adjacent to the given tile. /// </summary> /// <param name="index">The tile to look around.</param> /// <returns>A list of all the (legal) adjacent tiles.</returns> List<int> GetAdjacentTiles(int index); #endregion #region Board Manipulation /// <summary> /// Gives the resulting Board from moving the robber to /// the specified location. /// </summary> /// <param name="index">The index on the board to move the /// robber.</param> /// <returns>The resulting board.</returns> IBoard MoveRobber(int index); /// <summary> /// Places the given Piece on the specified position on the Board and /// returns the resulting Board. /// </summary> /// <param name="intersection">The intersection to place at.</param> /// <param name="p">The Piece to place on the Board.</param> /// <returns>The resulting Board from placing the Piece.</returns> IBoard PlacePiece(Intersection intersection, Piece p); /// <summary> /// Places a road on the specified position on the Board and /// returns the resulting Board. /// </summary> /// <param name="edge">The edge to place at.</param> /// <param name="playerID">The player who owns the road.</param> /// <returns>The resulting Board from placing the road.</returns> IBoard PlaceRoad(Edge edge, int playerID); #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.API { public class Intersection { public int FirstTile { get; private set; } public int SecondTile { get; private set; } public int ThirdTile { get; private set; } public Intersection(int first, int second, int third) { List<int> tiles = new List<int>(3) { first, second, third }; tiles.Sort(); FirstTile = tiles[0]; SecondTile = tiles[1]; ThirdTile = tiles[2]; } public int[] ToArray() { return new int[] { FirstTile, SecondTile, ThirdTile }; } public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is Intersection)) return false; Intersection that = (Intersection)obj; return this.FirstTile == that.FirstTile && this.SecondTile == that.SecondTile && this.ThirdTile == that.ThirdTile; } public override int GetHashCode() { return FirstTile << 16 | SecondTile << 8 | ThirdTile; } public override string ToString() { return "[" + FirstTile + "," + SecondTile + "," + ThirdTile + "]"; } } } <file_sep> namespace AIsOfCatan { /// <summary> /// To make an artificial intelligence capable of playing catan you need to implement this interface. /// The methods are called in the following order: /// * Reset /// * PlaceStart /// * PlaceStart /// Repeated until the end of the game: /// * BeforeDiceRoll /// * PerformTurn /// /// At any point the methods /// 1 MoveRobber /// 2 ChoosePlayerToDrawFrom /// 3 DiscardCards /// 4 HandleTrade /// can be called. /// #1, #2 and #3 if you roll 7. /// #3 if someone else rolls 7. /// #1 and #2 if you play a knight. /// #4 if another player proposes a trade /// /// The players of the game are referred to by an integer id. /// The id of your agent will be given when the method Reset is called. This value should be stored. /// Additional game rules and conditions can be found in the rest of the API interfaces: /// * IGameState - Contains the board, count of remaining resources and development cards + count of other players resource cards /// * IBoard - Tile types, numbers and roads, settlements and cities can be found here. /// * IStartAction - Methods to place your first settlements and roads before the game begins /// * IGameActions - Methods for taking actions during your turn. (Place road/settlement/city, play dev. card, propose trade, etc.) /// * ITrade - Information regarding a trade proposal and methods for reversing or counterproposing /// </summary> public interface IAgent { /// <summary> /// Reset the agent, getting it ready for a new game /// The agent should store the assigned Id for later in the game /// </summary> /// <param name="assignedId">The Id assigned to this player</param> void Reset(int assignedId); /// <summary> /// Return a human readable name for this agent /// This name should never change and should be implemented by just returning a string constant /// For information regarding strategy or behaviour use the getDescription() method /// </summary> /// <returns>A human readable name for this agent</returns> string GetName(); /// <summary> /// Return a description of this agent /// The description can be anything you want it to be /// Intended usages include debugging of agents and reporting current strategy /// </summary> /// <returns>A human readable description for this agent</returns> string GetDescription(); /// <summary> /// This method is called twice at the beginning of the game and is where /// the agent is to decide where to place the initial settlements and roads before the game begins /// Players receive resources from the last settlement placed in the beginning of the game /// </summary> /// <param name="state">The state of the game when the agent is to place its pieces</param> /// <param name="actions">An action object where methods for placing a settlement and a road is</param> void PlaceStart(IGameState state, IStartActions actions); /// <summary> /// In your agents turn, before the dice roll you have a chance of playing a development card. (rules p. 16 - #4) /// A maximum of one development card may be played in each turn, thus if a card is played now, it can't be /// done after the dice roll /// Reasonably the only kind of development cards it makes sense to play before the dice roll is a knight /// </summary> /// <param name="state">The state of the game when the agent is to decide whether or not to play a development card</param> /// <param name="actions">An action obejct where methods for playing development cards are. There are also methods for building which may not be called at this time</param> void BeforeDiceRoll(IGameState state, IGameActions actions); /// <summary> /// If the dice roll comes out as 7 or you play a knight you must move the robber to a new location /// After relocation of the robber, a call to ChooseOpponentToDrawFrom is made allowing your agent to choose which /// opponent, of the ones who have a building on the tile where you place the robber, you want to draw a random card from /// The robber must be moved to a new position (rules p. 10 - top) /// The robber can be moved back to the desert (riles p. 16 - note 34) /// </summary> /// <param name="state">The state of the game when the agent is to decide where to place the robber</param> /// <returns>The index of the hex where the robber will move to</returns> int MoveRobber(IGameState state); /// <summary> /// After moving the robber you must choose which player you want to draw a card from /// The array validOptions contains IDs of players with buildings on hex where the robber was placed /// If an invalid player Id is returned you will receive no resources /// </summary> /// <param name="state">The state of the game when the agent is to decide from whom to steal</param> /// <param name="validOpponents">IDs of players with buildings on hex where the robber was placed</param> /// <returns>The chosen Id from the list</returns> int ChoosePlayerToDrawFrom(IGameState state, int[] validOpponents); //You must choose an opponent to draw a card from (called after you move the robber) /// <summary> /// If a 7 is rolled on any turn, players with more than 7 cards must discard half of their cards rounded down /// In this method your agent must choose which resources to discard. /// The agents resources can be found in the supplied GameState object and the number toDiscard says how many must be discarded /// Notice! If your agent returns a wrong amount of resources, the resources to discard will be chosen at random. /// </summary> /// <param name="state">The state of the game when cards must be discarded</param> /// <param name="toDiscard">The amount of cards to discard</param> /// <returns>An array of resource types telling which cards to discard (duplicates allowed)</returns> Resource[] DiscardCards(IGameState state, int toDiscard); /// <summary> /// After the dice roll and resources have been handed out or the robber moved you can perform any number of actions /// This method is supplied a GameState which is where the current state of the game is located /// The supplied IGameActions object contains methods for doing various things that are possible during the turn /// Note that you may play at most 1 development card in each turn. This also includes in the BeforeDiceRoll method. /// When you are done with your turn simply return from the function and the next player will have his turn. /// </summary> /// <param name="state">The state of the game as the main part of your turn begins</param> /// <param name="actions">The actions you can perform during your turn. Note that performing actions doesn't update the GameState but most methods return a new updated version</param> void PerformTurn(IGameState state, IGameActions actions); /// <summary> /// During a players turn it is possible to propose a trade with the other players /// In this method you must handle this case by choosing what to do when a trade is proposed /// The input trade is the one that the current player has proposed to all players /// You may choose to either decline the offer or accept/counter the offer with other resources /// Note that even though you have acceptet the trade, it is up to the proposing player /// to choose which player he want to trade with, and if he wants to trade at all /// </summary> /// <param name="state">The state of the game</param> /// <param name="offer">The proposing players trade offer</param> /// <param name="proposingPlayerId">The id of the player who proposed the trade</param> /// <returns>Either offer.Decline() or offer.Respond(give, take) (see ITrade)</returns> ITrade HandleTrade(IGameState state, ITrade offer, int proposingPlayerId); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using AIsOfCatan.API; namespace AIsOfCatan { class HumanAgent : IAgent { private int assignedId; private bool hasPlayedDevCard = false; private Intersection getCityPosition() { Console.WriteLine("Enter 3 id's (each followed by enter) for tiles describing which settlement to upgrade to a city"); return new Intersection(int.Parse(Console.ReadLine()), int.Parse(Console.ReadLine()), int.Parse(Console.ReadLine())); } private Intersection getSettlementPosition() { Console.WriteLine("Enter 3 id's (each followed by enter) for tiles describing where to place the settlement"); return new Intersection(int.Parse(Console.ReadLine()), int.Parse(Console.ReadLine()), int.Parse(Console.ReadLine())); } private Edge getRoadPosition() { Console.WriteLine("Enter 2 id's (each followed by enter) for tiles describing where to place the road"); return new Edge(int.Parse(Console.ReadLine()), int.Parse(Console.ReadLine())); } private Resource selectResource(Resource[] resources = null) { Console.WriteLine("Select a resource:"); var res = resources ?? new Resource[] {Resource.Lumber, Resource.Brick, Resource.Grain, Resource.Ore, Resource.Wool}; for (var i = 0; i < res.Length; i++) { Console.WriteLine((i+1)+")" + res[i]); } return res[int.Parse(Console.ReadLine()) - 1]; } private Resource selectResourceTradeBank(IBoard board, Resource[] resources = null) { Console.WriteLine("Select a resource:"); var res = resources ?? new Resource[] { Resource.Lumber, Resource.Brick, Resource.Grain, Resource.Ore, Resource.Wool }; for (var i = 0; i < res.Length; i++) { Console.WriteLine((i + 1) + ")" + res[i] + " - " + TradePrice(board, res[i]) + ":1"); } return res[int.Parse(Console.ReadLine()) - 1]; } public void Reset(int assignedId) { Console.WriteLine("You are playing as player id #" + assignedId); this.assignedId = assignedId; } public string GetName() { return "Human agent " + assignedId; } public string GetDescription() { return "Cogito ergo sum"; } public void PlaceStart(IGameState state, IStartActions actions) { Console.WriteLine("It is your turn to place a starting settlement (#" + assignedId + ")"); var settlement = getSettlementPosition(); actions.BuildSettlement(settlement); Console.WriteLine("Place a road connected to the settlement you just placed"); var road = getRoadPosition(); actions.BuildRoad(road); } private IGameState PlayDevelopmentCard(IGameState state, IGameActions actions) { Console.WriteLine("Which development card do you wish to play:"); Console.WriteLine("0) None"); int i = 1; var cards = new Dictionary<int, DevelopmentCard>(); foreach (var c in state.GetOwnDevelopmentCards().Where(c => c != DevelopmentCard.VictoryPoint)) { Console.WriteLine(i + ") " + c); cards.Add(i, c); i++; } int selection = int.Parse(Console.ReadLine() ?? "0"); if (selection == 0) return null; Console.WriteLine("You played the card " + cards[selection]); hasPlayedDevCard = true; switch (cards[selection]) { case DevelopmentCard.Knight: return actions.PlayKnight(); case DevelopmentCard.Monopoly: Console.WriteLine("Choose the resource type to get monopoly on"); return actions.PlayMonopoly(selectResource()); case DevelopmentCard.RoadBuilding: Console.WriteLine("Decide where to build the two roads"); var road1 = getRoadPosition(); var road2 = getRoadPosition(); return actions.PlayRoadBuilding(road1, road2); case DevelopmentCard.YearOfPlenty: Console.WriteLine("Choose which two resources you want to draw"); return actions.PlayYearOfPlenty(selectResource(), selectResource()); } return null; } public void BeforeDiceRoll(IGameState state, IGameActions actions) { hasPlayedDevCard = false; if (!state.GetOwnDevelopmentCards().Any(dc => dc != DevelopmentCard.VictoryPoint)) return; //No cards to play Console.WriteLine("Do you want to use a Development Card before roling the dice? Y/N"); var r = Console.ReadLine() ?? ""; if (!r.ToLower().StartsWith("y")) return; PlayDevelopmentCard(state, actions); } public int MoveRobber(IGameState state) { Console.WriteLine("Choose where to place the robber by typing in the id of a position: "); return int.Parse(Console.ReadLine()); } public int ChoosePlayerToDrawFrom(IGameState state, int[] validOpponents) { Console.WriteLine("Choose which opponent to draw a card from: "); foreach (int o in validOpponents) { Console.Write(o + ") Agent #"+o); } Console.WriteLine(); return int.Parse(Console.ReadLine()); } public Resource[] DiscardCards(IGameState state, int toDiscard) { Console.WriteLine("You must discard " + toDiscard + " cards from you hand:"); var hand = state.GetOwnResources().ToList(); var cards = new Resource[toDiscard]; while (toDiscard-- > 0) { Console.WriteLine("Select a resource to discard:"); foreach (Resource resource in Enum.GetValues(typeof (Resource))) { if (hand.Count(r => r == resource) == 0) continue; Console.WriteLine(((int)resource) + ") " + resource + " x " + hand.Count(r => r == resource)); } //Keep trying if answering wrong do { cards[toDiscard] = (Resource)int.Parse(Console.ReadLine()); } while (!hand.Remove(cards[toDiscard])); } return cards; } private bool hasRes(IGameState state, Resource res, int amount = 1) { return state.GetOwnResources().Count(r => r == res) >= amount; } public void PerformTurn(IGameState state, IGameActions actions) { Console.WriteLine("It is now your turn (#" + assignedId + ")"); while (true) { try { Console.Write("Resources: ["); foreach (Resource resource in Enum.GetValues(typeof (Resource))) { var count = state.GetOwnResources().Count(r => r == resource); if (count == 0) continue; Console.Write(resource + " x " + count + ", "); } Console.WriteLine("]"); Console.Write("Dev. cards: ["); foreach (DevelopmentCard devcard in Enum.GetValues(typeof(DevelopmentCard))) { var count = state.GetOwnDevelopmentCards().Count(r => r == devcard); if (count == 0) continue; Console.Write(devcard + " x " + count + ", "); } Console.WriteLine("]"); bool canBuildRoad = hasRes(state, Resource.Lumber) && hasRes(state, Resource.Brick); //TODO: has any more pieces bool canBuildSettlement = hasRes(state, Resource.Brick) && hasRes(state, Resource.Lumber) && hasRes(state, Resource.Grain) && hasRes(state, Resource.Wool); //TODO: has any more pieces bool canBuildCity = hasRes(state, Resource.Ore, 3) && hasRes(state, Resource.Grain, 2); //TODO: has any more pieces bool canBuyDevCard = hasRes(state, Resource.Grain) && hasRes(state, Resource.Ore) && hasRes(state, Resource.Wool); //TODO: any more dev cards bool canTradeBank = true, canTradePlayers = true; //TODO: Implement these Console.WriteLine("Choose an action:"); Console.WriteLine("0) End turn"); if (canBuildRoad) Console.WriteLine("1) Build road"); if (canBuildSettlement) Console.WriteLine("2) Build settlement"); if (canBuildCity) Console.WriteLine("3) Build city"); if (canBuyDevCard) Console.WriteLine("4) Buy development card"); if (!hasPlayedDevCard && state.GetOwnDevelopmentCards().Count(d => d != DevelopmentCard.VictoryPoint) > 0) Console.WriteLine("5) Play development card"); if (canTradeBank) Console.WriteLine("6) Trade resources with the bank"); if (canTradePlayers) Console.WriteLine("7) Trade resources with the other players"); int answer = int.Parse(Console.ReadLine() ?? "0"); switch (answer) { case 1: //road var roadPos = getRoadPosition(); state = actions.BuildRoad(roadPos); break; case 2: //settlement var settlementPos = getSettlementPosition(); state = actions.BuildSettlement(settlementPos); break; case 3: //city var cityPos = getCityPosition(); state = actions.BuildCity(cityPos); break; case 4: //buy dev state = actions.DrawDevelopmentCard(); break; case 5: //play dev state = PlayDevelopmentCard(state, actions) ?? state; break; case 6: //trade bank Console.WriteLine("Choose which resource to give"); var tbGive = selectResourceTradeBank(state.Board); Console.WriteLine("Choose which resource to receive"); var tbTake = selectResource(); state = actions.TradeBank(tbGive, tbTake); break; case 7: //trade players Console.WriteLine("Which resource type do you want to give away:"); var tpGiveType = selectResource(); Console.WriteLine("How many " + tpGiveType + " do you want to give:"); var tpGiveAmount = int.Parse(Console.ReadLine() ?? "2"); Console.WriteLine("Which resource type do you want to get in return for " + tpGiveAmount + " " + tpGiveType + "? :"); var tpTakeType = selectResource(); Console.WriteLine("How many " + tpTakeType + " do you want to get:"); var tpTakeAmount = int.Parse(Console.ReadLine() ?? "1"); var give = new List<List<Resource>>(){new List<Resource>()}; for (int i = 0; i < tpGiveAmount; i++) give[0].Add(tpGiveType); var take = new List<List<Resource>>(){new List<Resource>()}; for (int i = 0; i < tpTakeAmount; i++) take[0].Add(tpTakeType); var feedback = actions.ProposeTrade(give, take); Console.WriteLine("The other players responded:"); foreach (var f in feedback) { Console.Write(f.Key + ") "); Console.Write(f.Value.Status + " "); if (f.Value.Status == TradeStatus.Countered) { Console.Write("(They give: "); Console.Write(f.Value.Give[0].Select(r => r.ToString()).Aggregate((a,b) => a + ", " + b)); Console.Write(" for "); Console.Write(f.Value.Take[0].Select(r => r.ToString()).Aggregate((a, b) => a + ", " + b)); Console.WriteLine(")"); } else { Console.WriteLine(); } } Console.WriteLine("Select a player to trade with by entering the id or -1 to cancel"); int reply = int.Parse(Console.ReadLine() ?? "-1"); if (reply != -1) { state = actions.Trade(reply); } break; default: return; } } catch (AgentActionException ex) { Console.WriteLine("Illegal action! Message: " + ex.Message); } catch(FormatException ex) { Console.WriteLine("Illegal input! Message: " + ex.Message); } } } private int TradePrice(IBoard board, Resource giving) { var harbors = board.GetPlayersHarbors(assignedId); var hasSpecific = harbors.Contains((HarborType)giving); var hasGeneral = harbors.Contains(HarborType.ThreeForOne); return (hasSpecific) ? 2 : ((hasGeneral) ? 3 : 4); } public ITrade HandleTrade(IGameState state, ITrade offer, int proposingPlayerId) { Console.WriteLine("You were asked if you wanted to trade."); Console.WriteLine("This is not yet implemented, so you declined."); return offer.Decline(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.API; namespace AIsOfCatan { class DebugAgent : IAgent { private const bool silent = true; private bool hasDevcardToPlay = false; private DevelopmentCard nextToPlay; private int id; private Intersection start1 = new Intersection( 21, 27, 28 ); private bool firstStartPlaced = false; private Intersection start2 = new Intersection( 9, 15, 16 ); private Intersection tooClose = new Intersection ( 21, 22, 28 ); private Edge farRoad = new Edge( 34, 35 ); public void Reset(int assignedId) { id = assignedId; if (!silent) Console.WriteLine("IAgent reset with id " + id); } public string GetName() { return "Debug Agent"; } public string GetDescription() { return ""; } public void PlaceStart(IGameState state, IStartActions actions) { if (!silent) Console.WriteLine(id + ": Place starts"); if (!firstStartPlaced) { firstStartPlaced = true; actions.BuildSettlement(start1); if (!silent) Console.WriteLine(id + ": First settlement built succesfully"); actions.BuildRoad(new Edge(start1.FirstTile, start1.SecondTile)); if (!silent) Console.WriteLine(id + ": First road built succesfully"); } else { try { actions.BuildSettlement(start1); if (!silent) Console.WriteLine(id + ": Controller allowed a building on top of another"); } catch (IllegalBuildPositionException e) { if (!silent) Console.WriteLine(id + ": Controller threw exception as expected: " + e.Message); } try { actions.BuildSettlement(tooClose); if (!silent) Console.WriteLine(id + ": Controller allowed a building too close"); } catch (IllegalBuildPositionException e) { if (!silent) Console.WriteLine(id + ": Controller threw exception as expected: " + e.Message); } actions.BuildSettlement(start2); Console.WriteLine(id + ": Second settlement built succesfully"); try { actions.BuildRoad(farRoad); if (!silent) Console.WriteLine(id + ": Controller allowed a building disconnected road"); } catch (IllegalBuildPositionException e) { if (!silent) Console.WriteLine(id + ": Controller threw exception as expected: " + e.Message); } actions.BuildRoad(new Edge(start2.FirstTile,start2.SecondTile)); if (!silent) Console.WriteLine(id + ": Second road built succesfully"); } } public void BeforeDiceRoll(IGameState state, IGameActions actions) { if (!silent) Console.WriteLine(id + ": Before dice roll"); } public int MoveRobber(IGameState state) { if (!silent) Console.WriteLine(id + ": Move robber"); return ((GameState)state).Board.GetRobberLocation() == 8 ? 9 : 8; } public int ChoosePlayerToDrawFrom(IGameState state, int[] validOpponents) { if (!silent) Console.WriteLine(id + ": Choosing opponent to draw from"); return validOpponents[0]; } public Resource[] DiscardCards(IGameState state, int toDiscard) { if (!silent) Console.WriteLine(id + ": Choosing cards to discard"); return ((GameState)state).GetOwnResources().Take(toDiscard).ToArray(); } public void PerformTurn(IGameState state, IGameActions actions) { if (!silent) Console.WriteLine(id + ": Performing main turn"); var resources = ((GameState)state).GetOwnResources(); int[] resCount = new int[5]; foreach (var r in resources) resCount[(int)r]++; if (!silent) Console.Write(id + ": Resources: ( "); foreach (var i in resCount) if (!silent) Console.Write(i + " "); if (!silent) Console.WriteLine(")"); if (hasDevcardToPlay) { hasDevcardToPlay = false; if (!silent) Console.WriteLine("-----------"); if (!silent) Console.WriteLine("Has a dev card to play: " + nextToPlay); switch (nextToPlay) { case DevelopmentCard.Knight: if (!silent) Console.WriteLine("Play knight"); state = ((MainActions) actions).PlayKnight(); break; case DevelopmentCard.Monopoly: if (!silent) Console.WriteLine("Play monopoly"); state = ((MainActions)actions).PlayMonopoly(Resource.Ore); break; case DevelopmentCard.RoadBuilding: if (!silent) Console.WriteLine("Play road building"); state = ((MainActions)actions).PlayRoadBuilding(new Edge(27,28), new Edge(28, 34)); break; case DevelopmentCard.YearOfPlenty: if (!silent) Console.WriteLine("Play year of plenty"); state = ((MainActions)actions).PlayYearOfPlenty(Resource.Grain, Resource.Wool); break; } if (!silent) Console.WriteLine("-----------"); } resources = ((GameState)state).GetOwnResources(); if (resources.Contains(Resource.Grain) && resources.Contains(Resource.Ore) && resources.Contains(Resource.Wool)) { var prevCards = ((GameState) state).GetOwnDevelopmentCards(); state = actions.DrawDevelopmentCard(); if (!silent) Console.WriteLine("Drawn developmentcard successfully"); hasDevcardToPlay = true; var cards = ((GameState) state).GetOwnDevelopmentCards().ToList(); foreach (var developmentCard in prevCards) { cards.Remove(developmentCard); } nextToPlay = cards.ToArray()[0]; } else { try { actions.DrawDevelopmentCard(); if (!silent) Console.WriteLine("WARNING! Was able to buy a development card with not enough resources"); } catch (InsufficientResourcesException e) { if (!silent) Console.WriteLine("exceptions was thrown as excpected"); } } } public ITrade HandleTrade(IGameState state, ITrade offer, int proposingPlayerId) { if (!silent) Console.WriteLine(id + ": Handling trade"); return offer; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { public static class ExtensionMethods { public static void ForEach<T>(this IEnumerable<T> list, System.Action<T> action) { foreach (T item in list) action(item); } public static void Shuffle<T>(this IList<T> list, int seed) { Random rng = new Random(seed); int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } public static string ToDeepString<T>(this IEnumerable<List<T>> enumerable) { if (enumerable.Count() < 1) return "[]"; StringBuilder builder = new StringBuilder("["); foreach( List<T> item in enumerable) { builder.Append(item.ToListString() + "/"); } builder.Remove(builder.Length - 1, 1); // remove last slash builder.Append("]"); return builder.ToString(); } public static string ToListString<T>(this IEnumerable<T> enumerable) { if (enumerable.Count() < 1) return "[]"; StringBuilder builder = new StringBuilder("["); foreach (var item in enumerable) { builder.Append(item.ToString() + "/"); } builder.Remove(builder.Length - 1, 1); // remove last slash builder.Append("]"); return builder.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.Log; using System.Threading; using AIsOfCatan.API; namespace AIsOfCatan { public class GameController { private Random diceRandom; private Random shuffleRandom; private Player[] players; private List<LogEvent> log = new List<LogEvent>(); private const bool debug = false; private const int maxRounds = 100; private IBoard board; private List<DevelopmentCard> developmentCardStack = new List<DevelopmentCard>(); private int[] resourceBank; private int turn; private int round = -1; private int largestArmySize = 2; //One less than the minimum for getting the largest army card private int longestRoadLength = 0; private int largestArmyId = -1; private int longestRoadId = -1; private const int LargestArmyMinimum = 3; private const int LongestRoadMinimum = 5; private bool visual = false; private bool logToFile = false; private GUIControl gui; /// <summary> /// Start the game. This method will run for the length of the game and returns the id of the winner /// </summary> /// <param name="agents">The competing agents (The order in which they are submitted is irrelevant)</param> /// <param name="boardSeed">The seed for the board generator, used to shuffle development cards, and for drawing a random card after moving the robber</param> /// <param name="diceSeed">The seed for the dice</param> /// <param name="visual">True if the game should be displayed visually</param> /// <param name="visual">True if the game should save the game log to a file</param> /// <returns>The id of the winner of the game (-1 in case of error)</returns> public int StartGame(IAgent[] agents, int boardSeed, int diceSeed, bool visual, bool logToFile) { this.visual = visual; this.logToFile = logToFile; //Initialize random number generators diceRandom = new Random(diceSeed); shuffleRandom = new Random(boardSeed); //The card deck is based on the seed of the board //Build player list players = new Player[agents.Length]; for (int i = 0; i < agents.Length; i++) { players[i] = new Player(agents[i], i); } //Set up board board = new Board(boardSeed); PopulateDevelopmentCardStack(); resourceBank = new int[] { 19, 19, 19, 19, 19 }; //Start the game! turn = 0; //StartGUI(); if (visual) { Thread guiThread = new Thread(StartGUI); guiThread.Start(); Thread.Sleep(5000); } PlaceStarts(); int result = GameLoop(); if (logToFile) System.IO.File.WriteAllLines(DateTime.Now.ToString("s").Replace(":","").Replace("-","")+" GameLog.txt", log.Select(l => l.ToString())); return result; } public int StartGame(IAgent[] agents, int boardSeed, int diceSeed) { return StartGame(agents, boardSeed, diceSeed, false, false); } private void StartGUI() { gui = new GUIControl(new GameState(board, developmentCardStack, resourceBank, players, turn, log, longestRoadId, largestArmyId)); gui.Run(); } private void Log(LogEvent evt) { log.Add(evt); if (debug) Console.WriteLine("LOG!: " + evt); } /// <summary> /// Populate and shuffle the development card stack according to the rules (rules p. 2 - Game Contents) /// </summary> private void PopulateDevelopmentCardStack() { developmentCardStack.Clear(); for (int i = 0; i < 14; i++) developmentCardStack.Add(DevelopmentCard.Knight); for (int i = 0; i < 5; i++) developmentCardStack.Add(DevelopmentCard.VictoryPoint); for (int i = 0; i < 2; i++) { developmentCardStack.Add(DevelopmentCard.RoadBuilding); developmentCardStack.Add(DevelopmentCard.YearOfPlenty); developmentCardStack.Add(DevelopmentCard.Monopoly); } //Shuffle! for (int n = developmentCardStack.Count-1; n > 1; n--) { int k = shuffleRandom.Next(n); var aux = developmentCardStack[k]; developmentCardStack[k] = developmentCardStack[n]; developmentCardStack[n] = aux; } } /// <summary> /// Executes the game, each player turn by turn until a player wins /// </summary> /// <returns>The Id of the winning player</returns> private int GameLoop() { while (round < maxRounds) { if (turn == 0) round++; try { TakeTurn(players[turn]); if (debug) ShowScores(); } finally { } /*catch (AgentActionException e) { Console.WriteLine("Player " + players[turn].Id + ", caused an exception: " + e.GetType().Name); Console.WriteLine("\t\t-> Message: " + e.Message); //Console.WriteLine(e.StackTrace); if (e.StopGame) { Console.WriteLine("This is game breaking, and the game ends now."); return -1; } }*/ if (HasWon(players[turn])) return players[turn].Id; NextTurn(); } return -1; } private void ShowScores() { Console.Write("\tScoreboard: ["); foreach (Player p in players) { Console.Write("#" + p.Id + " " + p.Agent.GetName() + " : " + GetPoints(p) + " , "); } Console.WriteLine("]"); } /// <summary> /// Find out if a given player has won (if his number of victory points is over or equal to 10) /// </summary> /// <param name="player">The player to test</param> /// <returns>True if the player has 10 or more victory points</returns> private Boolean HasWon(Player player) { return (GetPoints(player) >= 10); } /// <summary> /// Find out how many victory points a given player has /// Points are counted as: /// Settlements give 1 point each /// Cities give 2 points each /// Victory point development cards give 1 point each /// Having the largest army or the longest road give 2 points each. /// </summary> /// <param name="player">The player to test</param> /// <returns>How many victory points the player has</returns> private int GetPoints(Player player) { int points = 0; points += (5 - player.SettlementsLeft) * 1; points += (4 - player.CitiesLeft) * 2; points += player.DevelopmentCards.Count(c => c == DevelopmentCard.VictoryPoint) * 1; if (player.Id == largestArmyId) points += 2; if (player.Id == longestRoadId) points += 2; return points; } /// <summary> /// Executes all parts of a players turn /// 1. Allow the play of a development card before the dice are rolled /// 2. Roll the dice, hand out resources to all players, and move the robber if roll is 7 /// 3. Allow all actions according to the rules /// </summary> /// <param name="player">The player whose turn it is</param> private void TakeTurn(Player player) { var actions = new MainActions(player, this); player.Agent.BeforeDiceRoll(CurrentGamestate(), actions); int roll = RollDice(); actions.DieRoll(); Log(new RollLogEvent(player.Id,roll)); if (roll == 7) { //Discard if over 7 cards foreach (var p in players) { if (p.Resources.Count > 7) { var cards = p.Agent.DiscardCards(CurrentGamestate(p.Id), p.Resources.Count / 2); if (cards.Length != p.Resources.Count / 2) { //Clone, shuffle, take, convert cards = p.Resources.ToList().OrderBy(e => Guid.NewGuid()).Take(p.Resources.Count / 2).ToArray(); } foreach (var c in cards) { PayResource(p, c); } Log(new DiscardCardsLogEvent(p.Id,cards.ToList())); } } MoveRobber(player, CurrentGamestate()); } else { HandOutResources(roll); } var afterResourcesState = CurrentGamestate(); player.Agent.PerformTurn(afterResourcesState, actions); player.NewDevelopmentCards.Clear(); //Reset new development cards } /// <summary> /// Let a player move the robber to a new location and draw a random card from a player with a building on the tile /// If the agent moves the robber to a water tile or the tile that it was already on, nothing will happen /// If the agent tries to draw a card from a unaffected player, no cards will be drawn /// </summary> /// <param name="player">The player that must move the robber</param> /// <param name="gameState">The gamestate to send to the player</param> private void MoveRobber(Player player, GameState gameState) { int robberPosition = player.Agent.MoveRobber(gameState); if (board.GetTile(robberPosition).Terrain == Terrain.Water || robberPosition == board.GetRobberLocation()) { Console.WriteLine("IAgent " + player.Agent.GetType().Name + " moved robber illegally"); throw new AgentActionException("Agent " + player.Agent.GetType().Name + " moved robber illegally", true); } board = board.MoveRobber(robberPosition); Log(new MoveRobberLogEvent(player.Id, robberPosition)); //Draw a card from an opponent var opponents = new List<int>(); foreach (var piece in board.GetPieces(robberPosition)) { if (piece.Player == player.Id) continue; if (opponents.Contains(piece.Player)) continue; opponents.Add(piece.Player); } if (opponents.Count == 0) return; //No opponents to draw from int choice = player.Agent.ChoosePlayerToDrawFrom(CurrentGamestate(), opponents.ToArray()); if (!opponents.Contains(choice)) { Console.WriteLine("IAgent " + player.Agent.GetType().Name + " chose an illegal player to draw from"); return; } if (players[choice].Resources.Count == 0) return; //Nothing to take Log(new StealCardLogEvent(player.Id, choice)); //Move a card from one player to another var position = shuffleRandom.Next(players[choice].Resources.Count); var toMove = players[choice].Resources[position]; players[choice].Resources.RemoveAt(position); player.Resources.Add(toMove); } /// <summary> /// Hand out resources to players according to a roll /// Gives resources to players with buildings on tiles with a number corresponding to the roll /// and only if the tile doesn't have the robber. /// If there is not enough resources of a kind in the bank so that all player who shall receive, /// can get the amount they are allowed to, none of that kind are dealt (see rules p. 8 top) /// </summary> /// <param name="roll">The value of the roll</param> private void HandOutResources(int roll) { //Map from PlayerID to dictionary that maps resource to amount var handouts = new Dictionary<int, Dictionary<Resource, int>>(); var handoutSums = new Dictionary<Resource, int>(); for (int i = 0; i < players.Length; i++) { handouts[i] = new Dictionary<Resource, int>(); foreach (Resource r in Enum.GetValues(typeof(Resource))) handouts[i][r] = 0; } foreach (Resource r in Enum.GetValues(typeof(Resource))) handoutSums[r] = 0; //Count how many resources to be dealt for (int i = 0; i <= 44; i++) { var tile = board.GetTile(i); if (tile.Value != roll || board.GetRobberLocation() == i) continue; if (tile.Terrain == Terrain.Desert || tile.Terrain == Terrain.Water) continue; foreach (var piece in board.GetPieces(i)) { int incr = (piece.Token == Token.Settlement) ? 1 : 2; handouts[piece.Player][(Resource)tile.Terrain] += incr; handoutSums[(Resource)tile.Terrain] += incr; } } //Check if there are enough resources in the bank foreach (var resource in handoutSums.Keys) { if (resourceBank[(int)resource] < handoutSums[resource]) { for (int i = 0; i < players.Length; i++) { handouts[i][resource] = 0; } } } //Hand out resources foreach (var player in players) { List<Resource> logResources = new List<Resource>(); foreach (var resource in handouts[player.Id].Keys) { GetResource(player, resource, handouts[player.Id][resource]); for (var i = 0; i < handouts[player.Id][resource]; i++) logResources.Add(resource); } Log(new ReceiveResourcesLogEvent(logResources.ToArray(), player.Id)); } } /// <summary> /// Let the players place their starting settlements and roads and receive resources /// from all neighboring tiles from the last placed settlement (rules p. 7 top) /// </summary> private void PlaceStarts() { foreach (Player p in players) { var state = CurrentGamestate(); var actions = new StartActions(players[turn], this); players[turn].Agent.PlaceStart(state, actions); if (!actions.IsComplete()) { throw new AgentActionException("Agent " + p.Agent.GetType().Name + " did not place the correct amount of start pieces (1/2)", true); } var spos = actions.GetSettlementPosition(); Log(new BuildPieceLogEvent(p.Id,Token.Settlement,spos)); var rpos = actions.GetRoadPosition(); Log(new BuildRoadLogEvent(p.Id, rpos)); NextTurn(); } foreach (Player p in players.Reverse()) { PrevTurn(); var state = CurrentGamestate(); var actions = new StartActions(players[turn], this); players[turn].Agent.PlaceStart(state, actions); if (!actions.IsComplete()) { throw new AgentActionException("Agent " + p.Agent.GetType().Name + " did not place the correct amount of start piece (2/2)", true); } var spos = actions.GetSettlementPosition(); Log(new BuildPieceLogEvent(p.Id, Token.Settlement, spos)); var rpos = actions.GetRoadPosition(); Log(new BuildRoadLogEvent(p.Id, rpos)); //Hand out resources foreach (var pos in actions.GetSettlementPosition().ToArray()) { Terrain terrain = board.GetTile(pos).Terrain; if (terrain == Terrain.Desert || terrain == Terrain.Water) continue; //can't get desert or water GetResource(players[turn], (Resource)board.GetTile(pos).Terrain); } } } /// <summary> /// Roll two d6 using the seeded random number generator and get the sum /// </summary> /// <returns>The sum of the roll</returns> private int RollDice() { int d1 = diceRandom.Next(1,7); int d2 = diceRandom.Next(1,7); if(debug) Console.WriteLine("Rolled " + d1 + ", " + d2 + " = " + (d1+d2)); return d1+d2; } /// <summary> /// Increment the turn variable modulo the number of players /// </summary> private void NextTurn() { turn = (turn + 1) % players.Length; } /// <summary> /// Decrement the turn variable, if it goes below 0, wrap around /// </summary> private void PrevTurn() { turn = turn - 1; if (turn < 0) turn += players.Length; } /// <summary> /// Let a given player pay an amount of a resource to the bank /// </summary> /// <param name="player">The player that must pay</param> /// <param name="resource">The type of resource to pay</param> /// <param name="quantity">The quantity of the resource to pay (default 1)</param> private void PayResource(Player player, Resource resource, int quantity = 1) { for (int i = 0; i < quantity; i++) { if (!player.Resources.Contains(resource)) throw new InsufficientResourcesException("Player out of " + resource); player.Resources.Remove(resource); resourceBank[(int)resource]++; } } /// <summary> /// Give a player an amount of some resource /// If there are no more cards in the pile an NoMoreCardsException is thrown /// </summary> /// <param name="player">The player to give resources to</param> /// <param name="resource">The type of resource he receives</param> /// <param name="quantity">The amount of the resource he receives (default 1)</param> private void GetResource(Player player, Resource resource, int quantity = 1) { for (int i = 0; i < quantity; i++) { if (resourceBank[(int)resource] == 0) throw new NoMoreCardsException("Resource bank is out of " + resource.ToString()); player.Resources.Add(resource); resourceBank[(int)resource]--; } } private GameState CurrentGamestate(int playerId) { GameState gs = new GameState(board, developmentCardStack, resourceBank, players, playerId, log, longestRoadId, largestArmyId); if (visual) { gui.NewGameState(gs); } return gs; } private GameState CurrentGamestate() { return CurrentGamestate(turn); } /// <summary> /// Figure out if a given edge on the board is connected to a given players road in some end /// </summary> /// <param name="edge">The edge to check</param> /// <param name="playerId">The id of the player to test</param> /// <returns>True if the edge is connected to a road</returns> private bool RoadConnected(IBoard board, Edge edge, int playerId) { return board.GetAdjacentIntersections(edge) .SelectMany(inter => board.GetAdjacentEdges(inter)) .Any(e => board.GetRoad(e) == playerId); } /// <summary> /// Update the player who has the longest road to be able to determine who has how many points /// </summary> private void UpdateLongestRoad() { var playersLongest = board.GetLongestRoad(); var newLength = playersLongest.OrderByDescending(p => p.Value).First().Value; if (newLength < LongestRoadMinimum) //Don't hand out the card if road is too short { longestRoadId = -1; return; } var ids = playersLongest.Where(p => p.Value == newLength).Select(p => p.Key); var newId = (ids.Count()) > 1 ? -1 : ids.First(); /* if (newLength > longestRoadLength) //Road is longer than previously (can only happen with a valid player ID) { longestRoadLength = newLength; longestRoadId = newId; } else if (newLength < longestRoadLength && newId != -1) //Previously longest must have been divided but someone has a longest road { longestRoadLength = newLength; longestRoadId = newId; } else if (newLength < longestRoadLength && newId == -1) //Previously longest must have been divided and others are tied { longestRoadLength = newLength; longestRoadId = -1; } else if (newLength == longestRoadLength) { //Do nothing } * */ //Reduced to: if (newLength == longestRoadLength) return; longestRoadLength = newLength; longestRoadId = newId; } /// <summary> /// Get a list of playable development cards for a given player /// Newly bought development cards cannot be played in the same round /// </summary> /// <param name="player">The player for whom to get the list of playable development cards</param> /// <returns>The list of playable development cards</returns> private List<DevelopmentCard> GetPlayableDevelopmentCards(Player player) { var playable = new List<DevelopmentCard>(); foreach (var card in player.DevelopmentCards) { if (player.NewDevelopmentCards.Contains(card)) { player.NewDevelopmentCards.Remove(card); } else { playable.Add(card); } } return playable; } /* * ACTIONS */ /// <summary> /// Let a player draw a development card /// If the player doesn't have enough resources a InsufficientResourcesException is thrown /// If the development card stack is empty a NoMoreCardsException is thrown /// Resources to pay for the card are removed from the player hand and returned to the resource bank /// </summary> /// <param name="player">The player drawing a development card</param> /// <returns>The drawn development card</returns> public GameState DrawDevelopmentCard(Player player) { var r = player.Resources; if (!(r.Contains(Resource.Grain) && r.Contains(Resource.Wool) && r.Contains(Resource.Ore))) throw new InsufficientResourcesException("Not enough resources to buy a development card"); if (developmentCardStack.Count == 0) throw new NoMoreCardsException("Development card stack is empty"); PayResource(player, Resource.Grain); PayResource(player, Resource.Wool); PayResource(player, Resource.Ore); var last = developmentCardStack.Last(); developmentCardStack.RemoveAt(developmentCardStack.Count-1); Log(new BuyDevLogEvent(player.Id)); player.DevelopmentCards.Add(last); player.NewDevelopmentCards.Add(last); return CurrentGamestate(); } private readonly Dictionary<int, Dictionary<int, Trade>> proposedTrades = new Dictionary<int, Dictionary<int, Trade>>(); //TODO: Move this public Dictionary<int, ITrade> ProposeTrade(Player player, List<List<Resource>> give, List<List<Resource>> take) { var trade = new Trade(give, take); var dict = new Dictionary<int, Trade>(); //Reversed trades var replyDict = new Dictionary<int, ITrade>(); Log(new ProposeTradeLogEvent(player.Id, trade.Give, trade.Take)); var state = CurrentGamestate(); foreach (var other in players) { if (other.Id == player.Id) continue; //No need to propose a trade with yourself dict[other.Id] = (Trade)other.Agent.HandleTrade(state, trade.Reverse(), player.Id); if (dict[other.Id].Status == TradeStatus.Countered) { replyDict[other.Id] = dict[other.Id].Reverse(); //Note, take and give are swapped since dict[other.Id] is as seen from the opponent var giveLog = dict[other.Id].Take.Where(c => c.Count > 0).Select(r => r[0]).ToList(); var takeLog = dict[other.Id].Give.Where(c => c.Count > 0).Select(r => r[0]).ToList(); Log(new CounterTradeLogEvent(other.Id, giveLog, takeLog)); break; } } proposedTrades[player.Id] = dict; return replyDict; } public GameState CompleteTrade(Player player, int playerid) { if (!proposedTrades.ContainsKey(player.Id)) throw new IllegalActionException("Tried to complete a trade, but no trade proposed"); if (!proposedTrades[player.Id].ContainsKey(playerid) || playerid < 0 || playerid >= players.Length) throw new IllegalActionException("Tried to complete a trade with an illegal player Id"); var trade = proposedTrades[player.Id][playerid]; //remember that the trade is as seen from the opponents pov var opponent = players[playerid]; if (trade.Status == TradeStatus.Declined) throw new IllegalActionException("Tried to complete a declined trade"); //Validate trade if (trade.Give.Count > 1 || trade.Take.Count > 1) { throw new IllegalActionException("Player " + player.Id + "(" + player.Agent.GetName() + ") tried to complete an invalid trade with Player " + opponent.Id + "(" + opponent.Agent.GetName() + ")"); } //Validate that players have enough resources (maybe do this earlier?) foreach (Resource resource in Enum.GetValues(typeof(Resource))) { //Give - other must have if (trade.Give[0].Count(r => r == resource) > opponent.Resources.Count(r => r == resource)) throw new InsufficientResourcesException("Player " + opponent.Id + "(" + opponent.Agent.GetName() + ") does not have enough resource to complete trade"); //Take - this must have if (trade.Take[0].Count(r => r == resource) > player.Resources.Count(r => r == resource)) throw new InsufficientResourcesException("Player " + player.Id + "(" + player.Agent.GetName() + ") does not have enough resource to complete trade"); } //Complete trade foreach (var res in trade.Give[0]) { opponent.Resources.Remove(res); player.Resources.Add(res); } foreach (var res in trade.Take[0]) { player.Resources.Remove(res); opponent.Resources.Add(res); } Log(new AcceptTradeLogEvent(player.Id, playerid, trade.Give[0], trade.Take[0])); return CurrentGamestate(); } /// <summary> /// Let a player play a knight development card /// If the player doesn't have a knight on his hand a InsufficientResourcesException is thrown /// A knight is removed from the players hand /// The largest army special card is relocated if playing this knight causes it to be /// </summary> /// <param name="player">The player playing a knight</param> public GameState PlayKnight(Player player) { var playable = GetPlayableDevelopmentCards(player); if (!playable.Contains(DevelopmentCard.Knight)) throw new InsufficientResourcesException("No knight found in hand"); player.DevelopmentCards.Remove(DevelopmentCard.Knight); player.PlayedKnights++; if (player.PlayedKnights > largestArmySize) { largestArmySize = player.PlayedKnights; largestArmyId = player.Id; } MoveRobber(player, CurrentGamestate()); Log(new PlayKnightLogEvent(player.Id)); return CurrentGamestate(); } /// <summary> /// Let a player play a road building development card /// If the player doesn't have a RoadBuilding card on his hand a InsufficientResourcesException is thrown /// If the player doesn't have any road pieces left a IllegalActionException is thrown /// If the player tries to place a road at a position where a road is already present a IllegalBuildPositionException is thrown /// If the player only has one road piece left, the position to place it must be passed as road1Tile1, road1Tile2 (the others are ignored) /// </summary> /// <param name="player">The player that plays the RoadBuilding development card</param> /// <param name="firstRoad">The first edge to build a road on</param> /// <param name="secondRoad">The second edge to build a road on</param> public GameState PlayRoadBuilding(Player player, Edge firstRoad, Edge secondRoad) { var playable = GetPlayableDevelopmentCards(player); if (!playable.Contains(DevelopmentCard.RoadBuilding)) throw new InsufficientResourcesException("No Road building found in hand"); if (player.RoadsLeft == 0) throw new IllegalActionException("No more road pieces left of your color"); //Must always check road1 if (!board.CanBuildRoad(firstRoad)) throw new IllegalBuildPositionException("The chosen position is illegal or occupied"); if (board.GetRoad(firstRoad) != -1) throw new IllegalBuildPositionException("There is already a road on the selected position"); if (player.RoadsLeft == 1) { if (!RoadConnected(board, firstRoad, player.Id)) throw new IllegalBuildPositionException("The chosen position is not connected to any of your pieces"); player.RoadsLeft--; board = board.PlaceRoad(firstRoad, player.Id); Log(new PlayRoadBuildingLogEvent(player.Id, firstRoad)); } else { //Check road 2 if (!board.CanBuildRoad(secondRoad)) throw new IllegalBuildPositionException("The chosen position is illegal or occupied"); if (board.GetRoad(secondRoad) != -1) throw new IllegalBuildPositionException("There is already a road on the selected position"); //Can't build the same road twice if ((firstRoad.FirstTile == secondRoad.FirstTile && firstRoad.SecondTile == secondRoad.SecondTile) || (firstRoad.FirstTile == secondRoad.SecondTile && firstRoad.SecondTile == secondRoad.FirstTile)) throw new IllegalBuildPositionException("Can't build the same road twice (roadbuilding dev. card)"); //Place the connected road first (to be able to check that both are connected in the end if (RoadConnected(board, firstRoad, player.Id)) { var temp = board.PlaceRoad(firstRoad, player.Id); if (RoadConnected(temp, secondRoad, player.Id)) { board = temp.PlaceRoad(secondRoad, player.Id); player.RoadsLeft -= 2; } } else if (RoadConnected(board, secondRoad, player.Id)) { var temp = board.PlaceRoad(secondRoad, player.Id); if (RoadConnected(temp, firstRoad, player.Id)) { board = temp.PlaceRoad(firstRoad, player.Id); player.RoadsLeft -= 2; } } else { throw new IllegalBuildPositionException("The chosen positions are not connected to any of your buildings or roads"); } Log(new PlayRoadBuildingLogEvent(player.Id, firstRoad, secondRoad)); } player.DevelopmentCards.Remove(DevelopmentCard.RoadBuilding); UpdateLongestRoad(); return CurrentGamestate(); } /// <summary> /// Let a player play a year of plenty development card /// If the player doesn't have a YearOfPlenty card on his hand a InsufficientResourcesException is thrown /// If the resource bank doesn't have enough cards to fulfill the request a NoMoreCardsException is thrown /// </summary> /// <param name="player">The player playing the year of plenty development card</param> /// <param name="resource1">The type of resource for the first card</param> /// <param name="resource2">The type of resource for the second card</param> public GameState PlayYearOfPlenty(Player player, Resource resource1, Resource resource2) { var playable = GetPlayableDevelopmentCards(player); if (resourceBank[(int)resource1] == 0) throw new NoMoreCardsException("Resource bank is out of " + resource1); if (resourceBank[(int)resource2] == 0) throw new NoMoreCardsException("Resource bank is out of " + resource2); if (!playable.Contains(DevelopmentCard.YearOfPlenty)) throw new InsufficientResourcesException("No Year of Plenty found in hand"); player.DevelopmentCards.Remove(DevelopmentCard.YearOfPlenty); GetResource(player, resource1); GetResource(player, resource2); Log(new PlayYearOfPlentyLogEvent(player.Id, resource1, resource2)); return CurrentGamestate(); } /// <summary> /// Let a player play a Monopoly development card /// If the player doesn't have a Monopoly card on his hand a InsufficientResourcesException is thrown /// All resources of the given type is removed from players hands and all given to the playing player /// </summary> /// <param name="player">The player playing the monopoly development card</param> /// <param name="resource">The resource to get monopoly on</param> /// <returns></returns> public GameState PlayMonopoly(Player player, Resource resource) { var playable = GetPlayableDevelopmentCards(player); if (!playable.Contains(DevelopmentCard.Monopoly)) throw new InsufficientResourcesException("No Monopoly in hand"); player.DevelopmentCards.Remove(DevelopmentCard.Monopoly); //Take all resources of the given type out of all hands int count = players.Sum(t => t.Resources.RemoveAll(c => c == resource)); //And place them in the playing players hand for (int i = 0; i < count; i++) { player.Resources.Add(resource); } Log(new PlayMonopolyLogEvent(player.Id, resource, count)); return CurrentGamestate(); } /// <summary> /// Let a player build a settlement /// If the player doesn't have enough resources to build a settlement a InsufficientResourcesException is thrown /// If the player tries to build too close to another building, or not connected to a road a IllegalBuildPosition is thrown /// If the player doesn't have any more settlement pieces left to place a IllegalActionException is thrown /// The required resources are taken from the player and placed back at the resource bank /// If the settlement is placed at a harbor, the harbor can be used immediately (rules p. 7 - footnote 12) /// </summary> /// <param name="player">The player building a settlement</param> /// <param name="inter">The intersection to build a settlement on</param> /// <returns></returns> public GameState BuildSettlement(Player player, Intersection inter) { var r = player.Resources; if (!(r.Contains(Resource.Grain) && r.Contains(Resource.Wool) && r.Contains(Resource.Brick) && r.Contains(Resource.Lumber))) throw new InsufficientResourcesException("Not enough resources to buy a settlement"); if (player.SettlementsLeft == 0) throw new IllegalActionException("No more settlement pieces left of your color"); if (board.GetPiece(inter) != null) throw new IllegalBuildPositionException("The chosen position is occupied by another building"); if (!board.HasNoNeighbors(inter)) throw new IllegalBuildPositionException("The chosen position violates the distance rule"); if (board.GetRoad(new Edge(inter.FirstTile,inter.SecondTile)) != player.Id && board.GetRoad(new Edge(inter.FirstTile,inter.ThirdTile)) != player.Id && board.GetRoad(new Edge(inter.SecondTile, inter.ThirdTile)) != player.Id) throw new IllegalBuildPositionException("The chosen position has no road leading to it"); if (!board.CanBuildPiece(inter)) throw new IllegalBuildPositionException("The chosen position is not valid"); PayResource(player, Resource.Grain); PayResource(player, Resource.Wool); PayResource(player, Resource.Brick); PayResource(player, Resource.Lumber); Log(new BuildPieceLogEvent(player.Id, Token.Settlement, inter)); player.SettlementsLeft--; board = board.PlacePiece(inter, new Piece(Token.Settlement, player.Id)); UpdateLongestRoad(); return CurrentGamestate(); } /// <summary> /// Let a player upgrade a settlement to a city /// If the player doesn't have enough resources to build a city a InsufficientResourcesException is thrown /// If the player tries to build at a position where he doesn't have a settlement a IllegalBuildPosition is thrown /// If the player doesn't have any more city pieces left to place a IllegalActionException is thrown /// The required resources are taken from the player and placed back at the resource bank /// The settlement previously on the location is given back to the player /// </summary> /// <param name="player">The player upgrading to a city</param> /// <param name="intersection">The intersection to upgrade to a city on</param> /// <returns></returns> public GameState BuildCity(Player player, Intersection intersection) { var r = player.Resources; if (!(r.Count(c => c == Resource.Ore) >= 3 && r.Count(c => c == Resource.Grain) >= 2)) throw new InsufficientResourcesException("Not enough resources to buy a city"); if (player.CitiesLeft == 0) throw new IllegalActionException("No more city pieces left of your color"); Piece piece = board.GetPiece(intersection); if (piece == null || piece.Player != player.Id || piece.Token != Token.Settlement) throw new IllegalBuildPositionException("The chosen position does not contain one of your settlements"); PayResource(player, Resource.Ore, 3); PayResource(player, Resource.Grain, 2); Log(new BuildPieceLogEvent(player.Id, Token.City, intersection)); player.CitiesLeft--; player.SettlementsLeft++; board = board.PlacePiece(intersection, new Piece(Token.City, player.Id)); return CurrentGamestate(); } /// <summary> /// Let a player build a road /// If the player doesn't have enough resources to build a road an InsufficientResourcesException is thrown /// If the player tries to build at a position not connected to another road, settlement or city an IllegalBuildPositionException is thrown /// If the player doesn't have any more road pieces left to place an IllegalActionException is thrown /// </summary> /// <param name="player">The player building a road</param> /// <param name="edge">The to build a road on</param> /// <returns></returns> public GameState BuildRoad(Player player, Edge edge) { var r = player.Resources; if (!(r.Contains(Resource.Brick) && r.Contains(Resource.Lumber))) throw new InsufficientResourcesException("Not enough resources to buy a road"); if (player.RoadsLeft == 0) throw new IllegalActionException("No more road pieces left of your color"); if (board.GetRoad(edge) != -1) throw new IllegalBuildPositionException("The chosen position is occupied by another road"); if (!RoadConnected(board, edge, player.Id)) throw new IllegalBuildPositionException("The chosen position is not connected to any of your pieces"); if (!board.CanBuildRoad(edge)) throw new IllegalBuildPositionException("The chosen position is not valid"); PayResource(player, Resource.Brick); PayResource(player, Resource.Lumber); Log(new BuildRoadLogEvent(player.Id, edge)); player.RoadsLeft--; board = board.PlaceRoad(edge, player.Id); UpdateLongestRoad(); return CurrentGamestate(); } /// <summary> /// Let a player build a settlement without a requirement for connectivity and free of charge /// The settlement still has to follow the distance rule and cannot be placed on top of another building /// </summary> /// <param name="player">The player placing the settlement</param> /// <param name="intersection">The intersection to build a settlement on</param> public GameState BuildFirstSettlement(Player player, Intersection intersection) { if (board.GetPiece(intersection) != null) throw new IllegalBuildPositionException("The chosen position is occupied by another building"); if (!board.HasNoNeighbors(intersection)) throw new IllegalBuildPositionException("The chosen position violates the distance rule"); if (!board.CanBuildPiece(intersection)) throw new IllegalBuildPositionException("The chosen position is not valid"); player.SettlementsLeft--; board = board.PlacePiece(intersection, new Piece(Token.Settlement, player.Id)); return CurrentGamestate(); } /// <summary> /// Let a player build a road without a requirement for connectivity and free of charge /// The road may not be placed on top of another road /// Connectivity with previously placed settlement should be controlled elsewhere (in StartActions.cs) /// </summary> /// <param name="player">The player placing the road</param> /// <param name="edge">The edge to build the road on</param> public GameState BuildFirstRoad(Player player, Edge edge) { if (board.GetRoad(edge) != -1) throw new IllegalBuildPositionException("The chosen position is occupied by another road"); if (!board.CanBuildRoad(edge)) throw new IllegalBuildPositionException("The chosen position is not valid"); player.RoadsLeft--; board = board.PlaceRoad(edge, player.Id); return CurrentGamestate(); } /// <summary> /// Trade resources with the bank /// If no harbor is owned trading is 4 : 1 /// If a general harbor is owned trading is 3 : 1 /// Special harbors trade a specific resource 2 : 1 /// </summary> /// <param name="player">The player wanting to trade</param> /// <param name="giving">The resource that the player want to give</param> /// <param name="receiving">The resource that the player want to receive</param> /// <returns>The updated gamestate after trading</returns> public GameState TradeBank(Player player, Resource giving, Resource receiving) { if (resourceBank[(int)receiving] == 0) throw new NoMoreCardsException("Resource bank has no more resources of type " + receiving); var harbors = board.GetPlayersHarbors(player.Id); var hasSpecific = harbors.Contains((HarborType) giving); var hasGeneral = harbors.Contains(HarborType.ThreeForOne); var amountToGive = (hasSpecific) ? 2 : ((hasGeneral) ? 3 : 4); if (player.Resources.Count(r => r == giving) < amountToGive) throw new InsufficientResourcesException("Player hasn't got enough resources to trade"); PayResource(player,giving,amountToGive); GetResource(player,receiving); Log(new TradeBankLogEvent(player.Id,giving,amountToGive,receiving)); return CurrentGamestate(); } /// <summary> /// Returns the current game board held by this controller. /// </summary> /// <returns>The game board.</returns> public IBoard GetBoard() { return board; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class ReceiveResourcesLogEvent : LogEvent { public int Player { get; private set; } public Resource[] Resources { get; private set; } public ReceiveResourcesLogEvent(Resource[] resources, int playerId) { this.Player = playerId; this.Resources = resources; } public override string ToString() { return "Player " + Player + " received " + Resources.ToListString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class RollLogEvent : LogEvent { public int Player { get; private set; } public int Roll { get; private set; } public RollLogEvent(int player, int roll) { Player = player; Roll = roll; } public override string ToString() { return "Player " + Player + " rolled " + Roll; } } } <file_sep>using System.Linq; using AIsOfCatan.API; namespace AIsOfCatan { public class StartActions : IStartActions { private readonly Player player; private readonly GameController controller; private bool settlementBuilt = false; private bool roadBuilt = false; private Intersection settlementPosition; private Edge roadPosition; public StartActions(Player player, GameController controller) { this.player = player; this.controller = controller; } /// <summary> /// Returns whether the start action has been completed /// </summary> public bool IsComplete() { return roadBuilt && settlementBuilt; } /// <summary> /// Internal method used for handing out resources /// </summary> public Intersection GetSettlementPosition() { return settlementPosition; } /// <summary> /// Internal method used for handing out resources /// </summary> public Edge GetRoadPosition() { return roadPosition; } /// <summary> /// Build a settlement on the board /// If you try to build too close to another building a IllegalBuildPosition is thrown /// Must be called before BuildRoad, otherwise an IllegalActionException is thrown /// </summary> /// <param name="firstTile">The intersection</param> public void BuildSettlement(Intersection intersection) { if (settlementBuilt) throw new IllegalActionException("Only one settlement may be built in a turn during the startup"); settlementPosition = intersection; controller.BuildFirstSettlement(player, intersection); settlementBuilt = true; } /// <summary> /// Build a road on the board /// If you try to build at a position not connected to the newly placed settlement an IllegalBuildPositionException is thrown /// If you try to build more than one road an IllegalActionException is thrown /// </summary> /// <param name="firstTile">The first tile that the road will be along</param> /// <param name="secondTile">The second tile that the road will be along</param> public void BuildRoad(Edge edge) { if (roadBuilt) throw new IllegalActionException("Only one road may be built in a turn during the startup"); if (!settlementBuilt) throw new IllegalActionException("The settlement must be placed before the road"); int[] array = new int[] { settlementPosition.FirstTile, settlementPosition.SecondTile, settlementPosition.ThirdTile }; if (!(array.Contains(edge.FirstTile) && array.Contains(edge.SecondTile))) throw new IllegalBuildPositionException("The road must be placed next to the settlement"); roadPosition = edge; controller.BuildFirstRoad(player, edge); roadBuilt = true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { /// <summary> /// Thrown when a build fails because it's in an illegal position /// </summary> class IllegalBuildPositionException : AgentActionException { public IllegalBuildPositionException() { } public IllegalBuildPositionException(string message) : base(message) { } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TroyXnaAPI; using AIsOfCatan.API; namespace AIsOfCatan { class GUITile : TXADrawableComponent { public static int TileWidth() { return 222; } public static int TileHeight() { return 255; } private static float TileShift() { return (float)Math.Sqrt(Math.Pow(TileWidth(), 2) - Math.Pow((TileWidth() / 2), 2)); } //private static readonly Vector2 EAST = new Vector2(0, TILE_WIDTH); //private static readonly Vector2 WEST = new Vector2(0, -TILE_WIDTH); //private static readonly Vector2 S_EAST = new Vector2(TileShift, TILE_WIDTH / 2); //private static readonly Vector2 N_EAST = new Vector2(-TileShift, TILE_WIDTH / 2); //private static readonly Vector2 S_WEST = new Vector2(TileShift, -TILE_WIDTH / 2); //private static readonly Vector2 N_WEST = new Vector2(-TileShift, -TILE_WIDTH / 2); private bool Omitted { get; set; } private Vector2 numberPos; private Vector2 textPos; private readonly Color valueColour; private Tile Tile { get; set; } public GUITile(int x, int y, Tile tile, bool omit) : base( new Vector2((float) ((x+0.5+(y % 2 == 0 ? 0.5 : 0))*TileWidth()), (float) ((0.66+y)*TileShift())), GetTexture(tile.Terrain) ) { Tile = tile; Omitted = omit; NumAreaAndTextPos(); valueColour = (Tile.Value == 6 || Tile.Value == 8 ? Color.Red : Color.Black); } //private int X { get; set; } //private int Y { get; set; } private static Texture2D GetTexture(Terrain ter) { return TXAGame.TEXTURES["T_" + ter]; } protected override void DoUpdate(GameTime time) { if (Omitted && Visible) { //!OmittedTile(MapScreen.GetTerrainIndex(Y, X)) Visible = false; } } private void NumAreaAndTextPos() { int width = (int)(TXAGame.TEXTURES["TO_Number"].Width * TXAGame.SCALE); int height = (int)(TXAGame.TEXTURES["TO_Number"].Height * TXAGame.SCALE); numberPos = new Vector2( (Position.X) - (width / 2), (Position.Y) - (height / 2)); Vector2 measurementValue = TXAGame.ARIAL.MeasureString(Tile.Value.ToString(CultureInfo.InvariantCulture))* TXAGame.SCALE; textPos = Position - (measurementValue/2); } protected override void Draw(SpriteBatch batch) { base.Draw(batch); if (Visible) { if (IsTileNumbered(Tile)) { batch.Draw(TXAGame.TEXTURES["TO_Number"], numberPos, null, Color.Wheat, 0f, new Vector2(0, 0), TXAGame.SCALE, SpriteEffects.None, 0.0f); batch.DrawString(TXAGame.ARIAL, Tile.Value.ToString(CultureInfo.InvariantCulture), textPos, valueColour, 0f, new Vector2(0, 0), TXAGame.SCALE, SpriteEffects.None, 0.0f); } } } private static bool IsTileNumbered(Tile tile) { switch (tile.Terrain) { case Terrain.Pasture: case Terrain.Mountains: case Terrain.Hills: case Terrain.Fields: case Terrain.Forest: return true; default: return false; } // } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TroyXnaAPI; namespace AIsOfCatan { class GUIRoad : TXADrawableComponent { private int PlayerId { get; set; } public int Tile1 { get; private set; } public int Tile2 { get; private set; } public GUIRoad(Vector2 position, float rotation, int playerId, int tile1, int tile2) : base(position, TXAGame.TEXTURES["TO_Road"],rotation) { PlayerId = playerId; Tile1 = tile1; Tile2 = tile2; } protected override void DoUpdate(GameTime time) { //throw new NotImplementedException(); } protected override void Draw(SpriteBatch batch) { if (Visible) { batch.Draw(Texture, Position, null, MapScreen.GetPlayerColor(PlayerId), Rotation, Origin, TXAGame.SCALE, SpriteEffects.None, 0f); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class PlayMonopolyLogEvent : LogEvent { public int Player { get; private set; } public Resource Resource { get; private set; } public int Gained { get; private set; } public PlayMonopolyLogEvent(int player, Resource res, int cardsGained) { Player = player; Resource = res; Gained = cardsGained; } public override string ToString() { return "Player " + Player + " plays Monopoly on " + Resource + " and gets " + Gained + " cards"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using AIsOfCatan.API; namespace AIsOfCatan { #if WINDOWS || XBOX static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { //PerformGameBenchmarking(); var controller = new GameController(); var agents = new IAgent[] { new StarterAgent(), new StarterAgent(), new StarterAgent(), new StarterAgent() }; // new HumanAgent() int intWinner = controller.StartGame(agents, 10, 0, false, true); if (intWinner != -1) { var winner = agents[intWinner]; Console.WriteLine("Winner is: " + winner.GetName() + " (" + intWinner + ")"); } else { Console.WriteLine("It is a draw after 100 rounds"); } Console.WriteLine(controller.GetBoard()); } static void PerformGameBenchmarking() { Dictionary<int, int> wins = new Dictionary<int, int>(4); for (int i = 0; i < 1000; i++) { var controller = new GameController(); var agents = new IAgent[] { new StarterAgent(), new StarterAgent(), new StarterAgent() }; // new HumanAgent() int intWinner = controller.StartGame(agents, i, i, false, false); //var winner = agents[intWinner]; if (wins.ContainsKey(intWinner)) { wins[intWinner] = wins[intWinner] + 1; } else { wins.Add(intWinner, 1); } Console.WriteLine(i + ": P " + intWinner + " wins."); } Console.WriteLine(); wins.OrderBy(w => w.Key).ForEach(kv => Console.WriteLine("Player " + kv.Key + ": " + kv.Value + " wins.")); } } #endif } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { interface ILogEntry { int Turn { get; }} class BasicLogEntry : ILogEntry { public BasicLogEntry(int turn) { Turn = turn; } public int Turn { get; private set; } } interface IDiceRollLogEntry : ILogEntry { int Roll { get; } } class DiceRollLogEntry : BasicLogEntry, IDiceRollLogEntry { public DiceRollLogEntry(int turn, int roll) : base(turn) { Roll = roll; } public int Roll { get; private set; } public override string ToString() { return "Player " + Turn + " rolled " + Roll; } } interface IPlayKnightLogEntry : ILogEntry { int RobberPosition { get; } } class PlayKnightLogEntry : BasicLogEntry, IPlayKnightLogEntry { public PlayKnightLogEntry(int turn, int position) : base(turn) { RobberPosition = position; } public int RobberPosition { get; private set; } } class ActionLog { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TroyXnaAPI; namespace AIsOfCatan { public class GUIPiece : TXADrawableComponent { public int Tile1 { get; private set; } public int Tile2 { get; private set; } public int Tile3 { get; private set; } private Token type; public Token Type { get { return type; } set { type = value; Texture = GetTex(type); } } public int Player { get; private set; } public GUIPiece(Vector2 position, int player, Token token, int t1, int t2, int t3) : base(position, GetTex(Token.Settlement)) { Player = player; Type = token; Tile1 = t1; Tile2 = t2; Tile3 = t3; //throw new NotImplementedException(); } private static Texture2D GetTex(Token token) { switch (token) { case Token.City: return TXAGame.TEXTURES["TO_City"]; case Token.Settlement: default: return TXAGame.TEXTURES["TO_Settle"]; } } protected override void Draw(SpriteBatch batch) { if (Visible) { batch.Draw(Texture, Position, null, MapScreen.GetPlayerColor(Player), Rotation, Origin, TXAGame.SCALE, SpriteEffects.None, 0f); } } protected override void DoUpdate(GameTime time) { //throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class DiscardCardsLogEvent : LogEvent { public int Player { get; private set; } private List<Resource> cards; public List<Resource> Cards { get { return cards.ToList(); } } public DiscardCardsLogEvent(int player, List<Resource> cards) { Player = player; this.cards = cards; } public override string ToString() { return "Player " + Player + " discards " + cards.ToListString(); } } } <file_sep>using Microsoft.Xna.Framework; using TroyXnaAPI; namespace AIsOfCatan { class GUIRobber : TXADrawableComponent { public GUIRobber(Vector2 pos) : base(pos, TXAGame.TEXTURES["TO_Robber"]) { } protected override void DoUpdate(GameTime time) { } public void UpdateRobberPosition(Vector2 pos) { Position = pos; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.Log; namespace AIsOfCatan { // 19 of each in bank public enum Resource { Brick, Lumber, Wool, Grain, Ore }; // names from wikipedia // 3 4 4 4 3 1 X public enum Terrain { Hills, Forest, Pasture, Fields, Mountains, Desert, Water } // 14 5 2 2 2 public enum DevelopmentCard { Knight, VictoryPoint, RoadBuilding, YearOfPlenty, Monopoly } public enum Token { Settlement, City }; public enum HarborType { Brick, Lumber, Wool, Grain, Ore, ThreeForOne }; //----------------------------------------------------------------------------------------// public interface IGameState { /// <summary> /// /// </summary> IBoard Board { get; } /// <summary> /// /// </summary> int DevelopmentCards { get; } /// <summary> /// /// </summary> int[] ResourceBank { get; } /// <summary> /// /// </summary> int[] AllPlayerIds { get; } /// <summary> /// /// </summary> int LongestRoadId { get; } /// <summary> /// /// </summary> int LargestArmyId { get; } /// <summary> /// /// </summary> /// <param name="playerId"></param> /// <returns></returns> int GetPlayerScore(int playerId); /// <summary> /// /// </summary> /// <returns></returns> int GetRoundNumber(); /// <summary> /// /// </summary> /// <param name="playerID"></param> /// <returns></returns> int GetResourceCount(int playerID); /// <summary> /// /// </summary> /// <param name="playerID"></param> /// <returns></returns> int GetDevelopmentCardCount(int playerID); /// <summary> /// /// </summary> /// <param name="playerID"></param> /// <returns></returns> int GetKnightCount(int playerID); /// <summary> /// /// </summary> /// <param name="playerID"></param> /// <returns></returns> int GetSettlementsLeft(int playerID); /// <summary> /// /// </summary> /// <param name="playerID"></param> /// <returns></returns> int GetCitiesLeft(int playerID); /// <summary> /// /// </summary> /// <param name="playerID"></param> /// <returns></returns> int GetRoadsLeft(int playerID); /// <summary> /// /// </summary> /// <returns></returns> Resource[] GetOwnResources(); /// <summary> /// /// </summary> /// <returns></returns> DevelopmentCard[] GetOwnDevelopmentCards(); /// <summary> /// /// </summary> /// <param name="res"></param> /// <returns></returns> int GetResourceBank(Resource res); /// <summary> /// /// </summary> /// <param name="amount"></param> /// <returns></returns> List<LogEvent> GetLatestEvents(int amount); /// <summary> /// /// </summary> /// <param name="time"></param> /// <returns></returns> List<LogEvent> GetEventsSince(DateTime time); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { /// <summary> /// Thrown on attempts to draw cards from an empty pile /// </summary> class NoMoreCardsException : AgentActionException { public NoMoreCardsException() { } public NoMoreCardsException(string message) : base(message) { } } } <file_sep>using System; using System.Diagnostics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TroyXnaAPI; namespace AIsOfCatan { class GUIBufferTextBlock : TXATextBlock { private static Vector2 Buffer = new Vector2(3,3); private Vector2 textPos; public GUIBufferTextBlock(Vector2 pos) : base(pos) { textPos = Position + Buffer; } public GUIBufferTextBlock(Vector2 pos, int bufSize) : this(pos) { Buffer = new Vector2(bufSize, bufSize); textPos = Position + Buffer; } protected override void DoUpdate(GameTime time) { base.DoUpdate(time); textPos = Position + Buffer; } protected override void Draw(SpriteBatch batch) { if (Visible) { batch.DrawString(TXAGame.ARIAL, Text, textPos, Color.Black, Rotation, Origin, TXAGame.SCALE, SpriteEffects.None, 0f); } } protected override void UpdateRect() { Vector2 textVector; if (Text != null) { textVector = TXAGame.ARIAL.MeasureString(Text) * TXAGame.SCALE; } else { textVector = TXAGame.ARIAL.MeasureString("") * TXAGame.SCALE; } Area = new Rectangle( (int) (Math.Round(Position.X)), (int) (Math.Round(Position.Y)), (int) (Math.Round(textVector.X + (Buffer.X*2))), (int) (Math.Round(textVector.Y + (Buffer.Y*2)))); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { /// <summary> /// Thrown when a player tries to perform an illegal action on the GameController /// </summary> class IllegalActionException : AgentActionException { public IllegalActionException() { } public IllegalActionException(string message) : base(message) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { public class LogEvent { private DateTime time = DateTime.Now; public DateTime TimeStamp { get { return time; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class PlayYearOfPlentyLogEvent : LogEvent { public int Player { get; private set; } public Resource First { get; private set; } public Resource Second { get; private set; } public PlayYearOfPlentyLogEvent(int player, Resource first, Resource second) { Player = player; First = first; Second = second; } public override string ToString() { return "Player " + Player + " plays Year of Plenty to gain " + First + " and " + Second; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class MoveRobberLogEvent : LogEvent { public int Player { get; private set; } public int Tile { get; private set; } public MoveRobberLogEvent(int player, int tile) { Player = player; Tile = tile; } public override string ToString() { return "Player " + Player + " moves the Robber to tile " + Tile; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.API; namespace AIsOfCatan.Log { public class PlayRoadBuildingLogEvent : LogEvent { public int Player { get; private set; } public Edge First { get; private set; } public Edge Second { get; private set; } public PlayRoadBuildingLogEvent(int player, Edge first, Edge second = null) { Player = player; this.First = first; this.Second = second; } public override string ToString() { return "Player " + Player + " plays Road Building and builds on " + First + " and " + Second; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { public enum TradeStatus {Declined, Countered, Untouched}; public class Trade : ITrade { // For a Wildcard put several Resource in the same inner list. public List<List<Resource>> Give { get; private set; } public List<List<Resource>> Take { get; private set; } public TradeStatus Status { get; private set; } public Trade(List<List<Resource>> give, List<List<Resource>> take){ this.Give = give; this.Take = take; Status = TradeStatus.Untouched; } public ITrade Respond(List<Resource> give, List<Resource> take) { return new Trade(new List<List<Resource>> {give}, new List<List<Resource>> {take}) { Status = TradeStatus.Countered }; } public ITrade Decline() { Status = TradeStatus.Declined; return this; } public Trade Reverse() { return new Trade(DeepClone(Take),DeepClone(Give)) {Status = Status}; } private static List<List<Resource>> DeepClone(List<List<Resource>> list) { var result = new List<List<Resource>>(list.Count); result.AddRange(list.Select(l => new List<Resource>(l))); return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.GUI { class GUIPlayerView { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { /// <summary> /// Data object containing information about a player in the game /// </summary> public class Player { public Player(IAgent agent, int id) { agent.Reset(id); RoadsLeft = 15; //You start with 15 roads CitiesLeft = 4; // - and 4 cities SettlementsLeft = 5; // - and 5 settlements, according to (rules p. 2 - Game Contents) PlayedKnights = 0; Agent = agent; Id = id; DevelopmentCards = new List<DevelopmentCard>(); NewDevelopmentCards = new List<DevelopmentCard>(); Resources = new List<Resource>(); } /// <summary> /// How many knights has this player played in this game so far /// </summary> public int PlayedKnights { get; set; } /// <summary> /// How many road pieces does this player have left to place /// </summary> public int RoadsLeft { get; set; } /// <summary> /// How many city pieces does this player have left to place /// </summary> public int CitiesLeft { get; set; } /// <summary> /// How many settlement pieces does this player have left to place /// </summary> public int SettlementsLeft { get; set; } /// <summary> /// The agent deciding actions for this player /// </summary> public IAgent Agent { get; private set; } /// <summary> /// The Id of this player /// </summary> public int Id { get; private set; } /// <summary> /// The development cards that this player has in his hand /// </summary> public List<DevelopmentCard> DevelopmentCards { get; private set; } /// <summary> /// The development cards that this player has drawn in this turn (and cannot play until next turn) /// </summary> public List<DevelopmentCard> NewDevelopmentCards { get; private set; } /// <summary> /// The resource cards that this player has in his hand /// </summary> public List<Resource> Resources { get; private set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.API; namespace AIsOfCatan { public class Board : IBoard { private static readonly int[] WaterTiles = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 18, 19, 25, 26, 31, 32, 33, 37, 38, 39, 40, 41, 42, 43, 44 }; private static readonly int[] placementOrder = new int[] { 8, 14, 20, 27, 34, 35, 36, 30, 24, 17, 10, 9, 15, 21, 28, 29, 23, 16, 22 }; private static readonly int[] valueOrder = new int[] { 11, 2, 9, 4, 3, 6, 4, 11, 10, 3, 9, 6, 5, 8, 5, 10, 8, 12 }; private static readonly Edge[] harborEdges = new Edge[] { new Edge(1, 8), new Edge(3, 9), new Edge(11, 17), new Edge(24, 25), new Edge(30, 37), new Edge(35, 42), new Edge(34, 40), new Edge(26, 27), new Edge(13, 14)}; public static int GetRowLength(int row) { return row % 2 == 0 ? 6 : 7; } private Intersection[] allIntersections = null; // to minimize computation private Edge[] allEdges = null; private Tile[][] terrain; private Harbor[] harbors; private Dictionary<Edge, int> roads; private Dictionary<Intersection, Piece> settlements; private int robberLocation; private Board(Tile[][] terrain, Dictionary<Edge, int> roads, Dictionary<Intersection, Piece> settlements, int robber, Harbor[] harbors, Intersection[] inter, Edge[] edges) : this() { this.allEdges = edges; this.allIntersections = inter; this.terrain = terrain; this.roads = roads; this.settlements = settlements; this.robberLocation = robber; this.harbors = harbors; } private Board() { // initialize fields roads = new Dictionary<Edge, int>(22); settlements = new Dictionary<Intersection, Piece>(22); harbors = new Harbor[9]; // create board terrain = new Tile[7][]; bool longrow = false; for (int i = 0; i < 7; i++) { terrain[i] = new Tile[longrow ? 7 : 6]; longrow = !longrow; } // place water foreach (int water in WaterTiles) { Tuple<int, int> coords = GetTerrainCoords(water); terrain[coords.Item1][coords.Item2] = new Tile(Terrain.Water, 0); } } public Board(int terrainSeed, int numberSeed) : this() { InitTerrain(terrainSeed, numberSeed, true); GetAllEdges(); GetAllIntersections(); } public Board(int terrainSeed) : this() { InitTerrain(terrainSeed, 0, false); GetAllEdges(); GetAllIntersections(); } public Dictionary<int, int> GetLongestRoad() { // find longest road for each player // player, length var playersLongest = new Dictionary<int, int>(4); // floodfill from each road segment to see if it constitutes the longest road. var visited = new HashSet<Edge>(); foreach (var road in roads) { if (visited.Contains(road.Key)) continue; // already explored visited.Add(road.Key); // get ends var ends = this.GetAdjacentIntersections(road.Key); var tempVisited = new HashSet<Edge>(); tempVisited.Add(road.Key); int first = CountRoadLengthFromIntersection(road.Value, ends[0], tempVisited, visited); int second = CountRoadLengthFromIntersection(road.Value, ends[1], tempVisited, visited); int result = first + 1 + second; if (!playersLongest.ContainsKey(road.Value) || playersLongest[road.Value] < result) { playersLongest[road.Value] = result; } } return playersLongest; } public int GetPlayersLongestRoad(int playerID) { int highest = 0; // floodfill from each road segment to see if it constitutes the longest road. HashSet<Edge> visited = new HashSet<Edge>(); foreach (var road in roads.Where(r => GetRoad(r.Key) == playerID)) { if (visited.Contains(road.Key)) continue; // already explored visited.Add(road.Key); // get ends Intersection[] ends = this.GetAdjacentIntersections(road.Key); HashSet<Edge> tempVisited = new HashSet<Edge>(); tempVisited.Add(road.Key); int first = CountRoadLengthFromIntersection(road.Value, ends[0], tempVisited, visited); int second = CountRoadLengthFromIntersection(road.Value, ends[1], tempVisited, visited); int result = first + 1 + second; if (highest < result) { highest = result; } } return highest; } public Tile GetTile(int index) { Tuple<int, int> coords = GetTerrainCoords(index); return terrain[coords.Item1][coords.Item2]; } public Tile GetTile(int row, int column) { return terrain[row][column]; } public bool CanBuildPiece(Intersection intersection) { if (GetTile(intersection.FirstTile).Terrain == Terrain.Water && GetTile(intersection.SecondTile).Terrain == Terrain.Water && GetTile(intersection.ThirdTile).Terrain == Terrain.Water) return false; return !settlements.ContainsKey(intersection); } public int GetRoad(Edge edge) { return roads.ContainsKey(edge) ? roads[edge] : -1; } public Dictionary<Edge,int> GetAllRoads() { return new Dictionary<Edge, int>(roads); } public bool CanBuildRoad(Edge edge) { if (!IsLegalEdge(edge)) return false; return !roads.ContainsKey(edge); } public Piece GetPiece(Intersection intersection) { return settlements.ContainsKey(intersection) ? settlements[intersection] : null; } public Dictionary<Intersection,Piece> GetAllPieces() { return new Dictionary<Intersection, Piece>(settlements); } public Piece[] GetPieces(int index) { List<Piece> result = new List<Piece>(); AddPiece(result, new Intersection(index, index - 7, index - 1)); AddPiece(result, new Intersection(index, index - 7, index - 6)); AddPiece(result, new Intersection(index, index - 6, index + 1)); AddPiece(result, new Intersection(index, index + 1, index + 7)); AddPiece(result, new Intersection(index, index + 6, index + 7)); AddPiece(result, new Intersection(index, index + 6, index - 1)); return result.ToArray(); } public Intersection[] GetAllIntersections() { if(allIntersections == null){ List<Intersection> result = new List<Intersection>(22); for (int r = 0; r < 7; r++) { for (int c = 0; c < Board.GetRowLength(r); c++) { Intersection south = null; Intersection southeast = null; if (r % 2 == 0) { if(r + 1 < 7 && c + 1 < Board.GetRowLength(r + 1)) south = new Intersection(GetTerrainIndex(r, c), GetTerrainIndex(r + 1, c), GetTerrainIndex(r + 1, c + 1)); if (r + 1 < 7 && c + 1 < Board.GetRowLength(r)) southeast = new Intersection(GetTerrainIndex(r, c), GetTerrainIndex(r, c + 1), GetTerrainIndex(r + 1, c + 1)); } else { if (r + 1 < 7 && c - 1 >= 0 && c < 6) south = new Intersection(GetTerrainIndex(r, c), GetTerrainIndex(r + 1, c - 1), GetTerrainIndex(r + 1, c)); if (r + 1 < 7 && c < 6) southeast = new Intersection(GetTerrainIndex(r, c), GetTerrainIndex(r, c + 1), GetTerrainIndex(r + 1, c)); } if (south != null && (GetTile(south.FirstTile).Terrain != Terrain.Water || GetTile(south.SecondTile).Terrain != Terrain.Water)) result.Add(south); if (southeast != null && (GetTile(southeast.FirstTile).Terrain != Terrain.Water || GetTile(southeast.SecondTile).Terrain != Terrain.Water)) result.Add(southeast); } } allIntersections = result.ToArray(); } return allIntersections.ToArray(); } public Edge[] GetAllEdges() { if(allEdges == null){ HashSet<Edge> result = new HashSet<Edge>(); for (int i = 0; i < 45; i++) { this.GetAdjacentTiles(i).Where(j => this.IsLegalEdge(new Edge(i, j))).ForEach(j => result.Add(new Edge(i, j))); } allEdges = result.ToArray(); } return allEdges.ToArray(); } public int GetRobberLocation() { return robberLocation; } public IBoard MoveRobber(int index) { return new Board(terrain, new Dictionary<Edge, int>(roads), new Dictionary<Intersection, Piece>(settlements), index, harbors, allIntersections, allEdges); } public IBoard PlacePiece(Intersection intersection, Piece p) { var newSettlements = new Dictionary<Intersection, Piece>(settlements); newSettlements[intersection] = p; return new Board(terrain, new Dictionary<Edge, int>(roads), newSettlements, robberLocation, harbors, allIntersections, allEdges); } public IBoard PlaceRoad(Edge edge, int playerID) { var newRoads = new Dictionary<Edge, int>(roads); newRoads[edge] = playerID; return new Board(terrain, newRoads, new Dictionary<Intersection, Piece>(settlements), robberLocation, harbors, allIntersections, allEdges); } public Edge[] GetAdjacentEdges(Intersection intersection) { List<Edge> result = new List<Edge>(3); if (IsLegalEdge(new Edge(intersection.FirstTile, intersection.SecondTile))) result.Add(new Edge(intersection.FirstTile,intersection.SecondTile)); if (IsLegalEdge(new Edge(intersection.SecondTile, intersection.ThirdTile))) result.Add(new Edge(intersection.SecondTile, intersection.ThirdTile)); if (IsLegalEdge(new Edge(intersection.FirstTile, intersection.ThirdTile))) result.Add(new Edge(intersection.FirstTile, intersection.ThirdTile)); return result.ToArray(); } public Edge[] GetAdjacentEdges(int tileIndex) { return GetAllEdges().Where(e => e.FirstTile == tileIndex || e.SecondTile == tileIndex).ToArray(); } public Intersection[] GetAdjacentIntersections(Edge edge) { var n1 = GetAdjacentTiles(edge.FirstTile); return GetAdjacentTiles(edge.SecondTile) .Where(t => n1.Contains(t)) .Where(t => IsLegalEdge(edge) || GetTile(t).Terrain != Terrain.Water) .Select(t => new Intersection(edge.FirstTile, edge.SecondTile, t)) .ToArray(); } public Intersection[] GetAdjacentIntersections(int tileIndex) { return GetAllIntersections().Where(i => i.FirstTile == tileIndex || i.SecondTile == tileIndex || i.ThirdTile == tileIndex).ToArray(); } public List<int> GetAdjacentTiles(int index) { List<int> result = new List<int>(); if (index - 7 > 0) result.Add(index - 7); if (index - 6 > 0) result.Add(index - 6); if (index - 1 > 0) result.Add(index - 1); if (index + 1 < 45) result.Add(index + 1); if (index + 6 < 45) result.Add(index + 6); if (index + 7 < 45) result.Add(index + 7); return result; } public bool HasNoNeighbors(Intersection intersection) { return GetAdjacentEdges(intersection). SelectMany(edge => GetAdjacentIntersections(edge)). All(inter => inter.Equals(intersection) || GetPiece(inter) == null); } public Harbor[] GetHarbors() { return this.harbors.ToArray(); } public HarborType[] GetPlayersHarbors(int playerID) { HashSet<HarborType> result = new HashSet<HarborType>(); foreach (var h in harbors) { var corners = GetAdjacentIntersections(h.Position); foreach (Intersection pos in corners) { Piece curPiece = GetPiece(pos); if (curPiece != null && curPiece.Player == playerID) result.Add(h.Type); } } return result.ToArray(); } public Edge[] GetPossibleRoads(int playerID) { List<Edge> result = new List<Edge>(15); foreach(Edge edge in this.GetAllEdges()){ // must be empty if (roads.ContainsKey(edge)) continue; foreach (Intersection inter in this.GetAdjacentIntersections(edge)) { // must not be other players piece at intersection Piece atInter = this.GetPiece(inter); if (atInter != null && atInter.Player != playerID) continue; // must have one of the players roads connected to one of the end edges if(this.GetAdjacentEdges(inter).Any(e => this.GetRoad(e) == playerID)) { result.Add(edge); break; } } } return result.ToArray(); } public Intersection[] GetPossibleSettlements(int playerID) { return new HashSet<Intersection>(this.roads.Keys.Where(k => roads[k] == playerID) .SelectMany(e => this.GetAdjacentIntersections(e))) .Where(i => HasNoNeighbors(i) && !this.settlements.ContainsKey(i)).ToArray(); } public Intersection[] GetPossibleCities(int playerID) { return this.settlements.Keys.Where(i => settlements[i].Player == playerID && settlements[i].Token == Token.Settlement).ToArray(); } public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("Board Terrain:\n"); foreach (Tile[] row in terrain) { foreach (Tile tile in row) { builder.Append(tile.ToString() + ","); } builder.Append("\n"); } // cities this.settlements.Where(s => s.Value.Token.Equals(Token.City)) .OrderBy(s => s.Value.Player) .ForEach(c => builder.Append("City: p=" + c.Value.Player + " " + c.Key + "\n")); // settlements this.settlements.Where(s => s.Value.Token.Equals(Token.Settlement)) .OrderBy(s => s.Value.Player) .ForEach(s => builder.Append("Settlement: p=" + s.Value.Player + " " + s.Key + "\n")); // roads this.roads.OrderBy(r => r.Value).ForEach(r => builder.Append("Road: p=" + r.Value + " " + r.Key + "\n")); return builder.ToString(); } //------------Private Methods------------------------------// private void InitTerrain(int terrainSeed, int numberSeed, bool randomNumbers) { // generate random board // construct pool List<Terrain> terrainPool = new List<Terrain>(19); for (int i = 0; i < 4; i++) { if (i < 3) terrainPool.Add(Terrain.Hills); if (i < 3) terrainPool.Add(Terrain.Mountains); terrainPool.Add(Terrain.Pasture); terrainPool.Add(Terrain.Fields); terrainPool.Add(Terrain.Forest); } terrainPool.Add(Terrain.Desert); List<int> numberPool = new List<int>(valueOrder); List<HarborType> harborPool = new List<HarborType>(9); harborPool.Add(HarborType.Brick); harborPool.Add(HarborType.Grain); harborPool.Add(HarborType.Lumber); harborPool.Add(HarborType.Ore); harborPool.Add(HarborType.Wool); for(int i = 0; i < 4; i++) harborPool.Add(HarborType.ThreeForOne); // shuffles terrainPool.Shuffle(terrainSeed); harborPool.Shuffle(terrainSeed); if (randomNumbers) numberPool.Shuffle(numberSeed); // place randomized tiles bool desertFound = false; for (int i = 0; i < placementOrder.Length; i++) { Tuple<int, int> coords = GetTerrainCoords(placementOrder[i]); if (terrainPool[i] == Terrain.Desert) { terrain[coords.Item1][coords.Item2] = new Tile(terrainPool[i], 0); desertFound = true; robberLocation = placementOrder[i]; // place the robber } else { terrain[coords.Item1][coords.Item2] = new Tile(terrainPool[i], numberPool[i - (desertFound ? 1 : 0)]); } } // place harbors random at positions for (int i = 0; i < 9; i++) this.harbors[i] = new Harbor(harborPool[i], harborEdges[i]); } private Tuple<int, int> GetTerrainCoords(int index) { int row = 0; bool longrow = false; while (index >= (longrow ? 7 : 6)) { row++; index -= longrow ? 7 : 6; longrow = !longrow; } return new Tuple<int, int>(row, index); } private int GetTerrainIndex(int row, int col) { int index = 0; bool longrow = false; while (row > 0) { row--; index += longrow ? 7 : 6; longrow = !longrow; } return index + col; } private void AddPiece(List<Piece> list, Intersection intersection) { Piece hit = this.GetPiece(intersection); if(hit != null) list.Add(hit); } private int CountRoadLengthFromIntersection(int playerID, Intersection curInt, HashSet<Edge> visited, HashSet<Edge> globalVisited) { // check for break Piece curPiece = GetPiece(curInt); if(curPiece != null && curPiece.Player != playerID) return 0; // no more edges this direction // find connections var edgesOut = GetAdjacentEdges(curInt).Where(e => !visited.Contains(e) && GetRoad(e) == playerID).ToArray(); // temp array int highest = 0; foreach (var edge in edgesOut) { // add edges to visited visited.Add(edge); globalVisited.Add(edge); Intersection otherEnd = GetAdjacentIntersections(edge).First(i => !i.Equals(curInt)); int depthSearch = CountRoadLengthFromIntersection(playerID, otherEnd, visited, globalVisited); if (1 + depthSearch > highest) highest = 1 + depthSearch; visited.Remove(edge); } return highest; } private Boolean IsLegalEdge(Edge edge) { return GetTile(edge.FirstTile).Terrain != Terrain.Water || GetTile(edge.SecondTile).Terrain != Terrain.Water; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.Log; namespace AIsOfCatan { public class GameState : IGameState { private Player[] players; private int curPlayer; private List<LogEvent> log; public GameState(IBoard board, List<DevelopmentCard> deck, int[] resourceBank, Player[] players, int curPlayer, List<LogEvent> log, int longestRoad, int largestArmy) { Board = board; DevelopmentCards = deck == null ? 0 : deck.Count; ResourceBank = resourceBank == null ? null : resourceBank.ToArray(); this.players = players; this.curPlayer = curPlayer; this.log = log; if (players == null) players = new Player[0]; AllPlayerIds = players.Select(p => p.Id).ToArray(); LongestRoadId = longestRoad; LargestArmyId = largestArmy; } public IBoard Board { get; private set; } public int DevelopmentCards { get; private set; } public int[] ResourceBank { get; private set; } public int[] AllPlayerIds { get; private set; } public int LongestRoadId { get; private set; } public int LargestArmyId { get; private set; } public int GetPlayerScore(int playerId) { int result = 0; if (playerId == LargestArmyId) result += 2; if (playerId == LongestRoadId) result += 2; // add 2 for each city and 1 for each settlement Board.GetAllPieces().Where(p => p.Value.Player == playerId).ForEach(p => result += p.Value.Token == Token.City ? 2 : 1); return result; } public int GetRoundNumber() { return log.OfType<RollLogEvent>().Where(r => r.Player == 0).Count(); } public int GetResourceCount(int playerID) { return players[playerID].Resources.Count; } public int GetDevelopmentCardCount(int playerID) { return players[playerID].DevelopmentCards.Count; } public int GetKnightCount(int playerID) { return players[playerID].PlayedKnights; } public int GetSettlementsLeft(int playerID) { return players[playerID].SettlementsLeft; } public int GetCitiesLeft(int playerID) { return players[playerID].CitiesLeft; } public int GetRoadsLeft(int playerID) { return players[playerID].RoadsLeft; } public Resource[] GetOwnResources() { return players[curPlayer].Resources.ToArray(); } public DevelopmentCard[] GetOwnDevelopmentCards() { return players[curPlayer].DevelopmentCards.ToArray(); } public int GetResourceBank(Resource res) { return ResourceBank[(int)res]; } public List<LogEvent> GetLatestEvents(int amount) { return log.Skip(Math.Max(0, log.Count() - amount)).Take(amount).ToList(); } public List<LogEvent> GetEventsSince(DateTime time) { return log.Where(e => e.TimeStamp.CompareTo(time) > 0).ToList(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.API; namespace AIsOfCatan.Log { public class BuildRoadLogEvent : LogEvent { public int Player { get; private set; } public Edge Position { get; private set; } public BuildRoadLogEvent(int player, Edge position) { Player = player; this.Position = position; } public override string ToString() { return "Player " + Player + " build a Road at " + Position; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class AcceptTradeLogEvent : LogEvent { public int Player { get; private set; } public int OtherPlayer { get; private set; } private List<Resource> give; public List<Resource> Give { get { return give.ToList(); } } private List<Resource> take; public List<Resource> Take { get { return take.ToList(); } } public AcceptTradeLogEvent(int player, int otherplayer, List<Resource> give, List<Resource> take){ Player = player; OtherPlayer = otherplayer; this.give = give; this.take = take; } public override string ToString() { return "Player " + Player + " accepts to trade " + give.ToListString() + " for " + take.ToListString() + " with " + OtherPlayer; } } } <file_sep> using System.Collections.Generic; using AIsOfCatan.API; namespace AIsOfCatan { public class MainActions : IGameActions { private readonly Player player; private readonly GameController controller; private bool valid; private bool hasPlayedDevCard; private bool isAfterDieRoll; public MainActions(Player player, GameController controller) { this.player = player; this.controller = controller; valid = true; this.hasPlayedDevCard = false; this.isAfterDieRoll = false; } /// <summary> /// Allow the build actions to be called /// </summary> public void DieRoll() { isAfterDieRoll = true; } /// <summary> /// Invalidate this action object making all methods throw IllegalActionExceptions if called /// </summary> public void Invalidate() { valid = false; } public GameState TradeBank(Resource giving, Resource receiving) { if (!valid) throw new IllegalActionException("Tried to trade on an invalid GameAction"); if (!isAfterDieRoll) throw new IllegalActionException("Tried to trade before the die roll"); return controller.TradeBank(player, giving, receiving); } //Development cards public GameState DrawDevelopmentCard() { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (!isAfterDieRoll) throw new IllegalActionException("Tried to draw developmentcard before the die roll"); var result = controller.DrawDevelopmentCard(player); return result; } public GameState PlayKnight() { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (hasPlayedDevCard) throw new IllegalActionException("Max one development card can be played each turn"); hasPlayedDevCard = true; return controller.PlayKnight(player); } public GameState PlayRoadBuilding(Edge firstEdge, Edge secondEdge) { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (hasPlayedDevCard) throw new IllegalActionException("Max one development card can be played each turn"); hasPlayedDevCard = true; return controller.PlayRoadBuilding(player, firstEdge, secondEdge); } public GameState PlayYearOfPlenty(Resource resource1, Resource resource2) { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (hasPlayedDevCard) throw new IllegalActionException("Max one development card can be played each turn"); hasPlayedDevCard = true; return controller.PlayYearOfPlenty(player, resource1, resource2); } public GameState PlayMonopoly(Resource resource) { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (hasPlayedDevCard) throw new IllegalActionException("Max one development card can be played each turn"); hasPlayedDevCard = true; return controller.PlayMonopoly(player, resource); } //Trading public Dictionary<int, ITrade> ProposeTrade(List<List<Resource>> give, List<List<Resource>> take) { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (!isAfterDieRoll) throw new IllegalActionException("Tried to propose trade before the die roll"); return controller.ProposeTrade(player, give, take); } public GameState Trade(int otherPlayer) { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (!isAfterDieRoll) throw new IllegalActionException("Tried to trade before the die roll"); return controller.CompleteTrade(player, otherPlayer); } //Building public GameState BuildSettlement(Intersection intersection) { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (!isAfterDieRoll) throw new IllegalActionException("Tried to build before the die roll"); return controller.BuildSettlement(player, intersection); } public GameState BuildCity(Intersection intersection) { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (!isAfterDieRoll) throw new IllegalActionException("Tried to build before the die roll"); return controller.BuildCity(player, intersection); } public GameState BuildRoad(Edge edge) { if (!valid) throw new IllegalActionException("Tried to perform an action on an invalid GameAction"); if (!isAfterDieRoll) throw new IllegalActionException("Tried to build before the die roll"); return controller.BuildRoad(player, edge); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class TradeBankLogEvent : LogEvent { public int Player { get; private set; } public Resource Payment { get; private set; } public int Price { get; private set; } public Resource Purchase { get; private set; } public TradeBankLogEvent(int player, Resource payment, int price, Resource purchase) { Player = player; Payment = payment; Price = price; Purchase = purchase; } public override string ToString() { return "Player " + Player + " traded with the bank " + Price + " " + Payment + " for a " + Purchase; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.API { public class Piece { public Token Token { get; private set; } public int Player { get; private set; } public Piece(Token token, int player) { this.Token = token; this.Player = player; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan { public interface ITrade { /// <summary> /// The proposed list of resources that you should give in this trade /// The format is a list of lists of resources. This is to be interpreted /// as the opponent wanting you to give either all of Give[0] or all of Give[1] ... for what is in Take /// </summary> List<List<Resource>> Give { get; } /// <summary> /// The proposed list of resources that you should take in this trade /// The format is a list of lists of resources. This is to be interpreted /// as the opponent wanting you to take either all of Take[0] or all of Take[1] ... for what is in Give /// </summary> List<List<Resource>> Take { get; } /// <summary> /// Get the status of the trade /// </summary> TradeStatus Status { get; } /// <summary> /// To accept the offer, choose a sublist from Give and Take and put in this method /// To counter the offer, build new lists of resources (or expanding on the existing) and put in this method /// </summary> /// <param name="give">A list of resources you want to trade away</param> /// <param name="take">A list of resources you want to receive in the trade</param> /// <returns>The accepted/countered offer (should be the returned value of your implementation of the HandleTrade method)</returns> ITrade Respond(List<Resource> give, List<Resource> take); /// <summary> /// Decline the trade without making a counteroffer (the opponent might still initiate another trade proposal) /// </summary> /// <returns>The declined offer (should be the returned value of your implementation of the HandleTrade method)</returns> ITrade Decline(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class CounterTradeLogEvent : LogEvent { public int Player { get; private set; } private List<Resource> give; public List<Resource> Give { get { return give.ToList(); } } private List<Resource> take; public List<Resource> Take { get { return take.ToList(); } } public CounterTradeLogEvent(int player, List<Resource> give, List<Resource> take) { Player = player; this.give = give; this.take = take; } public override string ToString() { return "Player " + Player + " suggests the trade to be " + give.ToListString() + " for " + take.ToListString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using TroyXnaAPI; namespace AIsOfCatan { class GUILogList<T> : TXAListOverview<T> where T : TXADrawableComponent { private int Border { get; set; } private int Width { get; set; } private int Height { get; set; } public int Count { get { return fullList.Count; } } private readonly List<T> fullList = new List<T>(); private int numOfElements; public GUILogList(Vector2 position) : base(position) { Border = 2; Height = 500; Width = 300; //fullList = new List<T>(); } public GUILogList(Vector2 pos, int height, int width) : this(pos) { Height = height; Width = width; } protected override void Draw(SpriteBatch batch) { if (Visible) { Rectangle blackArea = new Rectangle(Area.X - Border, Area.Y - Border, Area.Width + 2 * Border, Area.Height + 2 * Border); batch.Draw(TXAGame.WHITE_BASE, blackArea, null, Color.Black); batch.Draw(TXAGame.WHITE_BASE, Area, null, Color.White); } base.Draw(batch); } public override void AddToList(T addItem) { fullList.Add(addItem); if (List.Count == 0) { numOfElements = (Height / fullList.First().Area.Height); } } protected override void UpdateRect() { Area = new Rectangle( (int)(Math.Round(Position.X)), (int)(Math.Round(Position.Y)), Width, Height); } protected override void DoUpdate(GameTime time) { base.DoUpdate(time); T last = fullList.LastOrDefault(); if (last != null && !last.Equals(List.FirstOrDefault())) { List<T> tempList = fullList.ToList(); tempList.Reverse(); if (tempList.Count <= numOfElements) { List = tempList.GetRange(0, tempList.Count); } else { List = tempList.GetRange(0, numOfElements); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using AIsOfCatan.API; namespace AIsOfCatan { public interface IStartActions { /// <summary> /// Build a settlement on the board /// If you try to build too close to another building a IllegalBuildPosition is thrown /// Must be called before BuildRoad, otherwise an IllegalActionException is thrown /// If you try to build more than one settlement an IllegalActionException is thrown /// </summary> /// <param name="intersection">The intersection to build at.</param> void BuildSettlement(Intersection intersection); /// <summary> /// Build a road on the board /// If you try to build at a position not connected to the newly placed settlement an IllegalBuildPositionException is thrown /// If you try to build more than one road an IllegalActionException is thrown /// </summary> /// <param name="edge">The edge the road will be along.</param> void BuildRoad(Edge edge); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AIsOfCatan.Log { class ProposeTradeLogEvent : LogEvent { public int Player { get; private set; } private List<List<Resource>> give; public List<List<Resource>> Give { get { return DeepClone(give); } } private List<List<Resource>> take; public List<List<Resource>> Take { get { return DeepClone(take); } } public ProposeTradeLogEvent(int player, List<List<Resource>> give, List<List<Resource>> take) { Player = player; this.give = give; this.take = take; } private static List<List<Resource>> DeepClone(List<List<Resource>> list) { var result = new List<List<Resource>>(list.Count); result.AddRange(list.Select(l => new List<Resource>(l))); return result; } public override string ToString() { return "Player " + Player + " proposes to trade " + give.ToDeepString() + " for " + take.ToDeepString(); } } }
6a88797058f9ad083ed54533f6d3403e9e9c50d1
[ "Markdown", "C#" ]
56
C#
mappy999/catan
3e3f207b406a0eae9c171ec328973aaac6e67776
d56a92ca8813375694d34c53680b80dc1c4c9580
refs/heads/master
<file_sep>package com.company; public class Main { public static void main(String[] args) { AppRunner gI = new AppRunner(); gI.getInitial(5); } }
b6c2fed5aad12027220e0d8065bb399f674152a4
[ "Java" ]
1
Java
sum414ever/hw7
bafc62c3c1ef12c5da44cda354905ab8bff5981c
9fb78d4b2e664bab7ba3e02159cbc3c7fd4032f1
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import * as data from './data.json'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent implements OnInit { // ******* Read json from json file ******* email_Content_json: any = (data as any).default; isDesc: Boolean = false; column: String = 'date'; direction: number; constructor() { } ngOnInit() { // ******* load email data on page load event which goes here ******* this.email_Content_json = data; } sort(property) { // ******* Loginc for sorting data goes here we can changes sorting order from here ******* this.isDesc = !this.isDesc; this.column = property; this.direction = this.isDesc ? 1 : -1; } } <file_sep>Efforts ============== Admission Challenge ----------------- 1. Analysis of business requirements. 2. Do paper work before actuall implementation of a work 3. Prepare plan sheet for work . 4. As per requirement I analyze whether we can go with a data table or simple bootstrap layouts. 5. Learn integration of date picker tools with Angular framework instead of code copy from sources. 6. As A Developer Unit testing of each input controls and oveall behaviour check. 7. Prepare UseCase After Unit Testing <file_sep>HENNGE ============== Admission Challenge ----------------- ### Welcome to the private repository of Umang naik front-end developer ### Suggested improvement Are : 1. We can Enhance UI Design by adding color text, shadows so it can be rich in look and filed 2. We should provide a free search for any text or content, unlike only date filter. 3. We can additionally provide Importance mail marking, Deletion mail Checkbox, spam mail marking etc. 4. we can add pagination, per page view facility so it can be more user friendly 5. We can add Sorting for each component unlike only for date. 6. We can add collapse functionality so a user can view mail primary content Thank you ....<file_sep>Front-End Mockup Design
b08d72dc1ca38a34ae5aaa8a531c448d624d58b8
[ "Markdown", "TypeScript" ]
4
TypeScript
umangnaik/Email-UI-Mockup-Angular-HTML-
59697810307de6f0071d1858204d20779465e0d7
53f9595800fe98eceea8cf20c0c3e27fb791e29c
refs/heads/main
<repo_name>AntonKuzmishyn/Lab_IStTP<file_sep>/Models/Teacher.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; #nullable disable namespace MyLabVar5 { public partial class Teacher { public Teacher() { Subjects = new HashSet<Subject>(); } public int Id { get; set; } [Required(ErrorMessage = "Поле не повинно бути порожнім!")] [Display(Name = "<NAME>")] public string Name { get; set; } public int FacultyId { get; set; } public int ChairId { get; set; } public int SubjectId { get; set; } [Required(ErrorMessage = "Поле не повинно бути порожнім!")] [Display(Name = "Кафедра")] public virtual Chair Chair { get; set; } [Required(ErrorMessage = "Поле не повинно бути порожнім!")] [Display(Name = "Факультет")] public virtual Faculty Faculty { get; set; } [Required(ErrorMessage = "Поле не повинно бути порожнім!")] [Display(Name = "Предмет")] public virtual Subject Subject { get; set; } public virtual ICollection<Subject> Subjects { get; set; } } }
72c307a2c3331ec22263072d3d4d2ce7d3b889ff
[ "C#" ]
1
C#
AntonKuzmishyn/Lab_IStTP
9cf1dfd964233e3b9d37f17ebc68b4744bc748d4
be71fae1e8232d008c4bff25c012a58aca8004f8
refs/heads/master
<file_sep>#!/bin/bash SCRIPTS_DIR="$(dirname "$0")/www/scripts/" CORDOVA_VERSION=`cat CORDOVA_VERSION` DEVICE_MODEL=$1 if [ -z "$DEVICE_MODEL" ]; then echo "ERROR: Missing device model. $0 iOS|android" exit 1; fi DESTINATION="cordova-current.js" FILENAME="cordova-$CORDOVA_VERSION-$DEVICE_MODEL.js" if [ ! -f "$SCRIPTS_DIR$FILENAME" ]; then echo "ERROR: Missing file $FILENAME." exit 2; fi `cp $SCRIPTS_DIR$FILENAME $SCRIPTS_DIR$DESTINATION` <file_sep>package org.apache.cordova; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; import org.apache.cordova.CordovaWebViewClient; import org.apache.cordova.DroidGap; import org.nuxeo.ecm.mobile.android.NuxeoWebApp; import android.graphics.Bitmap; import android.util.Log; import android.webkit.WebView; /** * Nuxeo WebViewClient implementation that handle a list of javascript files to * be injected each page loaded. The package is moved to org.apache.cordova to * access WebView control directly. * * @author arnaud */ public class NuxeoWebViewClient extends CordovaWebViewClient { private static final String TAG = "NuxeoWebViewClient"; protected Set<String> filesToBeInject = new HashSet<String>(); protected Map<String, String> filesContentCache = new HashMap<String, String>(); protected DroidGap ctx; public NuxeoWebViewClient(DroidGap ctx) { super(ctx); this.ctx = ctx; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); injectFiles(url); loadJavascript(String.format("var cordovaBase = '%s'", "file://" + NuxeoWebApp.BASE_PATH)); view.getSettings().setBuiltInZoomControls(url.contains("restAPI/preview")); } public void addFileToLoad(String file) { filesToBeInject.add(file); } protected void injectFiles(String url) { if (url.startsWith("javascript")) { Log.d(TAG, "Do not try to inject javascript inlined as file."); return; } Log.i(TAG, "Inject files for: " + url); for (String file : filesToBeInject) { loadFile(file); } } protected void loadFile(String uri) { try { Log.i(TAG, "Try to load file: " + uri); if (!filesContentCache.containsKey(uri)) { filesContentCache.put(uri, new Scanner( ctx.getAssets().open(uri)).useDelimiter("\\A").next()); } String fileContent = filesContentCache.get(uri); loadJavascript(fileContent); } catch (IOException e) { Log.e(TAG, "Unable to find file: " + e.getMessage()); } } public void loadJavascript(String js) { ctx.appView.loadUrl("javascript:" + js + ";"); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // Override Cordova default behavior, to not clear history. } } <file_sep>// Based on work from <NAME>, Nitobi under MIT License with their ChildBrowser plugins. (function() { var cordovaRef = window.PhoneGap || window.Cordova || window.cordova; // old to new fallbacks function NxFileBrowser() { // Does nothing } // Callback when the location of the page changes // called from native NxFileBrowser._onLocationChange = function(newLoc) { window.plugins.NxFileBrowser.onLocationChange(newLoc); }; // Callback when the user chooses the 'Done' button // called from native NxFileBrowser._onClose = function() { window.plugins.NxFileBrowser.onClose(); }; // Callback when the user chooses the 'open in Safari' button // called from native NxFileBrowser._onOpenExternal = function() { window.plugins.NxFileBrowser.onOpenExternal(); }; // Pages loaded into the NxFileBrowser can execute callback scripts, so be careful to // check location, and make sure it is a location you trust. // Warning ... don't exec arbitrary code, it's risky and could fuck up your app. // called from native NxFileBrowser._onJSCallback = function(js,loc) { // Not Implemented //window.plugins.NxFileBrowser.onJSCallback(js,loc); }; /* The interface that you will use to access functionality */ // Show a webpage, will result in a callback to onLocationChange NxFileBrowser.prototype.showWebPage = function(loc) { cordovaRef.exec("NxFileBrowserCommand.showWebPage", loc); }; // close the browser, will NOT result in close callback NxFileBrowser.prototype.close = function() { cordovaRef.exec("NxFileBrowserCommand.close"); }; // Not Implemented NxFileBrowser.prototype.jsExec = function(jsString) { // Not Implemented!! //PhoneGap.exec("NxFileBrowserCommand.jsExec",jsString); }; // Note: this plugin does NOT install itself, call this method some time after deviceready to install it // it will be returned, and also available globally from window.plugins.NxFileBrowser NxFileBrowser.install = function() { if(!window.plugins) { window.plugins = {}; } if ( ! window.plugins.nxFileBrowser ) { window.plugins.nxFileBrowser = new NxFileBrowser(); } }; if (cordovaRef && cordovaRef.addConstructor) { cordovaRef.addConstructor(NxFileBrowser.install); } else { console.log("NxFileBrowser Cordova Plugin could not be installed."); return null; } })();<file_sep>package org.nuxeo.ecm.mobile.android; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult.Status; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.hardware.Camera; import android.net.Uri; import android.util.Base64; import android.util.Log; public class OpenCommandPlugin extends CordovaPlugin { private static final String TAG = "OpenCommandPlugin"; protected enum Actions { openURL, openServer, presentingDocument, askUser } @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) { Status status = Status.NO_RESULT; Log.i(TAG, "Action called: " + action); try { if (Actions.openURL.toString().equals(action)) { String url = data.getString(0); status = openUrl(url); } else if (Actions.openServer.toString().equals(action)) { String url = data.getString(0); String username = data.getString(1); String password = data.getString(2); status = openServer(url, username, password); } else if (Actions.presentingDocument.toString().equals(action)) { String documentUrl = data.getString(0); String mimetype = data.getString(1); status = presentingDocument(documentUrl, mimetype); } else if (Actions.askUser.toString().equals(action)) { String documentUrl = null; if (data.length() > 0) { documentUrl = data.getString(0); } showUploadDialog(documentUrl); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); status = Status.JSON_EXCEPTION; } return status == Status.OK; } /** * @param filename * */ protected void showUploadDialog(String filename) { final List<String> sources = new ArrayList<String>(3); sources.add("from library"); if (hasCamera()) sources.add("from camera"); if (filename != null) { sources.add("from file " + filename); } if (hasFileBrowsing()) sources.add("from other application"); final CordovaPlugin plugin = this; Runnable runnable = new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder( webView.getContext()); builder.setTitle(R.string.upload_select_source); builder.setItems(sources.toArray(new String[] {}), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { String btnLabel = sources.get(item); if (btnLabel.equals("from library")) { openUrl("javascript:NXCordova.openLibrary();"); } else if (btnLabel.equals("from camera")) { openUrl("javascript:NXCordova.takePicture();"); } else if (btnLabel.equals("from other application")) { cordova.startActivityForResult(plugin, Intent.createChooser( buildAllFileIntent(), "Select an application"), 0); } else { openUrl("javascript:NXCordova.uploadFile();"); } } }); builder.create().show(); } }; cordova.getActivity().runOnUiThread(runnable); } protected Intent buildAllFileIntent() { Intent intent = new Intent(); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("*/*"); intent.setAction(Intent.ACTION_GET_CONTENT); return intent; } protected boolean hasFileBrowsing() { Intent intent = buildAllFileIntent(); PackageManager packageManager = cordova.getActivity().getApplicationContext().getPackageManager(); return packageManager.queryIntentActivities(intent, 0).size() > 0; } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (resultCode == Activity.RESULT_OK && intent.getDataString() != null) { openUrl(String.format("javascript:NXCordova.uploadFile('%s');", intent.getDataString())); } } /** * Method used to open any URL. Useful to request a local file (file://) * when the WenContext is browsing a http resource. * * @param url complete url with protocol. */ protected Status openUrl(String url) { return loadUrl(url, new HashMap<String, String>()); } /** * Method to handle basic authentification on a Nuxeo base URL * (http://localhost:8080/nuxeo for instance). * * @param url Nuxeo base server url. * @param username that will be passed as Basic Auth * @param password that will be passed as Basic Auth */ protected Status openServer(String url, String username, String password) { Map<String, String> extraHeaders = new HashMap<String, String>(); String credentials = username + ":" + password; String basicAuth = "basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT); extraHeaders.put("authorization", basicAuth); url += "/site/mobile"; return loadUrl(url, extraHeaders); } /** * Method to send document to another application, or save it somewhere with * Android. * * @param documentUrl of an existing document. * @param mimetype of the document */ protected Status presentingDocument(String documentUrl, String mimetype) { Log.i(TAG, "Try to presenting url: " + documentUrl + " with mimetype: " + mimetype); // Create a file object to ensure file is downloaded. File document = new File(documentUrl.substring(7, documentUrl.length())); if (!document.exists()) { Log.e(TAG, "File doesn't exist: " + documentUrl); return Status.MALFORMED_URL_EXCEPTION; } // Create an intent with mimetype Intent intent = new Intent(Intent.ACTION_VIEW); if (mimetype == null || "".equals(mimetype.trim())) { intent.setData(Uri.fromFile(document)); } else { intent.setDataAndType(Uri.fromFile(document), mimetype.trim()); } // Open Package Manager PackageManager packageManager = cordova.getActivity().getApplicationContext().getPackageManager(); List<ResolveInfo> activities = packageManager.queryIntentActivities( intent, 0); if (activities.size() > 0) { cordova.getActivity().startActivity(intent); return Status.OK; } else { Log.d(TAG, "No application associated with this intent."); webView.loadUrl("javascript:alert('No application associated with this kind of document.');"); return Status.NO_RESULT; } } private boolean hasCamera() { Camera cam = null; try { cam = Camera.open(); cam.release(); return true; } catch (Exception e) { return false; } } private Status loadUrl(String url, Map<String, String> extraHeaders) { webView.loadUrl(url, extraHeaders); return Status.OK; } } <file_sep>nuxeo-web-mobile-cordova ======================== Apache Cordova integration layer for embedding the mobile Nuxeo Web interface as a native app on Android and iOS<file_sep><?xml version="1.0"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.nuxeo.ecm.mobile</groupId> <artifactId>nuxeo-web-mobile-cordova-parent</artifactId> <version>5.7.2-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>nuxeo-mobile-application-android-parent</artifactId> <name>Nuxeo Web Mobile Application Android Parent</name> <packaging>pom</packaging> <modules> <module>nuxeo-web-mobile-android</module> <module>nuxeo-web-mobile-test</module> </modules> <properties> <android.sdk.version>10</android.sdk.version> <!-- Default signing values for development purpose only --> <keystore.path>../../nuxeo-dev.jks</keystore.path> <keystore.type>JKS</keystore.type> <keystore.alias>nuxeo-shell-dev</keystore.alias> <keystore.password><PASSWORD></keystore.password> </properties> <build> <pluginManagement> <plugins> <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <version>3.5.0</version> <inherited>true</inherited> <extensions>true</extensions> <configuration> <sdk> <platform>${android.sdk.version}</platform> </sdk> <deleteConflictingFiles>true</deleteConflictingFiles> <undeployBeforeDeploy>true</undeployBeforeDeploy> <!-- <attachSources>true</attachSources> --> <sign> <debug>false</debug> </sign> <zipalign> <verbose>true</verbose> <inputApk>${project.build.directory}/${project.artifactId}-${project.version}.apk</inputApk> <outputApk>${project.build.directory}/${project.artifactId}-signed.apk</outputApk> </zipalign> <extractDuplicates>true</extractDuplicates> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </pluginManagement> </build> </project> <file_sep>var NXCordova = function() { //if (!cordovaBase) { // alert('nuxeo-cordova-wrapper added without cordovaBase.'); //} var _ls = window.localStorage; var Constants = { fileStorageKey: 'nx_saved_file' } var Plugins = { //Constants openURL: { command: 'NxOpenCommand', method: 'openURL' }, openServer: { command: 'NxOpenCommand', method: 'openServer' }, uploadFile: { command: 'NxOpenCommand', method: 'askUser' }, presentingDocument: { command: 'NxOpenCommand', method: 'presentingDocument' } } function callCordova(command, param, onSuccessCall, onErrorCall) { //Helper method var cordovaRef = window.PhoneGap || window.Cordova || window.cordova; cordovaRef.exec(onSuccessCall || function() { console.log('success') }, onErrorCall || function() { console.log('error') }, command.command, command.method, param) } function addBaseURLIfNeeded(url) { url = encodeURI(url); if (url.match("^http:")) { return url; } var baseUrl = document.location.protocol + '//' + document.location.hostname; if (document.location.port) { baseUrl += ":" + document.location.port; } if (url.match("^/")) { return baseUrl + url; } else { return baseUrl + "/" + url; } } // Add a button to body element in case that the URL matches the specified (function(matchingUrls) { var found = false; for (var index in matchingUrls) { var pattern = matchingUrls[index]; if (document.URL.match(pattern)) { found = true; break; } } if (!found) return; // - Add a small back btn form preview screens var body = document.getElementsByTagName("body").item(0); var containerDiv = document.createElement('div'); containerDiv.style.position = 'fixed' containerDiv.style.zIndex = 1337 containerDiv.style.backgroundColor = 'rgba(0,0,0,0.7)'; containerDiv.style.border = '1px solid #111111' containerDiv.style.color = '#FFFFFF' containerDiv.style.fontWeight = 'bold' containerDiv.style.textShadow = '0 1px 1px #111111' containerDiv.style.borderRadius = '15px' containerDiv.style.boxShadow = '1px 1px 1px rgba(215,215,215,0.3)'; var backBtn = document.createElement('div'); backBtn.style.borderTop = '1px solid rgba(255, 255, 255, 0.3)' backBtn.style.padding = '3px 15px' backBtn.style.borderRadius = '15px' var backAnchor = document.createElement('a'); backAnchor.style.textDecoration = 'none' backAnchor.style.color = '#eee' backAnchor.style.fontWeight = 'bold' backAnchor.style.fontFamily = 'Helvetica, Arial, sans-serif' backAnchor.setAttribute('href', 'javascript:history.back();'); backAnchor.appendChild(document.createTextNode('Back')); backBtn.appendChild(backAnchor); containerDiv.appendChild(backBtn) if (body.firstChild) { body.insertBefore(containerDiv, body.firstChild) } else { body.appendChild(containerDiv); } })(['restAPI/preview']) // Module returned return { basePath: function() { return cordovaBase; }, openServer: function(url, username, password) { $.mobile.showPageLoadingMsg(); var params = [url, username, password]; callCordova(Plugins.openServer, params, function() { setTimeout(function() { $.mobile.hidePageLoadingMsg(); alert("Unable to connect on server") }, 5000) }); }, logout: function() { callCordova(Plugins.openURL, [cordovaBase + "index.html#page_servers_list"]); }, downloadFromURL: function(url) { console.log('Try to download: ' + url); function failFS() { alert('Unable to get the localfilesystem ...') } function downloadIntoFile(folder) { var urlLength = url.length; var baseUrl = url; if (url.lastIndexOf("?") > -1) { urlLength = url.lastIndexOf("?"); baseUrl = url.substring(0, urlLength); } var filename = baseUrl.substring(baseUrl.lastIndexOf('/') + 1, urlLength).replace(/\s+/g, '_'); folder.getFile(filename, { create: true, exclusive: false }, function(entry) { //alert('pdf created.') $.mobile.showPageLoadingMsg(); var ft = new FileTransfer(); var _url = addBaseURLIfNeeded(url); ft.download(_url, entry.fullPath, function(entry) { $.mobile.hidePageLoadingMsg(); console.log("download complete: " + entry.fullPath); // Read mimetype from parameter var mimetype = ""; var matches = _url.match(/mimetype=([a-z\./]+)/i); if (matches) { mimetype = matches[1]; console.log('Mimetype found: ' + mimetype); } //Presenting downloaded document callCordova(Plugins.presentingDocument, [encodeURI(entry.fullPath), mimetype]); }, function(error) { $.mobile.hidePageLoadingMsg(); alert('An error occured while trying to download file.') console.log("download error source " + error.source); console.log("download error target " + error.target); console.log("upload error code" + error.code); }); }, failFS); } // Get an arbitrary downloads folder to store dowloaded file temporaly window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function(fileSystem) { //alert('tmp created.') fileSystem.root.getDirectory("downloads", { create: true, exclusive: false }, downloadIntoFile, failFS); }, failFS); }, openUploadChooser: function(callback) { var file = _ls.getItem(Constants.fileStorageKey); var currentFile = file ? JSON.parse(file) : null; var args = []; if (currentFile) { args.push(currentFile.fileName) } callCordova(Plugins.uploadFile, args) }, takePicture: function(onSuccess, onFail) { var _onFail = onFail || function onFail(message) { alert('Failed because: ' + message); }; var _onSuccess = onSuccess || this.uploadFile; navigator.camera.getPicture(_onSuccess, _onFail, { quality: 65, allowEdit: true, destinationType: Camera.DestinationType.FILE_URI }); }, openLibrary: function(onSuccess, onFail) { var _onFail = onFail || function onFail(message) { alert('Failed because: ' + message); }; var _onSuccess = onSuccess || this.uploadFile navigator.camera.getPicture(_onSuccess, _onFail, { quality: 65, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }); }, uploadFile: function(filePath) { console.log("Asset: " + filePath); // Ensure to be in a Folderish path console.log('start uploading file') if (!document.URL.match("@folderish")) { alert('You must upload a file into a Folderish document. Operation aborded.') return; } // If no filePath, use the one in localStorage if (!filePath) { var currentFile = JSON.parse(_ls.getItem(Constants.fileStorageKey)); filePath = currentFile.filePath; } // Some upload metadata var options = new FileUploadOptions(); options.fileKey = "file:file"; options.fileName = decodeURIComponent(filePath.substr(filePath.lastIndexOf('/') + 1)); var params = new Object(); options.params = params; $.mobile.showPageLoadingMsg(); var ft = new FileTransfer(); ft.upload(filePath, document.URL, function(r) { if ("500" == r.responseCode) { alert('You are not allowed to create a new document in this Folderish.') } else { window.location.reload() } }, function(error) { $.mobile.hidePageLoadingMsg(); alert("An error has occurred: Code = " + error.code); console.log("upload error source " + error.source); console.log("upload error target " + error.target); }, options); }, handleOpenURL: function(filePath) { if (document.URL.match('^file:')) { alert('You should be connected to a server before trying to upload file.'); return; } // Timeout it to let the application loading. setTimeout(function() { var splits = filePath.split("/") var fileName = splits[splits.length - 1]; _ls.setItem(Constants.fileStorageKey, JSON.stringify({ 'filePath': filePath, 'fileName': fileName })); alert('Document ' + fileName + ' is ready to be uploaded.'); // XXX need to save it locally ?? }, 200); } }; }(); handleOpenURL = NXCordova.handleOpenURL; //Bind window.handleOpenURL to nxCordova wrapper <file_sep>#!/bin/bash BASE_URL=$1 if [ -z $BASE_URL ]; then echo "Missing url" echo "$0 base_url build_number" exit 1; fi BUILD_NUMBER=$2 if [ -z $BUILD_NUMBER ]; then echo "Missing build number" echo "$0 base_url build_number" exit 2; fi # http://qa.nuxeo.org/jenkins/job/addons_nuxeo-web-mobile-cordova-iOS-master/19/artifact/iOS/nuxeo-web-mobile-ios/build/nuxeo-web-mobile-Release-19.ipa echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"> <plist version=\"1.0\"> <dict> <key>items</key> <array> <dict> <key>assets</key> <array> <dict> <key>kind</key> <string>software-package</string> <key>url</key> <string>$BASE_URL/artifact/iOS/nuxeo-web-mobile-ios/build/nuxeo-web-mobile-Release-$BUILD_NUMBER.ipa</string> </dict> </array> <key>metadata</key> <dict> <key>bundle-identifier</key> <string>org.nuxeo.nuxeo.web.mobile</string> <key>kind</key> <string>software</string> <key>subtitle</key> <string>Nuxeo Web Mobile application</string> <key>title</key> <string>nuxeo-web-mobile</string> </dict> </dict> </array> </dict> </plist>" > nuxeo-web-mobile.plist <file_sep>var isPhoneGapReady = false; var db; String.prototype.trim = function() { return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }; String.prototype.trailingSlash = function() { return this.replace(/\/$/, ''); }; function init() { $.mobile.showPageLoadingMsg(); $('#server_profile_form').submit(function(evt) { evt.preventDefault(); return false; }) $("#create_server_profile").bind("click", function(event) { var formElementsArray = $('#server_profile_form').serializeArray(); var formElements = {} for (var index in formElementsArray) { var elt = formElementsArray[index]; formElements[elt.name] = elt.value; } var server = ServerUtils(formElements); server.store(function() { refreshServers() }); }); $('#btnEdit').click(function() { var that = $(this) $('#servers_list .btnDelete').fadeToggle(); }); (function() { // Use deviceReady Cordova event to init the app and fallback // in case that the event is never sent. console.log("Try to start Cordova.") var deviceIsReady = false; document.addEventListener("deviceready", function() { console.log("Start using Cordova.") deviceIsReady = true; setTimeout(function() { initAndGoToHome(); }, 1500); }, false); setTimeout(function() { if (!deviceIsReady) { $.mobile.hidePageLoadingMsg(); initAndGoToHome(); } }, 500) }()) } function initAndGoToHome() { /* window.clearInterval(intervalID); */ isPhoneGapReady = true; navigateToServerList(false); } function handleOpenURL(url) { console.log("Try to open file url: " + url); copyFileLocally(url, function() { NXCordova.openFileChooser(); }) } function copyFileLocally(url, callback) { // Try to resolve url parameters as a FS file window.resolveLocalFileSystemURI(url, function(fileEntry) { console.log("FileEntry gets: " + fileEntry.name); if (!fileEntry.isFile) { alert("Nuxeo mobile app do not allowed not regular file.") return; } // Try to request FS window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) { console.log("Filesystem opened") console.log(fileSystem.root) console.log("Check if file already exists") // Try to find if file already exists var destinationPath = "file://" + encodeURI(fileSystem.root.fullPath + "/" + fileEntry.name); window.resolveLocalFileSystemURI(destinationPath, function(oldFile) { console.log("File already exists: " + oldFile.name); oldFile.remove(function() { console.log("Oldfile removed.") copyFile(); }, handleFileError); }, function(evt) { // CopyFile only if it's file not found err if (evt.code == FileError.NOT_FOUND_ERR) { copyFile(); } else { handleFileError(evt); } }); function copyFile() { console.log("Try to copy file") fileEntry.copyTo(fileSystem.root, null, function(newEntry) { console.log("Copy successful: " + newEntry.fullPath); callback(); }, handleFileError); } }, handleFileError); }, handleFileError); } window.onload = init; //********************* DB MANAGEMENT ********************* // XXX Should be moved to localStorage ... function refreshServers(servers) { if (!servers) { ServerUtils().getAllServer(function(servers) { refreshServers(servers); }); return; } var len = servers.length; var html = ""; for (var i = 0; i < len; i++) { var server = ServerUtils(servers[i]); if ((!server.getURL()) || (!server.get('name'))) { alert('a not well formed server has been found'); } else { html += '<li>'; html += ' <a class="link" href="javascript:NXCordova.openServer(\'' + server.getURL() + '\', \'' + server.get('login') + '\',\'' + server.get('password') + '\')" data-icon="delete">' + server.get('name') + '</a>'; html += ' <span class="ui-icon ui-icon-arrow-r ui-icon-shadow">&nbsp;</span>'; //Hack to force arrow icon. html += ' <a class="btnDelete" style="display:none;" href="#" data-icon="delete">Delete</a>'; html += '</li>'; } } $('#servers_list').html(html); $('#servers_list .btnDelete').click(function() { var that = $(this); var serverName = that.parents('li').find('a.link').html(); ServerUtils({ name: serverName }).remove(function() { ServerUtils().getAllServer(function(servers) { refreshServers(servers); }); }); }) // Not sure about this timeout ... setTimeout(function() { $('#servers_list').listview('refresh') }, 50) } function navigateToServerList(isBackNavigation) { ServerUtils().getAllServer(function(servers) { refreshServers(servers); changePage('page_servers_list', isBackNavigation); if (servers.length == 0) { // If there is no servers added ... Go to the serverCreationPage changePage('page_server_creation'); } }); } function changePage(id, isBackNavigation) { var _isBackInNavigation = isBackNavigation || false; $.mobile.changePage('#' + id, { transition: "slide", reloadPage: false, reverse: _isBackInNavigation }); } var ServerUtils = function(server) { var _values = $.extend({}, server); var _ls = window.localStorage; //_ls.clear(); var Constant = { SERVERS_KEY: "nx_servers" } function setServers(servers) { _ls.setItem(Constant.SERVERS_KEY, JSON.stringify(servers)); } function getServers() { var servers = _ls.getItem(Constant.SERVERS_KEY); return servers ? JSON.parse(servers) : null; } function buildDefaultServerList() { return [{ name: "demo.nuxeo.com", servername: "http://demo.nuxeo.com", login: "Administrator", password: "<PASSWORD>", contextpath: "/nuxeo" }] } return { get: function(name) { var value = _values[name]; return (!value || !value.trim()) ? null : value; }, getAllServer: function(callback) { var servers = getServers() if (!servers) { servers = buildDefaultServerList(); setServers(servers) } if (callback) callback(servers) else return servers; }, getURL: function() { return this.get('servername') + this.get('contextpath'); }, store: function(callback) { var servers = this.getAllServer(); var newServer = { name: _values.name ? _values.name.trim() : null, servername: _values.servername ? _values.servername.trim() : null, login: _values.login ? _values.login.trim() : null, password: _values.password ? _values.password.trim() : null, contextpath: _values.contextpath ? _values.contextpath.trim().trailingSlash() : null }; // Check if already exists var replaceIndex = -1; $.each(servers, function(index, server) { if (server.name == newServer.name) { replaceIndex = index; return false; } }); if (replaceIndex >= 0) { servers[replaceIndex] = newServer; } else { servers.push(newServer); } setServers(servers) if (callback) callback(); }, remove: function(callback) { var servers = this.getAllServer(); var foundIndex = -1; $.each(servers, function(index, server) { if (server.name == _values.name) { foundIndex = index; return false; } }); if (foundIndex >= 0) { servers.splice(foundIndex, 1); setServers(servers) callback() } } } }; <file_sep>/* * (C) Copyright 2011 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Nuxeo - initial API and implementation */ package org.nuxeo.ecm.mobile.android; import junit.framework.Test; import junit.framework.TestSuite; import android.test.suitebuilder.TestSuiteBuilder; /** * A test suite running all tests under current package. * * To run all suites found in this apk: * adb shell am instrument -w \ * org.nuxeo.android.automationsample.test/android.test.InstrumentationTestRunner * * To run just this suite from the command line: * adb shell am instrument -w -e class org.nuxeo.android.automationsample.AllTests \ * org.nuxeo.android.automationsample.test/android.test.InstrumentationTestRunner * * To run an individual test case: * adb shell am instrument -w \ * -e class org.nuxeo.android.automationsample.test.BrowseTest \ * org.nuxeo.android.automationsample.test/android.test.InstrumentationTestRunner * * To run an individual test: * adb shell am instrument -w \ * -e class org.nuxeo.android.automationsample.test.StartActivityForResultTest#testAttachFile \ * org.nuxeo.android.automationsample.test/android.test.InstrumentationTestRunner */ public class AllTests extends TestSuite { public static Test suite() { return new TestSuiteBuilder(AllTests.class).includeAllPackagesUnderHere().build(); } } <file_sep><?xml version="1.0"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.nuxeo.ecm.mobile</groupId> <artifactId>nuxeo-mobile-application-android-parent</artifactId> <version>5.7.2-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>nuxeo-mobile-application-android-test</artifactId> <name>Nuxeo Web Mobile Application Android Test</name> <packaging>apk</packaging> <dependencies> <dependency> <groupId>org.nuxeo.ecm.mobile</groupId> <artifactId>nuxeo-mobile-application-android</artifactId> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>org.nuxeo.ecm.mobile</groupId> <artifactId>nuxeo-mobile-application-android</artifactId> <type>apk</type> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.android</groupId> <artifactId>android-test</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.jayway.android.robotium</groupId> <artifactId>robotium-solo</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies> <profiles> <profile> <id>manage-emulator</id> <!-- Won't stop an already existing emulator --> <activation> <file> <missing>${java.io.tmpdir}/maven-android-plugin-emulator.pid</missing> </file> </activation> <build> <plugins> <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <configuration> <emulator> <avd>virtual_2.2</avd> <options>-no-snapshot -wipe-data</options> <wait>240000</wait> </emulator> <emulatorWait>240000</emulatorWait> <device>emulator</device> </configuration> <executions> <execution> <id>startemulator</id> <phase>package</phase> <goals> <goal>emulator-start</goal> </goals> </execution> <execution> <id>alignApk</id> <phase>package</phase> <goals> <goal>zipalign</goal> </goals> </execution> <execution> <id>stopemulator</id> <phase>post-integration-test</phase> <goals> <goal>emulator-stop</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>manage-server</id> <!-- set manage.nuxeo.server=no to manage yourself the Nuxeo server --> <activation> <property> <name>manage.nuxeo.server</name> <value>!no</value> </property> </activation> <build> <plugins> <plugin> <groupId>org.nuxeo.build</groupId> <artifactId>nuxeo-distribution-tools</artifactId> <executions> <execution> <id>start-tomcat</id> <phase>pre-integration-test</phase> <goals> <goal>build</goal> </goals> <configuration> <buildFile>${basedir}/itests.xml</buildFile> <targets> <target>prepare-environment</target> <target>start</target> </targets> </configuration> </execution> <execution> <id>stop-tomcat</id> <phase>post-integration-test</phase> <goals> <goal>build</goal> </goals> <configuration> <buildFile>${basedir}/itests.xml</buildFile> <targets> <target>stop</target> <target>cleanup-environment</target> </targets> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jarsigner-plugin</artifactId> <executions> <execution> <id>signing</id> <goals> <goal>sign</goal> </goals> <phase>package</phase> <inherited>true</inherited> <configuration> <sdk> <platform>${android.sdk.version}</platform> </sdk> <deleteConflictingFiles>true</deleteConflictingFiles> <undeployBeforeDeploy>true</undeployBeforeDeploy> <manifest> <manifestVersionCodeUpdateFromVersion>true</manifestVersionCodeUpdateFromVersion> </manifest> <zipalign> <skip>false</skip> <outputApk>${project.build.directory}/${project.artifactId}-signed.apk</outputApk> </zipalign> <archive>${project.build.directory}/${project.artifactId}-${project.version}.apk</archive> <storetype>${keystore.type}</storetype> <keystore>${keystore.path}</keystore> <alias>${keystore.alias}</alias> <storepass>${keystore.password}</storepass> <!-- For compliance with JDK7 --> <arguments> <argument>-digestalg</argument> <argument>SHA1</argument> <argument>-sigalg</argument> <argument>MD5withRSA</argument> </arguments> </configuration> </execution> </executions> </plugin> <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <configuration> <test> <skip>auto</skip> <debug>false</debug> <coverage>true</coverage> <!--<logonly>false</logonly> --> <!-- <testsize>small|medium|large</testsize> --> <!--<createreport>true</createreport> --> <!-- <classes> --> <!-- <class>org.nuxeo.android.automationsample.AllTests</class> --> <!-- </classes> --> <!-- <packages> --> <!-- <package>your.package.name</package> --> <!-- </packages> --> </test> <dex> <coreLibrary>true</coreLibrary> </dex> </configuration> <executions> <execution> <id>alignApk</id> <phase>package</phase> <goals> <goal>zipalign</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.nuxeo</groupId> <artifactId>nuxeo-addons-parent</artifactId> <version>5.7.2-SNAPSHOT</version> </parent> <groupId>org.nuxeo.ecm.mobile</groupId> <artifactId>nuxeo-web-mobile-cordova-parent</artifactId> <name>Nuxeo Web Mobile Cordova Parent</name> <packaging>pom</packaging> <description>Device specific application for nuxeo-web-mobile using Cordova</description> <properties> <nuxeo.version>5.7.2-SNAPSHOT</nuxeo.version> <nuxeo.distribution.tools.version>1.11.5</nuxeo.distribution.tools.version> <android.version>2.3.3</android.version> <cordova.version>2.2.0</cordova.version> <robotium.version>2.5</robotium.version> </properties> <profiles> <profile> <id>packaging-android</id> <modules> <module>Android</module> </modules> </profile> </profiles> <dependencyManagement> <dependencies> <!-- Android dependencies --> <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <version>${android.version}</version> </dependency> <dependency> <groupId>com.google.android</groupId> <artifactId>android-test</artifactId> <version>${android.version}</version> </dependency> <dependency> <groupId>com.jayway.android.robotium</groupId> <artifactId>robotium-solo</artifactId> <version>${robotium.version}</version> </dependency> <!-- Nuxeo Web App - Cordova dependencies --> <dependency> <groupId>org.apache.cordova</groupId> <artifactId>cordova</artifactId> <version>${cordova.version}</version> </dependency> <dependency> <groupId>org.nuxeo.ecm.mobile</groupId> <artifactId>nuxeo-web-mobile-cordova-parent</artifactId> <version>${nuxeo.version}</version> </dependency> <dependency> <groupId>org.nuxeo.ecm.mobile</groupId> <artifactId>nuxeo-web-mobile-android</artifactId> <version>${nuxeo.version}</version> </dependency> <dependency> <groupId>org.nuxeo.ecm.mobile</groupId> <artifactId>nuxeo-mobile-application-android</artifactId> <version>${nuxeo.version}</version> <type>jar</type> </dependency> <dependency> <groupId>org.nuxeo.ecm.mobile</groupId> <artifactId>nuxeo-mobile-application-android</artifactId> <version>${nuxeo.version}</version> <type>apk</type> </dependency> <!-- Nuxeo dependencies --> <dependency> <groupId>org.nuxeo.ecm.distribution</groupId> <artifactId>nuxeo-distribution</artifactId> <version>${nuxeo.version}</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement> <build> <pluginManagement> <plugins> <plugin> <!-- Force version to 1.11.5 while it is not running on maven3 --> <groupId>org.nuxeo.build</groupId> <artifactId>nuxeo-distribution-tools</artifactId> <version>${nuxeo.distribution.tools.version}</version> <extensions>true</extensions> </plugin> </plugins> </pluginManagement> </build> <repositories> <repository> <id>public</id> <url>http://maven.nuxeo.org/nexus/content/groups/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>public-snapshot</id> <url>http://maven.nuxeo.org/nexus/content/groups/public-snapshot</url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>public</id> <url>http://maven.nuxeo.org/nexus/content/groups/public</url> <name>Nuxeo virtual release repository</name> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> <pluginRepository> <id>public-snapshot</id> <url>http://maven.nuxeo.org/nexus/content/groups/public-snapshot</url> <name>Nuxeo virtual snapshot repository</name> <releases> <enabled>false</enabled> </releases> <snapshots> <updatePolicy>always</updatePolicy> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <scm> <connection>scm:git:git://github.com/nuxeo/nuxeo-web-mobile.git</connection> <developerConnection>scm:git:ssh://[email protected]:nuxeo/nuxeo-web-mobile.git</developerConnection> <url>https://github.com/nuxeo/nuxeo-web-mobile</url> </scm> </project> <file_sep>(function() { alert("loading ..."); document.addEventListener("deviceready", function() { alert("file-deviceready"); refreshFiles(); }); function refreshFiles() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) { var dropbox = $("#dropbox_files"); dropbox.empty(); console.log("Start refreshing files"); fileSystem.root.createReader().readEntries(function(entries) { var html = "" for (var i = 0; i < entries.length; i++) { var entry = entries[i]; if (!entry.isFile) { continue; } // class="ui-btn ui-btn-icon-right ui-li-has-arrow ui-li ui-li-has-count ui-li-has-icon ui-btn-up-c" html += '<li data-url="' + encodeURI(entry.fullPath) + '">'; html += entry.name; html += '<a href="#" class="delete">delete</a>' html += '</li>'; } dropbox.append(html).find(".delete").click(function() { var li = $(this).parents('li'); console.log(dropbox.html()); if (!li) { console.error("Unable to find LI parent"); return; } window.resolveLocalFileSystemURI("file://" + li.data('url'), function(fileEntry) { fileEntry.remove(function() { refreshFiles(); }, function(evt) { alert("Unable to remove this file.") handleFileError(evt); }); }, handleFileError); console.log("data-url: " + li.data('url')); }); dropbox.listview('refresh'); }, handleFileError); }, handleFileError); }; }())
971d7e7134e169de1f50b4dd9fcd39561f808925
[ "JavaScript", "Markdown", "Maven POM", "Java", "Shell" ]
13
Shell
nuxeo/nuxeo-web-mobile-cordova
5fb0318fe6b076477134e36811fb86ee432a135b
b6db5cfd692838946addb7eab92136cbd7d36996
refs/heads/master
<file_sep>class Admin::BucketController < Admin::ResourceController end <file_sep>This is [episode 16][rce] of Radiantcasts. You'll see some tips and tricks on how to make the best use of Radiant Layouts and the [Radiant Nested Layouts Extension][rnle] - an extension that helps keeping your layouts organized and DRY. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/06/08/radiantcasts-episode-16-radiant-layouts [rnle]:http://github.com/moklett/radiant-nested-layouts-extension<file_sep>This is the source code repository for the [Radiantcasts][rc] episodes. For each Radiant CMS application the user is `admin` with the password `<PASSWORD>` [rc]:http://blog.aissac.ro/category/radiantcasts/<file_sep>Database Mailer === About --- A [Radiant][rd] Extension by [Aissac][ai] that adds database persistence to emailed forms. It works on top of the Radiant [Mailer Extension][rme] and the fields recorded to the database are user defined. The extension adds a tab to the Radiant admin interface allowing you to browse saved records. Tested on Radiant 0.7.1, 0.8 and 0.9 RC1. Features --- * Save posted form fields and entire mail message to the database * Save e-mail attachments using paperclip * Configurable save-to-database for mailer forms * Add fields to be saved without loosing data * Admin interface to browse saved records * Export data to CSV and XLS Important Notice! --- The git branches on this repository hold stable versions of the extension for older versions of Radiant CMS. For example the _0.8_ branch is compatible with Radiant 0.8. To checkout one of these branches: git clone git://github.com/Aissac/radiant-database-mailer-extension.git vendor/extensions/database_mailer cd vendor/extensions/database_mailer git checkout -b <branch-name> origin/<remote-branch-name> As an example if you're working on Radiant 0.8 you will need to checkout the 0.8 branch: cd vendor/extensions/database_mailer git checkout -b my_branch origin/0.8 Installation --- Radiant Database Mailer Extension has three dependecies, the Radiant Mailer Extension, the `will_paginate` gem/plugin and the `paperclip` gem/plugin Install the `mailer` extension: git clone git://github.com/radiant/radiant-mailer-extension.git vendor/extensions/mailer ###Note At the time being you will need Aissac's version of the [Radiant Mailer Extension][arme], as it incorporates sending e-mails with attachments. the `will_paginate` gem/plugin: git clone git://github.com/mislav/will_paginate.git vendor/plugins/will_paginate or sudo gem install mislav-will_paginate --source http://gems.github.com and the `paperclip` gem/plugin git clone git://github.com/thoughtbot/paperclip.git vendor/plugins/paperclip or sudo gem install thoughtbot-paperclip --source http://gems.github.com Next edit `config/environment.rb` and add desired fields to be recorded: DATABASE_MAILER_COLUMNS = { :name => :string, :message => :text, :email => :string } And finally add the [Database Mailer Extension][rdme]: git clone git://github.com/Aissac/radiant-database-mailer-extension.git vendor/extensions/database_mailer Migrate and update the extension: rake radiant:extensions:database_mailer:migrate rake radiant:extensions:database_mailer:update Configuration --- Adding fields to the `DATABASE_MAILER_COLUMNS` hash and re-running `rake radiant:extensions:database_mailer:migrate` nondestructively adds fields to be saved. Fields removed from the hash are not deleted. Look at the Mailer Extension README for information on how to configure mail delivery. If you set `save_to_database` to false in the Mailer config, saving to the database is skipped and just mail delivery takes place. Example (in the `mailer` page part): subject: From the website of Whatever from: <EMAIL> redirect_to: /contact/thank-you save_to_database: false recipients: - <EMAIL> - <EMAIL> Any attachments that the e-mail might have will be saved on the file system. They can be downloaded from the details page of every record. If you want to take advantage of the blob field you need to create a `email` page part. The blob field keeps the sent version of the email. Fields that are not specified by `DATABASE_MAILER_COLUMNS` are silently ignored. Usage --- Create your Mailer pages and make sure to use the same field names: <r:mailer:form> <label for="name">Name:</label><br/> <r:mailer:text name="name" /><br/> <label for="email">Email:</label><br/> <r:mailer:text name="email" /><br/> <label for="message">Message:</label><br/> <r:mailer:textarea name="message" /> <br/> <label for="attachment">Image:</label><br/> <r:mailer:file name="attachment" /><br/> <input type="submit" value="Send" /> </r:mailer:form> Create the `mailer` page part: subject: From the website of Whatever from: <EMAIL> redirect_to: /contact/thank-you recipients: - <EMAIL> - <EMAIL> Create an `email` page part (to take advantage of the blob field): <r:mailer> Name: <r:get name="name" /> Email: <r:get name="email" /> Message: <r:get name="message" /> </r:mailer> Contributors --- * <NAME> ([@cristi_duma][cd]) * <NAME> ([@ihoka][ih]) [rd]: http://radiantcms.org/ [ai]: http://www.aissac.ro/ [rme]: http://github.com/radiant/radiant-mailer-extension [arme]: http://github.com/Aissac/radiant-mailer-extension [rdme]: http://blog.aissac.ro/radiant/database-mailer-extension/ [cd]: http://twitter.com/cristi_duma [ih]: http://twitter.com/ihoka<file_sep>Given /^I am logged in as admin$/ do Given "I go to to \"the welcome page\"" When "I fill in \"Username\" with \"admin\"" When "I fill in \"Password\" with \"<PASSWORD>\"" When "I press \"Login\"" end When /^I set the stereotype to "([^\"]*)" on the "([^\"]*)" page$/ do |stereotype, page| When "I follow \"#{page}\"" When "I select \"#{stereotype}\" from \"page_stereotype\"" When "I press \"Save Changes\"" end When /^I fill in all needed information in the new page$/ do When "I fill in \"Page Title\" with \"First Stereotype Child\"" When "I fill in \"Slug\" with \"first-stereotype-child\"" When "I fill in \"Breadcrumb\" with \"First Stereotype Child\"" end When /^I create a new child for the "([^\"]*)" page$/ do |page| visit new_admin_page_child_path(pages(:with_stereotype).id) end Then /^the new page should have the body page part with Markdown filter$/ do @page = pages(:with_stereotype).children.first @page.parts[0].name.should == "body" @page.parts[0].filter_id.should == "Markdown" end Then /^the new page should have the sidebar page part with Textile filter$/ do @page = pages(:with_stereotype).children.first @page.parts[1].name.should == "sidebar" @page.parts[1].filter_id.should == "Textile" end Then /^the new page should have the "([^\"]*)" layout$/ do |layout| pages(:with_stereotype).children.first.layout.name.should == layout end Then /^the new page should have status "([^\"]*)"$/ do |arg1| pages(:with_stereotype).children.first.status.should == Status["published"] end Then /^the new page should have "([^\"]*)" page type$/ do |arg1| pages(:with_stereotype).children.first.class_name.should == "ArchivePage" end<file_sep>module Globalize2 module GlobalizeTags include Radiant::Taggable class TagError < StandardError; end tag 'link_with_globalize' do |tag| locale = tag.attr.delete("locale") if locale switch_locale(locale) do send('tag:link_without_globalize', tag) end else send('tag:link_without_globalize', tag) end end tag 'children:each_with_globalize' do |tag| with_translated_locales = tag.attr['locale'] == 'false' ? false : true if with_translated_locales result = Page.scope_locale(I18n.locale) do send('tag:children:each_without_globalize', tag) end else result = send('tag:children:each_without_globalize', tag) end result end desc %{ Renders the current locale. *Usage:* <pre><code><r:locale /></code></pre> } tag 'locale' do |tag| I18n.locale.to_s end desc %{ Renders the locales passed in @codes@ attribute. Use the @between@ attribute to specify something between the rendered locale codes. *Example* <pre><code> <ul> <r:locales codes='en|ro'> <r:normal> <li><r:link id='<r:locale />'><r:locale /></r:link></li> </r:normal> <r:active> <li><r:link id='<r:locale />'><r:locale /></r:link></li> </r:active> </r:locales> </ul> </code></pre> } tag 'locales' do |tag| hash = tag.locals.locale = {} tag.expand raise TagError.new("'locales' tag must include a 'normal' tag") unless hash.has_key? :normal raise TagError.new("'codes' attribute must be set") if tag.attr['codes'].blank? result = [] codes = tag.attr["codes"].split("|").each do |code| hash[:code] = code if I18n.locale == code result << (hash[:active] || hash[:normal]).call else switch_locale(code) do result << hash[:normal].call end end end between = tag.attr["between"] || " " result.reject { |i| i.blank? }.join(between) end [:normal, :active].each do |symbol| tag "locales:#{symbol}" do |tag| hash = tag.locals.locale hash[symbol] = tag.block end end tag 'locales:code' do |tag| hash = tag.locals.locale hash[:code] end desc %{ Temporarily switch the locale within the block. Use the @code@ attribute so specify the locale you want to switch to. *Usage:* <pre><code><r:with_locale code='en'>...</r:with_locale></code></pre> } tag 'with_locale' do |tag| code = tag.attr['code'] raise TagError.new("'code' must be set") if code.blank? result = '' switch_locale(code) do result << tag.expand end result end desc %{ Renders the containing elements if the page's title is translated. This doesn't necessarily mean the content (page parts) are translated. *Usage:* <pre><code><r:if_translation_title>...</r:if_translation_title></code></pre> } tag 'if_translation_title' do |tag| page = tag.locals.page tag.expand if page.translated_locales.include?(I18n.locale.to_sym) end desc %{ The opposite of the @if_translation_title@ tag. Renders the containing elements if the page's title is not translated. *Usage:* <pre><code><r:unless_translation_title>...</r:unless_translation_title></code></pre> } tag 'unless_translation_title' do |tag| page = tag.locals.page tag.expand unless page.translated_locales.include?(I18n.locale.to_sym) end desc %{ Renders the containing elements if the page's part is translated. By default the @part@ attribute is set to @body@ *Usage:* <pre><code><r:if_translation_content [part='part_name']>...</r:if_translation_content></code></pre> } tag 'if_translation_content' do |tag| name = tag.attr['part'] || 'body' part = tag.locals.page.part(name) tag.expand if part && part.translated_locales.include?(I18n.locale.to_sym) end desc %{ The opposite of the @if_translation_content@ tag. Renders the containing elements if the page's part is not translated. By default, the @part@ attribute is set to @body@ *Usage:* <pre><code><r:unless_translation_content [part='part_name']>...</r:unless_translation_content></code></pre> } tag 'unless_translation_content' do |tag| name = tag.attr['part'] || 'body' part = tag.locals.page.part(name) tag.expand if part.nil? || !part.translated_locales.include?(I18n.locale.to_sym) end private # Allows you to switch the current locale while within the block. # The previously current locale is reset after the block is finished. def switch_locale(locale) current_locale = I18n.locale I18n.locale = locale result = yield I18n.locale = current_locale result end end end<file_sep># Uncomment this if you reference any of your controllers in activate require_dependency 'application_controller' class CustomFieldsExtension < Radiant::Extension version "0.1" description "An extension that lets you add custom fields to a Radiant page." url "http://blog.aissac.ro/radiant/custom-fields-extension/" define_routes do |map| map.resources :custom_fields, :path_prefix => '/admin/pages/:page_id', :controller => 'admin/custom_fields' end def activate Page.send(:include, CustomFields::PageExtensions) Page.send(:include, CustomFields::CustomFieldsTags) admin.page.edit.add :main, "admin/custom_fields/show_custom_fields", :before => "edit_header" admin.page.edit.add :popups, "admin/custom_fields/custom_fields_popup" end def deactivate end end<file_sep>module LazySnippetTags include Radiant::Taggable include ActionView::Helpers::TagHelper include ActionView::Helpers::JavaScriptHelper tag "lazy_snippet" do |tag| raise TagError.new("`lazy_snippet' tag must contain `name' attribute") unless name = tag.attr['name'] javascript_tag <<-JS LazySnippet.Registry.add('#{name.strip}', '#{tag.globals.page.url}'); JS end end<file_sep>This is [episode 17][rce] of Radiantcasts. You'll see how to install and use [Copy Move][cpe], [Reorder][re] and [Drag Order][doe] Radiant Extensions, three extensions that help manage the site structure Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/06/24/radiantcasts-episode-17-managing-site-structure [cpe]:http://github.com/pilu/radiant-copy-move [re]:http://github.com/radiant/radiant-reorder-extension [doe]:http://github.com/bright4/radiant-drag-order<file_sep>This is [episode 25][rce] of Radiantcasts. Part three of Radiant As A Blog, where you'll see how to use and configure the [Tags Extension][te] Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/11/18/radiantcasts-episode-25-radiant-as-a-blog-part-3-adding-tags/ [te]:https://github.com/jomz/radiant-tags-extension<file_sep>module Globalize2Paperclipped module PageExtensions def self.included(base) base.class_eval do alias_method_chain 'tag:if_assets', :globalize alias_method_chain 'tag:unless_assets', :globalize alias_method_chain 'tag:assets:each', :globalize end end end end<file_sep>module Admin::BucketHelper end <file_sep>require File.dirname(__FILE__) + '/../spec_helper' describe "Globalize2Paperclipped tags" do before(:each) do I18n.locale = "en" @page = Factory.create(:page) @asset = Factory.create(:asset) Factory.create(:page_attachment, :page_id => @page.id, :asset_id => @asset.id) end describe "<r:if_assets_with_globalize />" do it "expands if the page has translated assets" do @page. should render("<r:if_assets>test</r:if_assets>"). as("test") end it "does not expand if the page does not have translated assets" do switch_locale("ro") do @page. should render("<r:if_assets>test</r:if_assets>"). as("") end end end describe "<r:unless_assets_with_globalize />" do it "expands if the page does not have translated assets" do switch_locale("ro") do @page. should render("<r:unless_assets>test</r:unless_assets>"). as("test") end end it "does not expand if the page has translated assets" do @page. should render("<r:unless_assets>test</r:unless_assets>"). as("") end end describe "<r:assets:if_translation_asset />" do it "expands if the asset is translated" do @page. should render("<r:assets:each locale='false'><r:if_translation_asset><r:title /></r:if_translation_asset></r:assets:each>"). as(/Picture \d/) end it "does not expand if the asset is not translated" do switch_locale("ro") do @page. should render("<r:assets:each locale='false'><r:if_translation_asset><r:title /></r:if_translation_asset></r:assets:each>"). as("") end end end describe "<r:assets:unless_translation_asset" do it "expands if the asset is no translated" do switch_locale("ro") do @page. should render("<r:assets:each locale='false'><r:unless_translation_asset>test</r:unless_translation_asset></r:assets:each>"). as("test") end end it "does not expand if the asset is translated" do @page. should render("<r:assets:each locale='false'><r:unless_translation_asset>test</r:unless_translation_asset></r:assets:each>"). as("") end end describe "<r:assets:each_with_globalize />" do it "renders only the assets translated for the current locale if 'locale' attribute is not set to 'false'" do @page. should render("<r:assets:each><r:title /></r:assets:each>"). as(/Picture\d/) end it "renders all the attached assets if 'locale' attribute is set to 'false'" do @page. should render("<r:assets:each locale='false'><r:title /></r:assets:each>"). as(/Picture \d/) end end end<file_sep>require File.dirname(__FILE__) + '/../spec_helper' describe CustomField do dataset :pages, :custom_fields describe "validations" do it "should be valid" do create_custom_field @custom_field.should be_valid end [:name, :value, :page_id].each do |att| it "requires #{att} attribute" do lambda do create_custom_field(att => nil) @custom_field.errors.on(att).should_not be_nil end.should_not change(CustomField, :count) end end it "requires 'name' attribute to be unique within 'page_id' scope" do lambda do create_custom_field(:name => 'a_cf_on_first_page', :page_id => pages(:first).id) @custom_field.errors.on(:name).should_not be_nil end.should_not change(CustomField, :count) end end describe "methods" do it "find the assignable custom fields" do CustomField.find_assignable_custom_fields(pages(:first).id).should == ["a_cf_on_another_page"] end end private def create_custom_field(options = {}) @custom_field = CustomField.new({:name => "test_name", :value => "test_value", :page_id => '1'}.merge(options)) @custom_field.save @custom_field end end <file_sep>This is [episode 21][rce] of Radiantcasts. You'll see some of the best features Radiant 0.9 Refraction Release brings. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/07/29/radiantcasts-episode-21-radiant-0-9-refraction-release<file_sep>This is [episode 13][rce] of Radiantcasts. You'll see [Radiant Tiny Paper Extension][rtpe], an extension by [Aissac][a] that adds [Paperclipped][rpe] based [Tiny MCE][tmce] support to Radiant CMS. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/05/18/radiantcasts-episode-13-radiant-tiny-paper-extension [rtpe]:http://github.com/Aissac/radiant-tiny-paper-extension [rpe]:http://github.com/kbingman/paperclipped [a]:http://aissac.ro/en [tmce]:http://tinymce.moxiecode.com/<file_sep>Given /^I am logged in as admin$/ do Given "I navigate to \"the welcome page\"" And "I enter in \"user_login\" field \"admin\"" And "I enter in \"user_password\" field \"<PASSWORD>\"" And "I click the \"Login\" button" end<file_sep>Radiant Super Export Extension === About --- An extension by [Aissac][ai] that provides portability to your [Radiant CMS][rd] project by allowing you to export and import the records in the database and making it easy to manage them with a source control tool like Git or Subversion. Tested on Radiant 0.7.1, 0.8 and 0.9 RC1. Features --- * All records are exported to individual YAML files; * A directory is created for each model in the default import/export path which is db/export; * The individual YAML files are saved with the record ID as their filename. Installation --- The [Super Export Extension][rse] has no dependencies, so all you have to do is install it: git clone git://github.com/Aissac/radiant-super-export-extension.git vendor/extensions/super_export Usage --- To export, use: rake db:super_export To import, use: rake db:super_import ### Working example Exporting the Page model looks like this: db/ export/ pages/ 1.yml 2.yml 3.yml ... Contributors --- * <NAME> ([@ihoka][ih]) * <NAME> ([@cristi_duma][cd]) [ai]: http://www.aissac.ro/ [rd]: http://radiantcms.org/ [rse]: http://blog.aissac.ro/radiant/super-export-extension/ [cd]: http://twitter.com/cristi_duma [ih]: http://twitter.com/ihoka<file_sep>This is the [sixth episode][rce] of Radiantcasts. You'll see how to use [Radiant Custom Fields Extension][rcf] and [Radiant Stereotype Extension][rst]. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/03/23/radiantcasts-episode-6-radiant-custom-fields-and-stereotype-extensions [rcf]:http://github.com/Aissac/radiant-custom-fields-extension [rst]:http://github.com/Aissac/radiant-stereotype-extension <file_sep>class Globalize2PaperclippedExtension < Radiant::Extension version "0.1" description "Translate Paperclipped Assets using Radiant Globalize2 Extension." url "http://blog.aissac.ro/radiant/globalize2paperclipped-extension/" def activate throw "Globalize2 Extension must be loaded before Globalize2Paperclipped" unless defined?(Globalize2Extension) throw "Paperclipped Extension must be loaded before Globalize2Paperclipped" unless defined?(PaperclippedExtension) PaperclippedExtension.admin.asset.index.add :top, 'admin/shared/change_locale_admin' PaperclippedExtension.admin.asset.edit.add :main, 'admin/shared/change_asset_locale', :before => 'edit_form' PaperclippedExtension.admin.asset.index.add :thead, 'admin/shared/globalize_th' PaperclippedExtension.admin.asset.index.add :tbody, 'admin/shared/globalize_asset_td' Asset.send(:translates, *[:title, :caption]) Asset.send(:include, Globalize2Paperclipped::AssetExtensions) Page.send(:include, Globalize2Paperclipped::Globalize2PaperclippedTags) Page.send(:include, Globalize2Paperclipped::PageExtensions) #compatibility Asset.send(:include, Globalize2Paperclipped::Compatibility::TinyPaper::AssetExtensions) if defined?(TinyPaperExtension) end def deactivate end end <file_sep>This is [episode 20][rce] of Radiantcasts. You'll see how and why to use Radiant Snippets. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/07/15/radiantcasts-episode-20-radiant-snippets<file_sep>This is the [third episode][rce] of [Radiantcasts][rc]. You’ll see how to address compabibility issues between [Globalize2 Extension][ge] and other extensions, as well as how to install and use [Globalize2 Paperclipped Extension][g2pe]. Login using "admin" as username and "radiant" as password [rce]:http://blog.aissac.ro/2009/11/02/episode-3-radiant-globalize2-compatibility-issues/ [rc]:http://blog.aissac.ro/category/radiantcasts/ [ge]:http://github.com/Aissac/radiant-globalize2-extension [g2pe]:http://github.com/Aissac/radiant-globalize2-paperclipped-extension<file_sep>This is [episode 24][rce] of Radiantcasts. Part two of Radiant As A Blog, where you'll see how to use and configure the [Comments Extension][ce] Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/11/04/radiantcasts-episode-24-radiant-as-a-blog-part-2-adding-comments/ [ce]:https://github.com/saturnflyer/radiant-comments<file_sep>This is [episode 10][rce] of Radiantcasts. You'll see how to install and basic usage of [Radiant Paperclipped Extension][rpe]. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/04/27/radiantcasts-episode-10-radiant-paperclipped-extension-basic-usage [rpe]:http://github.com/kbingman/paperclipped<file_sep>Event.observe(window, 'load', function () { Event.observe('enter_new_custom_field', 'click', function () { $$("select.select_name")[0].hide(); $("enter_new_custom_field").hide(); $$("input.tb_name")[0].show(); $("cancel_enter_new_custom_field").show(); }); Event.observe('cancel_enter_new_custom_field', 'click', function () { $$("select.select_name")[0].show(); $("enter_new_custom_field").show(); $$("input.tb_name")[0].hide(); $("cancel_enter_new_custom_field").hide(); }); Event.observe('add_new_custom_field_link', 'click', function () { $("add_new_custom_field_div").show(); $("add_new_custom_field_link").hide(); }); Event.observe('cancel_new_custom_field', 'click', function () { $("add_new_custom_field_div").hide(); $("add_new_custom_field_link").show(); }) });<file_sep># Sets up the Rails environment for Cucumber ENV["RAILS_ENV"] = "test" require File.expand_path(File.dirname(__FILE__) + '/../../../../../config/environment') require 'cucumber/rails/world' require 'cucumber/formatter/unicode' # Comment out this line if you don't want Cucumber Unicode support require 'webrat' Webrat.configure do |config| config.mode = :rails end require 'firewatir' require 'spec' Before do ActiveRecord::Base.connection.tables.each do |table| begin table.classify.constantize.delete_all rescue StandardError => e # silent end end dataset_session.load_datasets_for(self.class) end After do system "killall firefox-bin" end # Comment out the next two lines if you're not using RSpec's matchers (should / should_not) in your steps. require 'cucumber/rails/rspec' Cucumber::Rails::World.class_eval do include Dataset datasets_directory "#{RADIANT_ROOT}/spec/datasets" Dataset::Resolver.default = Dataset::DirectoryResolver.new("#{RADIANT_ROOT}/spec/datasets", File.dirname(__FILE__) + '/../../spec/datasets') self.datasets_database_dump_path = "#{Rails.root}/tmp/dataset" add_dataset :pages, :users, :custom_fields end<file_sep>Radiant Globalize2 Extension === About --- An extension by [Aissac][aissac] that helps translating content in [Radiant CMS][radiant] using the Globalize2 Rails Plugin. Tested on Radiant 0.8. Features --- * Provides the ability to translate your pages (title, slug, breadcrumb, description, keywords) using the Radiant admin interface. * Provides the ability to translate your snippets and layouts using the Radiant admin interface. * Radius tags for accessing the locales and translations. * Possibility to completely delete the translation for a page. Installation --- [Globalize2 Extension][arg2] has no known dependencies. [Globalize2 Rails Plugin][rg2] is bundled. Because Globalize2 Extension keeps the settings in the `Radiant::Config` table it is highly recommended to install the [Settings Extension][rse] git submodule add git://github.com/Squeegy/radiant-settings.git vendor/extensions/settings Finally, install Globalize2 Extension git submodule add git://github.com/Aissac/radiant-globalize2.git vendor/extensions/globalize2 Then run the rake tasks: rake radiant:extensions:globalize2:migrate rake radiant:extensions:globalize2:update Configuration --- ###Settings [Globalize2 Extension][arg2] keeps its settings in Radiant::Config table, so in order to use correctly the extension you need to create some settings: globalize.default_language = 'en' globalize.languages = 'ro,de' Usage --- You have the possibility to change the locale either on the pages/snippets/layouts index page, or on the page/snippet/layout edit page. Changing the locale using either options will change the locale for the entire application. When you need to delete a translation, when on the page edit action, you need to check the "Delete Translation" checkbox, before saving the page. Saving the page with the checked "Delete Translation" will erase only the translation for that particular locale. When creating a new page, the locale will be changed automatically to the default language. ###Available Tags * See the "available tags" documentation built into the Radiant page admin for more details. * Use the <r:locale /> tag to render the current locale. * Use the <r:locales /> tag to render the locales you use in the application. * Use the <r:with_locale /> tag to temporarly switch the locale within the block. * Use the <r:if_translation_title /> and <r:unless_translation_title /> tags to render the page only if/unless the title is translated. * Use the <r:if_translation_content /> and <r:unless_translation_content /> tags to render the page only if/unless the content is translated. * If you pass to <r:link /> tag the `locale` attribute it will generate the link to the translated version of the current document * The <r:children:each /> tag cycles through all of the **translated** children. If you need to cycle through all the children (regardless if they are translated or not) set the tag's `locale` attribute to `false` * If you're using the Paginate Extension, the <r:paginate:each /> tag will find only **translated** children. If you need to find all the children (regardless if they are translated or not) set the tag's `locale` attribute to `false` Compatibility --- The following extensions were tested and work with Globalize2 Extension: ### [Copy-Move][cm] You need to load Copy-Move before Globalize2 config.extensions = [ :copy_move, :globalize2, :all ] ### [Custom Fields][cf] You need to load Custom Fields before Globalize2 config.extensions = [ :custom_fields, :globalize2, :all ] ### [Reoder][ro] You need to migrate Reorder extension before Globalize2 ### [Paginate][pe] You need to load Paginate after Globalize2 config.extensions = [ :globalize2, :paginate, :all ] ### [Paperclipped][pc] You need to install [Globalize2Paperclipped][g2p] Extension. Follow the installation notes on the extension's official page. ### [Tiny Paper][tp] Because Tiny Paper is based on Paperclipped, you neeed to install [Globalize2Paperclipped][g2p]. ### Out-of-the-box compatible Other extensions that have been tested and don't need any special treatment: [Mailer Extension][rm], [Stereotype Extension][rs], [SNS Extension][sns], [SNS Minifier][snsm], [SNS SASS Filter Extension][snss], [Database Mailer Extension][dbm], [Super Export Extension][rse] TODO --- Contributors --- [rg2]: http://github.com/joshmh/globalize2 [aissac]: http://aissac.ro [radiant]: http://radiantcms.org/ [rse]: http://github.com/Squeegy/radiant-settings [arg2]: http://blog.aissac.ro/radiant/globalize2-extension/ [cm]:http://github.com/pilu/radiant-copy-move [cf]:http://github.com/Aissac/radiant-custom-fields-extension/ [ro]:http://github.com/radiant/radiant-reorder-extension/ [pe]:http://github.com/Aissac/radiant-paginate-extension/ [pc]:http://github.com/kbingman/paperclipped/ [g2p]:http://github.com/Aissac/radiant-globalize2-paperclipped-extension/ [tp]:http://github.com/Aissac/radiant-tiny-paper-extension/ [rm]:http://github.com/radiant/radiant-mailer-extension/ [rs]:http://github.com/Aissac/radiant-stereotype-extension/ [sns]:http://github.com/radiant/radiant-sns-extension/ [snsm]:http://github.com/Aissac/radiant-sns-minifier-extension/ [snss]:http://github.com/SwankInnovations/radiant-sns-sass-filter-extension/ [dbm]:http://github.com/Aissac/radiant-database-mailer-extension/ [rse]:http://github.com/Aissac/radiant-super-export-extension/tree/master<file_sep>This is [episode 15][rce] of Radiantcasts. You'll see how easy and fast you can I18N your [RadiantCMS][rcms] extensions. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/06/01/radiantcasts-episode-15-i18n-your-extensions [rcms]:http://github.com/radiant/radiant<file_sep>This is the [fifth episode][rce] of [Radiantcasts][rc]. You'll see how to use [Radiant Database Mailer Extension][rdm]. Login using "admin" as username and "radiant" as password [rce]:http://blog.aissac.ro/2010/03/16/episode-5-radiant-database-mailer-extension/ [rc]:http://blog.aissac.ro/category/radiantcasts/ [rdm]:http://github.com/Aissac/radiant-database-mailer-extension<file_sep>namespace :radiant do namespace :extensions do namespace :sitemap_xml do desc "Runs the migration of the Sitemap Xml extension" task :migrate => :environment do require 'radiant/extension_migrator' if ENV["VERSION"] SitemapXmlExtension.migrator.migrate(ENV["VERSION"].to_i) else SitemapXmlExtension.migrator.migrate end end desc "Copies public assets of the Sitemap Xml to the instance public/ directory." task :update => :environment do puts "This extension has no public assets. Nothing done." end desc "Syncs all available translations for this ext to the English ext master" task :sync => :environment do # The main translation root, basically where English is kept language_root = SitemapXmlExtension.root + "/config/locales" words = TranslationSupport.get_translation_keys(language_root) Dir["#{language_root}/*.yml"].each do |filename| next if filename.match('_available_tags') basename = File.basename(filename, '.yml') puts "Syncing #{basename}" (comments, other) = TranslationSupport.read_file(filename, basename) words.each { |k,v| other[k] ||= words[k] } # Initializing hash variable as empty if it does not exist other.delete_if { |k,v| !words[k] } # Remove if not defined in en.yml TranslationSupport.write_file(filename, basename, comments, other) end end end end end <file_sep>Radiant Lazy Snippet Extension === This feature allows to keep same interface for snippets managment, but at the same time allows you to adjust the logic of their load to user. How it works --- 'lazy_snippet' radiant tag renders javascript object and create replacement with spinner. When document is ready it calls for snippet by ajax and render result. Requirements --- * Prototype 1.6+ * Radiant 0.9 edge (may be will work on early versions, but not tested) Installation --- git clone git://github.com/cheef/radiant-lazy-snippet-extension.git vendor/extensions/lazy_snippet Then update assets rake radiant:extensions:lazy_snippet:update Usage --- * place <r:lazy_snippet name="%test%" /> tag to page/snippet/layout content, where %test% - name of your snippet * include on page prototype and lazy_snippets scripts, something like <script src="/javascripts/prototype.js" type="text/javascript></script> <script src="/javascripts/extensions/lazy_snippet/lazy_snippet.js" type="text/javascript></script> Contributors --- * <NAME> <file_sep>This is [episode 14][rce] of Radiantcasts. You'll see how easy and fast you can install and start using [RadiantCMS][rcms]. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/05/25/radiantcasts-episode-14-installing-radiantcms [rcms]:http://github.com/radiant/radiant<file_sep>class Stereotypes < Dataset::Base def load Radiant::Config['stereotype.post.parts'] = "body:markdown,sidebar:textile" Radiant::Config['stereotype.post.layout'] = 'Main' Radiant::Config['stereotype.post.status'] = 'published' Radiant::Config['stereotype.post.page_type'] = 'ArchivePage' end end<file_sep>namespace :radiant do namespace :extensions do namespace :globalize2_paperclipped do desc "Runs the migration of the Globalize2 Paperclipped extension" task :migrate => :environment do require 'radiant/extension_migrator' if ENV["VERSION"] Globalize2PaperclippedExtension.migrator.migrate(ENV["VERSION"].to_i) else Globalize2PaperclippedExtension.migrator.migrate end end desc "Copies public assets of the Globalize2 Paperclipped to the instance public/ directory." task :update => :environment do puts "Globalize2Paperclipped Extension has no public assets. Nothing done." end end end end<file_sep>class StereotypePagesDataset < Dataset::Base uses :pages def load create_page "With Stereotype" end end<file_sep>This is the [second episode][rce] of [Radiantcasts][rc]. You’ll see how to install and use the [Globalize2 Extension][ge] Login using "admin" as username and "radiant" as password [rce]:http://blog.aissac.ro/2009/10/25/episode-2-radiant-globalize2-extension/ [rc]:http://blog.aissac.ro/category/radiantcasts/ [ge]:http://github.com/Aissac/radiant-globalize2-extension<file_sep>module SiteControllerExtension def show_snippet url = get_url if @page = find_page(url) response = @page.render_snippet Snippet.find_by_name(params[:snippet]) render :text => response else render :template => 'site/not_found', :status => 404 end end protected def get_url url = params[:url] if Array === url url = url.join('/') else url = url.to_s end url end end<file_sep>This post uses **Markdown**. <file_sep>This is [episode 8][rce] of Radiantcasts. You'll see how to use [Radiant Chronicle Extension][rc]. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/04/13/radiantcasts-episode-8-radiant-chronicle-extension [rc]:http://github.com/jgarber/radiant-chronicle-extension<file_sep>require File.dirname(__FILE__) + '/../../spec_helper' describe Admin::CustomFieldsHelper do end <file_sep>namespace :radiant do namespace :extensions do namespace :stereotype do desc "Runs the migration of the Stereotype extension" task :migrate => :environment do puts "This extension does not affect the database. Nothing done." end desc "Copies public assets of the Stereotype to the instance public/ directory." task :update => :environment do puts "This extension has no public assets. Nothing done." end end end end <file_sep>Factory.define(:asset) do |f| f.sequence(:title) { |i| "Picture #{i}" } f.caption { |a| "#{a.title} caption" } f.asset_file_name { |a| "#{a.title.underscore}.jpg" } f.asset_content_type "image/jpeg" f.asset_file_size 44760 end Factory.define(:romanian_asset_translation, :class => "asset_translation") do |f| f.locale "ro" f.association :asset, :factory => :asset f.title "Imagine" f.caption "Imagine caption" end Factory.define(:page) do |f| f.sequence(:title) { |i| "Page #{i}"} f.slug { |a| a.title.downcase.gsub(/[^-a-z0-9~\s\.:;+=_]/, '').gsub(/[\s\.:;=+]+/, '-') } f.breadcrumb { |a| a.title } end Factory.define(:page_attachment) do |f| f.page { |page| page.association(:page) } f.asset { |asset| asset.association(:asset) } end<file_sep>module Globalize2Paperclipped::Compatibility module TinyPaper::AssetExtensions def self.included(base) base.class_eval do named_scope :by_title, lambda{ |search_term| { :joins => "INNER JOIN asset_translations on asset_translations.asset_id = assets.id", :conditions => ["LOWER(asset_translations.title) LIKE ? AND asset_translations.locale = ?", "%#{search_term.to_s.downcase}%", I18n.locale]}} end end end end<file_sep># Uncomment this if you reference any of your controllers in activate # require_dependency 'application_controller' class LazySnippetExtension < Radiant::Extension version "1.0" description "This extension provides snippet's lazy loading via ajax after page loading" url "http://github.com/cheef/radiant-lazy-snippet-extension" define_routes do |map| map.with_options :controller => 'site' do |site| site.connect 'snippet', :action => 'show_snippet' end end def activate include_radius_tags extend_site_controller end protected def include_radius_tags Page.send :include, LazySnippetTags end def extend_site_controller SiteController.send :include, SiteControllerExtension end end <file_sep>This is [episode 23][rce] of Radiantcasts. Part one of a series of episodes where you'll see a quick rundown of extensions and techniques that can used to publish blogs with Radiant. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/08/26/radiantcasts-episode-23-radiant-as-a-blog-part-1<file_sep>This is the [fourth episode][rce] of [Radiantcasts][rc]. You'll see how to use [Radiant Mailer Extension][rm]. Login using "admin" as username and "radiant" as password [rce]:http://blog.aissac.ro/2009/12/12/episode-4-radiant-mailer-extension-basic-usage/ [rc]:http://blog.aissac.ro/category/radiantcasts/ [rm]:http://github.com/radiant/radiant-mailer-extension<file_sep>This is the [seventh episode][rce] of Radiantcasts. You'll see how to use [Radiant Styles 'n Scripts (SNS) Extension][rs] along with [SNS Minifier][rsm] and [SNS SASS Filter][rssf] extensions Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/04/06/radiantcasts-episode-7-radiant-styles-n-scripts-extension [rs]:http://github.com/SwankInnovations/radiant-sns-extension [rsm]:http://github.com/SwankInnovations/radiant-sns-minifier-extension [rssf]:http://github.com/SwankInnovations/radiant-sns-sass-filter-extension<file_sep>This is [episode 19][rce] of Radiantcasts. You'll see how to manage an use Radiant Layouts with the help of [Nested Layouts][nle] and [Stereotype][se] Extensions Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/07/08/radiantcasts-episode-19-radiant-layouts-reloaded [nle]:http://github.com/moklett/radiant-nested-layouts-extension [se]:http://github.com/Aissac/radiant-stereotype-extension<file_sep>module PaperclippedInterface def self.included(base) base.class_eval { before_filter :add_paperclipped_styles include InstanceMethods } end module InstanceMethods def add_paperclipped_styles include_javascript 'admin/assets.js' include_javascript 'admin/dragdrop.js' include_stylesheet 'admin/assets' end end end<file_sep># Sets up the Rails environment for Cucumber ENV["RAILS_ENV"] = "test" require File.expand_path(File.dirname(__FILE__) + '/../../../../../config/environment') require 'cucumber/rails/world' require 'cucumber/formatter/unicode' # Comment out this line if you don't want Cucumber Unicode support require 'webrat' Webrat.configure do |config| config.mode = :rails end Before do ActiveRecord::Base.connection.tables.each do |table| begin table.classify.constantize.delete_all rescue StandardError => e # silent end end Radiant::Config.create!(:key => 'globalize.languages', :value => "ro") if Radiant::Config['globalize.languages'].blank? Radiant::Config.create!(:key => 'assets.display_size', :value => "original") if Radiant::Config['assets.display_size'].blank? end require 'cucumber/rails/rspec' require 'webrat/core/matchers' gem 'thoughtbot-factory_girl', '>= 1.2.1' require 'factory_girl' require File.dirname(__FILE__) + "/../../spec/factories.rb"<file_sep>This is the [first episode][rce] of [Radiantcasts][rc]. You’ll see how to install and use the [Sitemap XML extension][sxl] and why should you use it. Login using "admin" as username and "radiant" as password [rce]:http://blog.aissac.ro/2009/10/20/episode-1-radiant-sitemap-xml-extension/ [rc]:http://blog.aissac.ro/category/radiantcasts/ [sxl]:http://github.com/Aissac/radiant-sitemap-xml-extension<file_sep>This is [episode 12][rce] of Radiantcasts. You'll see how some advanced features of [Radiant Paperclipped Extension][rpe]. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/05/11/radiantcasts-episode-12-radiant-paperclipped-extension-more-in-depth-features [rpe]:http://github.com/kbingman/paperclipped<file_sep>module Admin::CustomFieldsHelper def show_flash_message [:notice, :error, :success].map do |f| content_tag :div, flash[f], :class => "flash #{f}" if flash[f] end end end <file_sep>Given /^I am logged in as an admin$/ do User.create!(:login => 'admin', :password => '<PASSWORD>', :password_confirmation => '<PASSWORD>', :name => 'Administrator', :admin => true) Given "I go to to \"the welcome page\"" When "I fill in \"Username\" with \"admin\"" When "I fill in \"Password\" with \"<PASSWORD>\"" When "I press \"Login\"" end Given /^an asset "([^\"]*)" exists$/ do |title| Factory.create(:asset, :title => title) end<file_sep>Given /^I navigate to "([^\"]*)"$/ do |page_name| browser.goto("http://localhost:3001#{path_to(page_name)}") end Given /^I wait for the page to load$/ do browser.wait end Given /^I wait (\d+) seconds?$/ do |seconds| sleep seconds.to_i end Given /^I enter in "([^\"]*)" field "([^\"]*)"$/ do |field, value| browser.text_field(:id, field).set(value) end When /^I enter in "([^\"]*)" field "([^\"]*)" in the iframe$/ do |field, value| cf_frame.text_field(:id, field).set(value) end When /^I enter in "([^\"]*)" value "([^\"]*)" in the iframe$/ do |field_value, value| cf_frame.text_field(:value, field_value).set(value) end Given /^I select the "([^\"]*)" option from "([^\"]*)"$/ do |value, ddl| browser.select_list(:id, ddl).select(value) end Given /^I select the "([^\"]*)" option from "([^\"]*)" in the iframe$/ do |value, ddl| cf_frame.select_list(:id, ddl).select(value) end Given /^I click the "([^\"]*)" button$/ do |but| browser.button(:value, but).click sleep 1 end When /^I click the "([^\"]*)" button in the iframe$/ do |button| cf_frame.button(:value, button).click sleep 1 end Given /^I click the "([^\"]*)" link$/ do |lnk| link = browser.link(:text, lnk) link.click sleep 1 end Given /^I click the "([^\"]*)" link in the iframe$/ do |lnk| link = cf_frame.link(:text, lnk) link.click sleep 1 end When /^I click the Delete link in the iframe and confirm the dialog$/ do link = cf_frame.link(:text, "Delete") link.click browser.startClicker('OK', 1, '', "Are you sure you want to delete 'a_cf_on_first_page' custom field?") end Given /^I click the link with id "([^\"]*)"$/ do |lnk| browser.link(:id, lnk).click browser.wait end Then /^I must see "([^\"]*)"$/ do |text| browser.text.gsub(/\n/, ' ').gsub(/\s+/, ' ').should include(text) end Then /^I must see "([^\"]*)" in the iframe$/ do |text| cf_frame.text.gsub(/\n/, ' ').gsub(/\s+/, ' ').should include(text) end Then /^I must not see "([^\"]*)"$/ do |text| browser.text.gsub(/\n/, ' ').gsub(/\s+/, ' ').should_not include(text) end When /^I confirm the deletion$/ do browser.startClicker("ok", 1, '', "Are you sure you want to delete 'to delete custom field' custom field?") end <file_sep>module Globalize2Paperclipped module Globalize2PaperclippedTags include Radiant::Taggable class TagError < StandardError; end tag 'if_assets_with_globalize' do |tag| result = Asset.scope_locale(I18n.locale) do send('tag:if_assets_without_globalize', tag) end result end tag 'unless_assets_with_globalize' do |tag| result = Asset.scope_locale(I18n.locale) do send('tag:unless_assets_without_globalize', tag) end result end tag 'assets:each_with_globalize' do |tag| with_translated_locales = tag.attr['locale'] == 'false' ? false : true if with_translated_locales result = Asset.scope_locale(I18n.locale) do send('tag:assets:each_without_globalize', tag) end else result = send('tag:assets:each_without_globalize', tag) end result end desc %{ Renders the containing elements if the asset is translated *Usage:* <pre><code><r:if_translation_asset>...</r:if_translation_asset></code></pre> } tag 'assets:if_translation_asset' do |tag| asset = tag.locals.asset tag.expand if asset.translated_locales.include?(I18n.locale.to_sym) end desc %{ The opposite of the @if_translation_asset@ tag. Renders the containing elements if the asset is not translated *Usage:* <pre><code><r:unless_translation_asset>...</r:unless_translation_asset></code></pre> } tag 'assets:unless_translation_asset' do |tag| asset = tag.locals.asset tag.expand unless asset.translated_locales.include?(I18n.locale.to_sym) end end end<file_sep>This is [episode 9][rce] of Radiantcasts. You'll see how to use and how to add portability and version control friendliness to your Radiant CMS content using [Radiant Import Export Extension][rie], [Radiant Super Export Extension][rse] or [Radiant File System Extension][rfs]. Login using "admin" as username and "radiant" as password [rce]:http://radiantcms.org/blog/archives/2010/04/20/radiantcasts-episode-9-radiant-version-control-friendliness [rie]:http://github.com/radiant/radiant-import-export-extension [rse]:http://github.com/Aissac/radiant-super-export-extension [rfs]:http://github.com/nelstrom/radiant-file-system-extension<file_sep>Radiant Globalize2-Paperclipped Extension === About --- An extension by [Aissac][aissac] that helps translating [Radiant Paperclipped][pc] Assets using [Radiant Globalize2 Extension][arg2]. Tested on Radiant 0.8. Features --- * Provides the ability to translate Paperclipped assets (title and caption) using the Radiant admin interface. * Altered Paperclipped Radius Tags which take into account the locale Installation --- Globalize2-Paperclipped Extension has two dependencies: The [Paperclipped Extension][pc]: git submodule add git clone git://github.com/kbingman/paperclipped.git vendor/extensions/paperclipped And the [Radiant Globalize2 Extension][arg2] git submodule add git://github.com/Aissac/radiant-globalize2.git vendor/extensions/globalize2 Run the rake tasks, first for Paperclipped, then for Globalize 2: rake radiant:extensions:paperclipped:migrate rake radiant:extensions:paperclipped:update rake radiant:extensions:globalize2:migrate rake radiant:extensions:globalize2:update Install the Radiant Globalize2-Paperclipped Extension git submodule add git://github.com/Aissac/radiant-globalize2-paperclipped.git vendor/extensions/globalize2_paperclipped And run the rake tasks: rake radiant:extensions:globalize2_paperclipped:migrate rake radiant:extensions:globalize2_paperclipped:update Configuration --- For installation and configuration of [Paperclipped][pc] and [Globalize2][arg2] Extensions read their release notes. Being based on these two extensions Globalize2-Paperclipped needs to be loaded after both of them. config.extensions = [ :paperclipped, :globalize2, :globalize2_paperclipped, :all ] Usage --- You have the possibility to change the locale either on the assets index page, or on the asset edit page. As for the Globalize2, changing the locale using either options will change the locale for the entire application. ###Available Tags * See the "available tags" documentation built into the Radiant page admin for more details. * Use the <r:assets:if_translation_asset /> and <r:assets:unless_translation_asset /> tags to render the asset only if/unless it is translated * The <r:if_assets /> and <r:unless_assets /> tags render the contained elements only if/unless there are **translated** assets for the current locale. * The <r:assets:each /> tag cycles through all the **translated** assets attached to the current page. You can force the tag to cycle through all attached assets by setting the `locale` attribute to `false` Compatibility --- ### [Tiny Paper][tp] The Globalize2-Paperclipped Extension provides compatibility for Globalize2 and Radiant Tiny Paper. You only have to be careful about the extensions load order: config.extensions = [ :paperclipped, :globalize2, :tiny_paper, :globalize2_paperclipped, :all ] TODO --- Contributors --- [aissac]:http://aissac.ro [radiant]:http://radiantcms.org/ [arg2p]:http://blog.aissac.ro/radiant/globalize2-paperclipped-extension/ [pc]:http://github.com/kbingman/paperclipped/ [arg2]:http://blog.aissac.ro/radiant/globalize2-extension/ [tp]:http://github.com/Aissac/radiant-tiny-paper-extension/<file_sep>class CreateAssetsTranslationTable < ActiveRecord::Migration def self.up Asset.create_translation_table! :title => :string, :caption => :string Asset.all.each do |asset| translation = asset.globalize_translations. find_or_initialize_by_locale(Globalize2Extension.default_language.to_s) translation[:title] = asset[:title] translation[:caption] = asset[:caption] translation.save end remove_column :assets, :title remove_column :assets, :caption end def self.down add_column :assets, :title, :string add_column :assets, :caption, :string Asset.drop_translation_table! end end<file_sep>module Globalize2Paperclipped module AssetExtensions def self.included(base) base.extend(ClassMethods) end module ClassMethods def scope_locale(locale, &block) with_scope(:find => { :joins => "INNER JOIN asset_translations on asset_translations.asset_id = assets.id", :conditions => ['asset_translations.locale = ?', locale] }) do yield end end end end end<file_sep>module WatirHelpers Watir::Browser.default = "firefox" def browser @browser ||= Watir::Browser.new end def cf_frame browser.frame(:id, 'CFframe') end def h(x) ERB::Util.h(x) end end World(WatirHelpers)
d7ed71228bbef94eb9b8ab2111d0426004c551e5
[ "Markdown", "JavaScript", "Ruby" ]
61
Ruby
cristi/radiantcasts-episodes
61d6fbeabd9ca6d309b2cd465f81dab321e9cf8e
f03c2e3c1606083b90b5f6f797bc04fef4399b33
refs/heads/master
<repo_name>spenceropope/steps-recorded<file_sep>/javascripts/kit.js var NUM_INSTRUMENTS = 2; function Kit(name) { this.SAMPLE_BASE_PATH = "sounds/drum-samples/"; this.name = name; this.kickBuffer = null; this.snareBuffer = null; this.hihatBuffer = null; this.tomhiBuffer = null; this.tommidBuffer = null; this.tomlowBuffer = null; this.clBuffer = null; this.cbBuffer = null; this.cpBuffer = null; this.cyBuffer = null; this.rsBuffer = null; this.c0Buffer = null; this.d0Buffer = null; this.e0Buffer = null; this.f0Buffer = null; this.g0Buffer = null; this.a0Buffer = null; this.b0Buffer = null; this.c1Buffer = null; this.d1Buffer = null; this.startedLoading = false; this.isLoaded = false; this.instrumentLoadCount = 0; } Kit.prototype.pathName = function() { return this.SAMPLE_BASE_PATH + this.name + "/"; }; Kit.prototype.load = function() { if (this.startedLoading) { return; } this.startedLoading = true; var pathName = this.pathName(); //don't want to have set number of instruments, or whatever var kickPath = pathName + "kick.mp3"; var snarePath = pathName + "snare.mp3"; var hihatPath = pathName + "hihat.mp3"; var tomhiPath = pathName + "tomhi.mp3"; var tommidPath = pathName + "tommid.mp3"; var tomlowPath = pathName + "tomlow.mp3"; var clPath = pathName + "cl.mp3"; var cbPath = pathName + "cb.mp3"; var cpPath = pathName + "cp.mp3"; var cyPath = pathName + "cy.mp3"; var rsPath = pathName + "rs.mp3"; var c0Path = pathName + "c0.wav"; var d0Path = pathName + "d0.wav"; var e0Path = pathName + "e0.wav"; var f0Path = pathName + "f0.wav"; var g0Path = pathName + "g0.wav"; var a0Path = pathName + "a0.wav"; var b0Path = pathName + "b0.wav"; var c1Path = pathName + "c1.wav"; var d1Path = pathName + "d1.wav"; this.loadSample(kickPath, "kick"); this.loadSample(snarePath, "snare"); this.loadSample(hihatPath, "hihat"); this.loadSample(tomhiPath, "tomhi"); this.loadSample(tommidPath, "tommid"); this.loadSample(tomlowPath, "tomlow"); this.loadSample(clPath, "cl"); this.loadSample(cbPath, "cb"); this.loadSample(cpPath, "cp"); this.loadSample(cyPath, "cy"); this.loadSample(rsPath, "rs"); this.loadSample(c0Path, "c0"); this.loadSample(d0Path, "d0"); this.loadSample(e0Path, "e0"); this.loadSample(f0Path, "f0"); this.loadSample(g0Path, "g0"); this.loadSample(a0Path, "a0"); this.loadSample(b0Path, "b0"); this.loadSample(c1Path, "c1"); this.loadSample(d1Path, "d1"); }; //also make a class per buffer/sample? can store prettified name? //this should definitely be part of a sample class, pass in kit or st //if we have the name of a sample type, then we can do metaprogramming awesomeness. Kit.prototype.loadSample = function(url, instrumentName) { //need 2 load asynchronously var request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = "arraybuffer"; var kit = this; request.onload = function() { context.decodeAudioData( request.response, function(buffer) { switch (instrumentName) { case "kick": kit.kickBuffer = buffer; break; case "snare": kit.snareBuffer = buffer; break; case "hihat": kit.hihatBuffer = buffer; break; case "tomhi": kit.tomhiBuffer = buffer; break; case "tommid": kit.tommidBuffer = buffer; break; case "tomlow": kit.tomlowBuffer = buffer; break; case "cl": kit.clBuffer = buffer; break; case "cb": kit.cbBuffer = buffer; break; case "cp": kit.cpBuffer = buffer; break; case "cy": kit.cyBuffer = buffer; break; case "rs": kit.rsBuffer = buffer; break; case "c0": kit.c0Buffer = buffer; break; case "d0": kit.d0Buffer = buffer; break; case "e0": kit.e0Buffer = buffer; break; case "f0": kit.f0Buffer = buffer; break; case "g0": kit.g0Buffer = buffer; break; case "a0": kit.a0Buffer = buffer; break; case "b0": kit.b0Buffer = buffer; break; case "c1": kit.c1Buffer = buffer; break; case "d1": kit.d1Buffer = buffer; break; } kit.instrumentLoadCount++; if (kit.instrumentLoadCount === NUM_INSTRUMENTS) { kit.isLoaded = true; } }, function(buffer) { console.log("Error decoding drum samples!"); } ); } request.send(); }<file_sep>/README.md step-sequencer using roland tr-808 samples. you can record the output of the step sequencer as a wav file and download, i guess the next step is posting the wav to a server but we will see. prob add some more effects as well.
6aba75b5f36f5f591dc99a368fdc104a63959532
[ "JavaScript", "Markdown" ]
2
JavaScript
spenceropope/steps-recorded
c4b26810f72560fd96c36fc3c04cc77b75531451
fb88dbbe9279e6c969a558bf85a87b7cc1ffac8b
refs/heads/master
<repo_name>0101vivek/0101vivek<file_sep>/adarsh_backend/routes/authRoutes.js const express = require('express'); const router = express.Router(); const parseUrl = express.urlencoded({extended: false}); const parseJson = express.json({extended: false}); const authControllers = require('../controllers/authcontrollers'); router.post('/signup',authControllers.signup_post); router.post('/login',authControllers.login_post ); router.post('/send_otp',authControllers.send_otp ); router.post('/resend_otp',authControllers.resend_otp); router.post('/verify_otp',authControllers.verify_otp); router.post('/reset_password',authControllers.reset_password); router.post('/getName',authControllers.getName); router.get('/luxury_room',authControllers.luxury_room); router.get('/super_delux_room',authControllers.super_delux); router.get('/delux_room',authControllers.delux_room); router.post('/book_room',authControllers.book_room); router.post('/booking_room_cancellation_history',authControllers.booking_history_for_cancellation); router.post('/cancel_room',authControllers.booking_room_can_be_cancel); router.post('/update',authControllers.update); router.post('/user_history',authControllers.user_history); router.post('/check_available_book_room',authControllers.check_book_room) router.post('/getDetails',authControllers.getDetails); router.post('/getDetailsByDate',authControllers.booking_history_by_date); // router.post('/generateToken',authControllers.generateToken) // router.post('/transaction_status',authControllers.trans_status) module.exports = router; <file_sep>/adarsh_backend/models/otpModel.js const mongoose = require('mongoose'); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var schema = new mongoose.Schema({ email: "String", phoneNo: "String", otp: "String", minute: "String", second : "String" }); var Otp_schema = mongoose.model("OtpModel", schema); module.exports = { Otp_schema }; <file_sep>/adarsh_backend/models/usermodel.js const mongoose = require('mongoose'); var schema = new mongoose.Schema({ first_name: "String", last_name: "String", email: "String", mobileno: "String", password: "<PASSWORD>" }); var User = mongoose.model("User", schema); module.exports = {User}; <file_sep>/adarsh_backend/index.js const express = require('express'); const app = express(); const authRoutes = require('./routes/authRoutes'); const port = 3000 || process.env.PORT; const mongoose = require('mongoose'); app.use(express.json({ extended: false })); app.get('/', (req, res) => { res.send('Hello World!') }) app.use(authRoutes); app.listen(port, async () => { await mongoose.connect("mongodb+srv://Pixel:<EMAIL>/ZEPRoomBooking?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: true }); console.log("connectDB"); console.log(`You are listening to port ${port}`); }); <file_sep>/adarsh_backend/models/roomModel.js const mongoose = require('mongoose'); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var schema = new mongoose.Schema({ image:"String", roomNumber: "Number", description:"String", charges:Number, status:"String", Type:"String", startDate:"String", uploaded : {type:"Date",default:Date.now} }); var Room_schema = mongoose.model("Room", schema); module.exports = {Room_schema};
2df523fd599982a773877b2b1e222e7928197e0e
[ "JavaScript" ]
5
JavaScript
0101vivek/0101vivek
ce4406c4c83a23f510827fef8277eda83dd2a175
c79fb5c69dd6a9e8ab8e7d467fd6978e91398e15
refs/heads/main
<file_sep>#ifndef LINKER_H #define LINKER_H #include <bits/stdc++.h> #include "./drone.h" class Linker { static Linker *instance; Linker() {}; // no object instance can be created public: std::mutex command_mutex; std::mutex error_mutex; int command; double error; static Linker* get_instance(); static void give_command(int command); static int get_command(); static void give_error(double error); static double get_error(); }; #endif // LINKER_H<file_sep># PID-controller-simulator This can be considered a homework for students who want to learn to implement a Proportional Derivative Integral (PID) Controller so I will not provide a solution just yet. This program is a simulation of the physics of a drone ascending. The drone has mass, it's in a gravitational field and has to reach a certain height. The drone is equipped with motors that do not have an instant response to simulate motors in the real world. The student has to write a PID Controller in the "pid.cpp" file and when he runs the program, the drone has to reach the target height as fast as possible with a minimal overshoot. <file_sep>CC=g++ CVERSION=-std=c++11 CFLAGS=-Wall -Wextra -pthread TEMP_CFLAGS=-Og RELEASE_CFLAGS=-O2 OUT_NAME=check_pid C_OUT_NAME=-o $(OUT_NAME) SOURCES=main.cpp linker.cpp pid.cpp drone.cpp build: $(CC) $(CVERSION) $(VERSION) $(CFLAGS) $(TEMP_CFLAGS) $(SOURCES) $(C_OUT_NAME) build_release: $(CC) $(CVERSION) $(VERSION) $(CFLAGS) $(RELEASE_CFLAGS) $(SOURCES) $(C_OUT_NAME) run: ./$(OUT_NAME) clean: rm $(OUT_NAME) altitude.out<file_sep>#ifndef DRONE_H #define DRONE_H #include <bits/stdc++.h> #include "./linker.h" #define FILE_OUT "altitude.out" #define SIM_TIME 10000// in U_SEC #define PRINT_INTERVAl 10000 #define TARGET 1000 #define AIR_DENSITY 1.2754 // kg/m^3 #define DRONE_MASS 0.4 // kg #define DRONE_TOP_AREA 0.018125 // m^2 #define DRONE_DRAG_COEFF 0.88 // approximate: a combination between the drag coefficient of a sqare and a 45 degree rotated square #define IDEAL 0.15 // dictates the response of the mottors to the command #define GROUND_LEVEL 0 #define INITIAL_ALTITUDE GROUND_LEVEL #define INITIAL_ERROR (GROUND_LEVEL - TARGET) // the initial error from the target altitude #define INITIAL_COMMAND 0 #define INITIAL_SPEED 0 #define TIME_STAMP_US 100 // bigger makes the drone calculate its next position slower #define FROM_US_TO_S(x) (x / 1000000.0) #define MAX_COMMAND 2000 #define MIN_COMMAND 0 #define FROM_COMMAND_TO_FORCE 0.02 // For a maximum comand of 2000, we have the maximum up speed of 40m/s from // whitch we subtract 10m/s // #define MAX_SPEED_UP 30 #define GRAVITY -10 // #define MAX_SPEED (MAX_SPEED_UP - MAX_SPEED_DOWN) void start_drone(const long duration); double set_accel(int &past_command, int command, double speed); void border_command(int &command); #endif // DRONE_H<file_sep>#include "./pid.h" // point plotter with the boundries already set // just paste the content of altitude.out in the text box and the points will be plotted // http://fooplot.com#W3sidHlwZ<KEY>-- // mentions, you can only use the following functions // to get the error from the target altitude // double read_error(void) // to give commands to the mottors // valid input: 0 - 4000 // void set_motor_command(int command) void loop() { // TO_DO // a PID controller set_motor_command(5000); } void set_motor_command(int command) { Linker::get_instance()->give_command(command); } double read_error() { return Linker::get_instance()->get_error(); }<file_sep>#include <bits/stdc++.h> #include "./linker.h" #include "./drone.h" #include "./pid.h" void pid_caller(std::future<void> futureObj); int main() { Linker::give_command(INITIAL_COMMAND); Linker::give_error(INITIAL_ERROR); std::cout << "Welcome to PID simulator. The simulator is starting now..." << std::endl; // make a mechanism to stop the thread at the end std::promise<void> exitSignal; std::future<void> futureObj = exitSignal.get_future(); // strat the pid thread std::thread pid_thread(pid_caller, std::move(futureObj)); // start the drone start_drone(SIM_TIME); std::cout << "Well done, the simulater is shuting down..." << std::endl; // the simulation ends exitSignal.set_value(); pid_thread.join(); std::cout << "Have a nice day :)" << std::endl; return 0; } void pid_caller(std::future<void> futureObj) { while (futureObj.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout) { loop(); } }<file_sep>#ifndef PID_H #define PID_H #include <bits/stdc++.h> #include "./linker.h" void loop(); void set_motor_command(int command); double read_error(); #endif // PID_H<file_sep>#include "./drone.h" void start_drone(const long duration) { // time management auto start_time = std::chrono::high_resolution_clock::now(); auto now = std::chrono::high_resolution_clock::now(); auto past_now = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed; // get the simulator initial values that were preset double altitude = INITIAL_ALTITUDE; double error = Linker::get_error(); double target = altitude - error; int past_command = Linker::get_command(); int command = past_command; double accel = GRAVITY; double speed = INITIAL_SPEED; // output file std::ofstream fout(FILE_OUT); int no_x = 0; int out_counter = 0; while (1) { // take the info from the linker command = Linker::get_command(); //calculate the acceleration from command if (past_command != command) { accel = set_accel(past_command, command, speed); } // calculate the speed from the acceleration speed = speed + accel * FROM_US_TO_S(TIME_STAMP_US); // sleep until the time stamp is finished and we continue with the next frame struct timespec req = {0, 0}; req.tv_sec = 0; auto nsec = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - past_now); req.tv_nsec = TIME_STAMP_US - nsec.count(); nanosleep(&req, (struct timespec *) NULL); // the new past time reference past_now = now; // the new position is calculated just now, after the wait altitude += speed * FROM_US_TO_S(TIME_STAMP_US); if (altitude < 0) altitude = 0; error = altitude - target; // send the new position Linker::give_error(error); // TO_DO // vant random sa bata // TO_DO // output if (out_counter >= PRINT_INTERVAl) { out_counter = 0; // std::cout << "A: " << std::setw(12) << accel << " | V: " << // std::setw(12) << speed << " | Err: " << // std::setw(12) << error << " | Alt: " << // std::setw(12) << altitude << "\n"; fout << no_x++ << "," << (int)error << "\n"; } ++out_counter; // timer to finish the simulation nsec = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time); if (nsec.count() > duration) { break; } } fout.close(); } inline double set_accel(int &past_command, int command, double speed) { // ensure that the comand is between certain values border_command(command); // the motors are not ideal so they can not change their response imidietlly if (std::abs(past_command - command) > ((MAX_COMMAND - MIN_COMMAND) * IDEAL)) { if (command < past_command) { command = past_command - ((MAX_COMMAND - MIN_COMMAND) * IDEAL); } else { command = past_command + ((MAX_COMMAND - MIN_COMMAND) * IDEAL); } border_command(command); } past_command = command; // the command is transformed to force (Newtons) double force = FROM_COMMAND_TO_FORCE * command + GRAVITY * DRONE_MASS - 0.5 * AIR_DENSITY * speed * speed * DRONE_DRAG_COEFF * DRONE_TOP_AREA; // a = F / m double acceleration = force / DRONE_MASS; return acceleration; } inline void border_command(int &command) { // Brenchless version of the if code, but the compiler is optimizing the code // better at compile time as we can see if we analize the assembly code // generated: 3 instructions generated by the compiler for the normal version // VS. 8 more complex instructions generated by our "smart" version // command = (command * (command > MIN_COMMAND && command < MAX_COMMAND)) + // (MIN_COMMAND * (command < MIN_COMMAND)) + // (MAX_COMMAND * (command > MAX_COMMAND)); if (command < MIN_COMMAND) { command = MIN_COMMAND; } else if (command > MAX_COMMAND) { command = MAX_COMMAND; } }<file_sep>#include "./linker.h" Linker* Linker::instance = NULL; Linker* Linker::get_instance() { if (instance == NULL) { instance = new Linker(); } return instance; } void Linker::give_command(int _command) { std::lock_guard <std::mutex> guard(Linker::get_instance()->command_mutex); Linker::get_instance()->command = _command; } // you are not allowed to call this funciton int Linker::get_command() { std::lock_guard <std::mutex> guard(Linker::get_instance()->command_mutex); return Linker::get_instance()->command; } // you are not allowed to call this funciton void Linker::give_error(double _error) { std::lock_guard <std::mutex> guard(Linker::get_instance()->error_mutex); Linker::get_instance()->error = _error; } double Linker::get_error() { std::lock_guard <std::mutex> guard(Linker::get_instance()->error_mutex); return Linker::get_instance()->error; }
805599974174062d431f10e74bab8f7d2bb4e001
[ "Markdown", "C", "Makefile", "C++" ]
9
C++
Robert-ML/PID-controller-simulator
1f3b05a91ce7f555d1f50f049fa749d86120bf32
28f176bc29216d229add93c72cf317eaa7e9779b
refs/heads/master
<file_sep>#include <iostream> #include <opencv2\opencv.hpp> #include <vector> using namespace std; using namespace cv; Mat imgRotate(Mat &img, float angle) { Mat retMat = Mat::zeros(390, 1200, CV_8UC1); // 因为裁剪的是这个size大小的区域 float anglePI = (float)(angle * CV_PI / 180); int xR, yR; for (int i = 0; i < retMat.rows; i++) for (int j = 0; j < retMat.cols; j++) { // (i-retMat.rows/2)和(j-retMat.cols/2)是因为图像按(retMat.cols/2,retMat.rows/2)为旋转点旋转的 xR = (int)((i - retMat.rows / 2)*cos(anglePI) - (j - retMat.cols / 2)*sin(anglePI) + 0.5); yR = (int)((i - retMat.rows / 2)*sin(anglePI) + (j - retMat.cols / 2)*cos(anglePI) + 0.5); xR += img.rows / 2; // xR和yR表示在计算完之后,需要再次还原到相对左上角原点的旧坐标 yR += img.cols / 2; if (xR >= img.rows || yR >= img.cols || xR <= 0 || yR <= 0) { retMat.at<uchar>(i, j) = uchar(0); // 如果是彩色图用reMat.at<Vec3b>(i,j) = Vec3b(0, 0); } else { retMat.at<uchar>(i, j) = img.at<uchar>(xR, yR); } } return retMat; } void colsNormalization(Mat src, Mat& out) // 去掉钢条的边 { out = src.clone(); int value; int count=100; // 可以理解为钢条边界白色点最小长度 int pixel=5; // 像素阈值 if (src.type() == CV_8UC1) { for (size_t i = 0; i < src.cols; i++) { int Count = 0; for (size_t j = 0; j < src.rows; j++) { value = src.at<uchar>(j, i); // .at<>(行,列) 灰度图用uchar,彩色图用Vec3 if (value > pixel) { Count++; // 像素点大于阈值的计数器 } } if (Count > count) { for (size_t n = 0; n < src.rows; n++) { out.at<uchar>(n, i) = 0; // 全列置0 } } } } } int main() { Mat input_img = imread("G:\\detect_img\\5.bmp"); // size(1440,1920); Mat gray_out; cvtColor(input_img, gray_out, CV_BGR2GRAY); Mat ROI_img; ROI_img = gray_out(Rect(330, 1050, 1200, 390)); Mat gaussian_out; GaussianBlur(ROI_img, gaussian_out, Size(11, 11), 1, 1); Mat median_out; medianBlur(gaussian_out, median_out, 5); Mat element = getStructuringElement(MORPH_RECT, Size(3, 3)); Mat dilate_out, erode_out; dilate(median_out, dilate_out, element); erode(dilate_out, erode_out, element); Mat thresh_out; adaptiveThreshold(erode_out, thresh_out, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 25, -15); namedWindow("aa", WINDOW_NORMAL); resizeWindow("aa", 500, 500); imshow("aa", thresh_out); vector<Vec4i> lines; double theta; HoughLinesP(thresh_out, lines, 1, CV_PI/180, 50, 300, 300); // 为了求钢条倾斜的角度 double sum = 0; for (size_t i = 0; i < lines.size(); i++) { //Vec4i l = lines[i]; //line(thresh_out, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(55, 100, 195), 1, CV_AA); theta = CV_PI/180*lines[i][1]; // 弧度转换角度 sum += theta; } double average = sum / lines.size(); double angle = average - 2.0; // 钢条倾斜角 Mat rotate_img; rotate_img = imgRotate(thresh_out, -angle); // 负数代表逆时针旋转 Mat gaussian; GaussianBlur(rotate_img, gaussian, Size(15, 15), 1, 1); Mat normalization_out; colsNormalization(gaussian, normalization_out); namedWindow("normalization", WINDOW_NORMAL); resizeWindow("normalization", 500, 500); imshow("normlization", normalization_out); Mat rotate_Img; // 得到的划痕区域 rotate_Img = imgRotate(normalization_out, angle); //****************************************************划痕区域以提取出来************************************************ Mat dst = Mat::zeros(input_img.size(), CV_8UC1); Mat mask = rotate_Img; Mat imgROI = dst(Rect(330, 1050, 1200, 390)); mask.copyTo(imgROI, mask); // 将划痕放到原尺寸大小的全0矩阵中 vector<Vec4i> Lines; HoughLinesP(dst, Lines, 1, CV_PI / 180, 150, 5, 5); // 找划痕 for (size_t i = 0; i < Lines.size(); i++) { Vec4i l = Lines[i]; line(dst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(255, 255, 255), 1, CV_AA); } cvtColor(dst, dst, CV_GRAY2BGR); Mat Dst; vector<Mat> mv; split(dst, mv); for (int i = 0; i < mv[0].rows; i++) { uchar* data = mv[0].ptr<uchar>(i); uchar* data1 = mv[1].ptr<uchar>(i); for (int j = 0; j < mv[0].cols; j++) { data[j] = 0 * data[j]; data1[j] = 0; } } merge(mv, Dst); // 划痕已染红 Mat out; add(input_img, Dst, out); // 划痕变色图与原图像相加 namedWindow("out", WINDOW_NORMAL); imshow("out", out); waitKey(0); } <file_sep># steel-bar-scratch-detection Hello guys, this is an algorithm demo code I wrote in a machine vision project. In the strong exposure interference and unenclosed space environment, the small points and scratched areas on the steel bar can be effectively extracted and colored. # environment: Microsoft visual studio 2017 opencv 2.4.1 # output image ![Image text](https://github.com/QHXCoder2017/steel-bar-scratch-detection/blob/master/out1.png) ![Image text](https://github.com/QHXCoder2017/steel-bar-scratch-detection/blob/master/out2.png) ![Image text](https://github.com/QHXCoder2017/steel-bar-scratch-detection/blob/master/out3.png)
bc02e82d98818f95a47ee5c0c0e62b55422f42f9
[ "Markdown", "C++" ]
2
C++
jtpils/steel-bar-scratch-detection
c8469ce25fb113b3e04e6c1d3656761c7b6b9308
e74ff6ba49695a66d5e97d8dfe2e5d87dedb886c
refs/heads/master
<repo_name>Hopps/Informatik-Mdl<file_sep>/datenstrukturen/Knoten.java package datenstrukturen; /** * @author merlin */ public class Knoten{ private Object zInhalt; private Knoten kenntNachfolger = null; private Knoten kenntVorgaenger = null; public Knoten(){ } public Knoten(Object pInhalt) { zInhalt = pInhalt; } public void setVorgaenger(Knoten pVorgaenger) { kenntVorgaenger = pVorgaenger; } public Knoten getVorgaenger() { return kenntVorgaenger; } public void setNachfolger(Knoten pNachfolger) { kenntNachfolger = pNachfolger; } public Knoten getNachfolger() { return kenntNachfolger; } public Object inhalt() { return zInhalt; } public void setInhalt(Object pInhalt) { zInhalt = pInhalt; } } <file_sep>/datenstrukturen/Schlange.java package datenstrukturen; public class Schlange<Type> { Knoten Kopf; public Schlange() { } public void fuegeEin(Type obj) { if (Kopf == null) { Kopf = new Knoten(obj); } else { Kopf.fuegeAn(new Knoten(obj)); } } public void entferneKopf() { Kopf = Kopf.getNachFolger(); } public Knoten getKopf() { return Kopf; } public Type getInhalt() { return Kopf.getInhalt(); } class Knoten { Knoten nachFolger; Type inhalt; public Knoten(Type obj) { inhalt = obj; } private void fuegeAn(Knoten d) { if (nachFolger == null) { nachFolger = d; } else { nachFolger.fuegeAn(d); } } private Type getInhalt() { return inhalt; } private Knoten getNachFolger() { return nachFolger; } } } <file_sep>/abstractclasstest/Tier.java package abstractclasstest; public abstract class Tier { public abstract void abstrakteMethode(); } <file_sep>/datenstrukturen/AdjazenzMatrix.java package datenstrukturen; /** * @author merlin */ public class AdjazenzMatrix { private int zN; private int[][] adjaMa; public AdjazenzMatrix(int pN) { zN = pN; adjaMa = new int[zN][zN]; for (int i = 0; i < zN; i++) { for (int j = 0; j < zN; j++) { adjaMa[i][j] = -1; // Keine Verbindung } } } public void set(int pStartknoten, int pZielknoten, int pWert) { adjaMa[pStartknoten][pZielknoten] = pWert; } public int get(int pStartknoten, int pZielknoten) { return adjaMa[pStartknoten][pZielknoten]; } public int[] nachbarKnoten(int pKnoten) { int lAnzahl = 0; for (int i = 0; i < zN; i++) { if (adjaMa[pKnoten][i] > -1) { lAnzahl++; } } int[] lReturn = new int[lAnzahl]; for (int j = 0; j < lAnzahl; j = j) { for (int i = 0; i < zN; i++) { if (adjaMa[pKnoten][i] > -1) { lReturn[j] = i; j++; } } } return lReturn; } public void listeAlleKnoten(int pStartknoten) { this.durchlaufe(pStartknoten, new int[zN]); } private void durchlaufe(int pStartknoten, int[] pBesucht) { if (pBesucht[pStartknoten] != 1) { System.out.println(pStartknoten); } pBesucht[pStartknoten] = 1; int[] lNachbar = this.nachbarKnoten(pStartknoten); for (int i = 0; i < lNachbar.length; i++) { if (pBesucht[lNachbar[i]] != 1) { this.durchlaufe(lNachbar[i], pBesucht); } } } public int entfernung(int pStart, int pZiel) { int lAktuellerKnoten = pStart; int[] lEntfernung = new int[zN]; for (int i = 0; i < zN; i++) { lEntfernung[i] = -1; } lEntfernung[pStart] = 0; while ( this.unbesuchteKnoten(lEntfernung) ) { } return lEntfernung[pZiel]; } private boolean unbesuchteKnoten(int[] lInt) { boolean lReturn = false; for ( int i = 0; i < lInt.length; i++ ) { if ( lInt[i] == -1 ) { lReturn = true; } } return lReturn; } }<file_sep>/datenstrukturen/Stapel.java package datenstrukturen; //TEst public class Stapel<Type> { Knoten Kopf; public Stapel() { } public void fuegeEin(Type obj) { if (Kopf == null) { Kopf = new Stapel.Knoten(obj); } else { Knoten pKopf = Kopf; Kopf = new Stapel.Knoten(obj); Kopf.fuegeAn(pKopf); } } public void entferneKopf() { Kopf = Kopf.getNachFolger(); } public Knoten getKopf() { return Kopf; } public Type getInhalt() { return Kopf.getInhalt(); } class Knoten { Knoten nachFolger; Type inhalt; public Knoten(Type obj) { inhalt = obj; } private void fuegeAn(Knoten d) { if (nachFolger == null) { nachFolger = d; } else { nachFolger.fuegeAn(d); } } private Type getInhalt() { return inhalt; } private Knoten getNachFolger() { return nachFolger; } } } <file_sep>/datenstrukturen/SortierListe.java package datenstrukturen; import datenstrukturen.Liste; public class SortierListe extends Liste { public SortierListe() { super(); } public void quicksort() { SortierListe lLinkeListe = new SortierListe(); SortierListe lRechteListe = new SortierListe(); Integer pivot = null; if (this.laenge() > 0) { this.zumAnfang(); pivot = (Integer) this.aktuellesElement(); this.entferneAktuell(); // Pivot raus while (this.laenge() > 0) { this.zumAnfang(); if ((Integer) this.aktuellesElement() < pivot) { lLinkeListe.haengeAn(this.aktuellesElement()); this.entferneAktuell(); } else if ((Integer) this.aktuellesElement() >= pivot) { lRechteListe.haengeAn(this.aktuellesElement()); this.entferneAktuell(); } } } if (lLinkeListe.laenge() > 0) { lLinkeListe.quicksort(); } if (lRechteListe.laenge() > 0) { lRechteListe.quicksort(); } while (lLinkeListe.laenge() > 0) { lLinkeListe.zumAnfang(); this.haengeAn(lLinkeListe.aktuellesElement()); lLinkeListe.entferneAktuell(); } if (pivot != null) { this.haengeAn(pivot); } while (lRechteListe.laenge() > 0) { lRechteListe.zumAnfang(); this.haengeAn(lRechteListe.aktuellesElement()); lRechteListe.entferneAktuell(); } } }<file_sep>/datenstrukturen/TestCase.java package datenstrukturen; public class TestCase { BinBaum baum; BinSuchBaum sBaum; public TestCase() { } public static void main(String[] args) { TestCase tc = new TestCase(); //tc.erstelleBaum(); tc.adjama(); } private void erstelleBaum() { /* * baum = new BinBaum(5); baum.setzeLinks(new BinBaum(4)); * baum.setzeRechts(new BinBaum(7)); * baum.linkerTeilbaum().setzeLinks(new BinBaum(8)); * baum.linkerTeilbaum().setzeRechts(new BinBaum(10)); * baum.rechterTeilbaum().setzeLinks(new BinBaum(3)); * baum.linkerTeilbaum().rechterTeilbaum().setzeRechts(new BinBaum(2)); * System.out.println("Preorder"); preorder(baum); * System.out.println("Inorder"); inorder(baum); * System.out.println("Postorder"); postorder(baum); */ sBaum = new BinSuchBaum(5); sBaum.fuegeEin(4); sBaum.fuegeEin(8); sBaum.fuegeEin(10); sBaum.fuegeEin(16); sBaum.fuegeEin(2); sBaum.fuegeEin(9); //System.out.println("Preorder"); //preorder(sBaum); System.out.println("Inorder"); inorder(sBaum); sBaum.loesche(10); inorder(sBaum); //System.out.println("Postorder"); //postorder(sBaum); } private void preorder(BinBaum pKnoten) { System.out.println(pKnoten.inhalt()); if (pKnoten.linkerTeilbaum() != null) { preorder(pKnoten.linkerTeilbaum()); } if (pKnoten.rechterTeilbaum() != null) { preorder(pKnoten.rechterTeilbaum()); } } private void inorder(BinBaum pKnoten) { if (pKnoten.linkerTeilbaum() != null) { inorder(pKnoten.linkerTeilbaum()); } System.out.println(pKnoten.inhalt()); if (pKnoten.rechterTeilbaum() != null) { inorder(pKnoten.rechterTeilbaum()); } } private void postorder(BinBaum pKnoten) { if (pKnoten.linkerTeilbaum() != null) { postorder(pKnoten.linkerTeilbaum()); } if (pKnoten.rechterTeilbaum() != null) { postorder(pKnoten.rechterTeilbaum()); } System.out.println(pKnoten.inhalt()); } public void adjama() { AdjazenzMatrix a = new AdjazenzMatrix(4); a.set(0, 1, 1); a.set(0, 3, 1); a.set(1, 0, 1); a.set(1, 2, 1); a.set(2, 2, 1); a.set(3, 0, 1); a.set(3, 1, 1); a.set(3, 2, 1); /**int[] nachbar = a.nachbarKnoten(3); for (int i = 0; i < nachbar.length; i++) { System.out.println(nachbar[i]); }*/ a.listeAlleKnoten(0); } }<file_sep>/datenstrukturen/BinSuchBaum.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package datenstrukturen; /** * * @author Bluekey */ public class BinSuchBaum<Integer> extends BinBaum { public BinSuchBaum() { super(); } public BinSuchBaum(Integer pInhalt) { super(pInhalt); } public void fuegeEin(int pInhalt) { if (this.inhalt() == null) { this.setzeInhalt(pInhalt); } else if ((int) pInhalt < (int) this.inhalt()) { if (this.linkerTeilbaum() == null) { this.setzeLinks(new BinSuchBaum(pInhalt)); this.linkerTeilbaum().setzeVater(this); } else { ((BinSuchBaum) linkerTeilbaum()).fuegeEin(pInhalt); } } else { if (this.rechterTeilbaum() == null) { this.setzeRechts(new BinSuchBaum(pInhalt)); this.rechterTeilbaum().setzeVater(this); } else { ((BinSuchBaum) rechterTeilbaum()).fuegeEin(pInhalt); } } } public void loesche(int pInhalt) { if ((int) this.inhalt() != pInhalt) { if (this.linkerTeilbaum() != null) { ((BinSuchBaum) this.linkerTeilbaum()).loesche(pInhalt); } if (this.rechterTeilbaum() != null) { ((BinSuchBaum) this.rechterTeilbaum()).loesche(pInhalt); } } else if ((int) this.inhalt() == pInhalt) { if (this.istBlatt()) { this.setzeInhalt(null); if (this.vater().rechterTeilbaum() == this) { this.vater().setzeRechts(null); } if (this.vater().linkerTeilbaum() == this) { this.vater().setzeLinks(null); } } else if (this.linkerTeilbaum() != null && this.rechterTeilbaum() == null) { this.setzeInhalt(this.linkerTeilbaum().inhalt()); this.setzeRechts(this.linkerTeilbaum().rechterTeilbaum()); this.rechterTeilbaum().setzeVater(this); this.setzeLinks(this.linkerTeilbaum().linkerTeilbaum()); this.linkerTeilbaum().setzeVater(this); } else if (this.rechterTeilbaum() != null && this.linkerTeilbaum() == null) { this.setzeInhalt(this.rechterTeilbaum().inhalt()); this.setzeLinks(this.rechterTeilbaum().linkerTeilbaum()); this.linkerTeilbaum().setzeVater(this); this.setzeRechts(this.rechterTeilbaum().rechterTeilbaum()); this.rechterTeilbaum().setzeVater(this); } else if (this.rechterTeilbaum() != null && this.linkerTeilbaum() != null) { BinBaum lRechts = this.rechterTeilbaum(); this.setzeInhalt(this.linkerTeilbaum().inhalt()); this.setzeRechts(this.linkerTeilbaum().rechterTeilbaum()); this.rechterTeilbaum().setzeVater(this); this.setzeLinks(this.linkerTeilbaum().linkerTeilbaum()); this.linkerTeilbaum().setzeVater(this); BinBaum lTB = this.rechterTeilbaum(); while (lTB.rechterTeilbaum() != null) { lTB = lTB.rechterTeilbaum(); } lTB.setzeRechts(lRechts); lTB.rechterTeilbaum().setzeVater(lTB); } } } } <file_sep>/datenstrukturen/Liste.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package datenstrukturen; /** * @author merlin */ public class Liste{ private Knoten hatBug; // Die beiden werden Sentinels genannt, enthalten private Knoten hatHeck; // keine Daten und erleichtern Anfügen und Löschen. private Knoten kenntAktuell; // Markierung für aktuellen Knoten private int zAnzahl = 0; // Anzahl der Knoten (ohne Sentinels) public Liste() { hatBug = new Knoten(); hatHeck = new Knoten(); hatBug.setNachfolger(hatHeck); hatHeck.setVorgaenger(hatBug); kenntAktuell = hatBug; zAnzahl = 0; } public void zumAnfang() { if ( zAnzahl > 0) { kenntAktuell = hatBug.getNachfolger(); } else { kenntAktuell = hatBug; } } public void zumEnde() { if ( zAnzahl > 0) { kenntAktuell = hatHeck.getVorgaenger(); } else { kenntAktuell = hatHeck; } } public void vor() { if ( kenntAktuell != hatHeck ) { kenntAktuell = kenntAktuell.getNachfolger(); } } public void zurueck() { if ( kenntAktuell != hatBug ) { kenntAktuell = kenntAktuell.getVorgaenger(); } } public Object aktuellesElement() { return kenntAktuell.inhalt(); } public int laenge() { return zAnzahl; } public void fuegeDavorEin(Object pInhalt) { Knoten lKnoten = new Knoten(pInhalt); kenntAktuell.getVorgaenger().setNachfolger(lKnoten); lKnoten.setVorgaenger(kenntAktuell.getVorgaenger()); kenntAktuell.setVorgaenger(lKnoten); lKnoten.setNachfolger(kenntAktuell); zAnzahl++; } public void fuegeDahinterEin(Object pInhalt) { Knoten lKnoten = new Knoten(pInhalt); kenntAktuell.getNachfolger().setVorgaenger(lKnoten); lKnoten.setVorgaenger(kenntAktuell); lKnoten.setNachfolger(kenntAktuell.getNachfolger()); kenntAktuell.setNachfolger(lKnoten); zAnzahl++; } public void haengeAn(Object pInhalt) { Knoten lKnoten = new Knoten(pInhalt); hatHeck.getVorgaenger().setNachfolger(lKnoten); lKnoten.setVorgaenger(hatHeck.getVorgaenger()); lKnoten.setNachfolger(hatHeck); hatHeck.setVorgaenger(lKnoten); this.zumAnfang(); zAnzahl++; } public void entferneAktuell() { if ( kenntAktuell != hatBug && kenntAktuell != hatHeck ) { Knoten lVorgaenger = kenntAktuell.getVorgaenger(); Knoten lNachfolger = kenntAktuell.getNachfolger(); lVorgaenger.setNachfolger(lNachfolger); lNachfolger.setVorgaenger(lVorgaenger); this.zumAnfang(); zAnzahl--; } } }
153080ce7acb6bdc4ce59811e4b09b49a2165792
[ "Java" ]
9
Java
Hopps/Informatik-Mdl
806e41889518eaf52f12ebe1ba8a03cd33197271
a6cd2e4c72d2bfd8e7f8c8aaab0791df350f2cc2
refs/heads/master
<repo_name>royshouvik/rb101-programming-foundations<file_sep>/lesson_2/pass-by.rb def passed_by(param) puts param.object_id end a = 5.6 puts a.object_id passed_by(a)<file_sep>/lesson_2/calculator.rb puts "Enter the first number" number1 = gets.chomp puts "Enter the second number" number2 = gets.chomp puts "Enter the operation to perform: 1 - Addition, 2 - Subtraction, 3 - Multiplication and 4 - Division" operator = gets.chomp result = case operator when '1' then number1.to_i + number2.to_i when '2' then number1.to_i - number2.to_i when '3' then number1.to_i * number2.to_i when '4' then number1.to_f / number2.to_i end puts "The result is #{result}" <file_sep>/lesson_2/rock_paper_scissors.rb VALID_CHOICES = %w[rock paper scissors] WINNING_CHOICES = [ { user: 'rock', computer: 'scissors' }, { user: 'paper', computer: 'rock' }, { user: 'scissors', computer: 'paper' } ] def prompt(message) puts "=> #{message}" end def get_user_choice loop do prompt "Enter your choice (#{VALID_CHOICES.join(', ')})" choice = gets.chomp break choice if VALID_CHOICES.include?(choice) prompt "That's not a valid choice" end end def get_computer_choice VALID_CHOICES.sample end def display_result(user, computer) if user == computer prompt "It's a tie." elsif WINNING_CHOICES.include?(user: user, computer: computer) prompt 'You won!' else prompt 'Computer won.' end end def play_again? prompt 'Do you want to play again?' answer = gets.chomp answer.downcase.start_with?('y') end def start_game choice = get_user_choice computer_choice = get_computer_choice prompt "You chose #{choice}, computer chose #{computer_choice}" display_result(choice, computer_choice) start_game if play_again? end def main prompt 'Welcome to Rock, Paper, Scissors' start_game prompt 'Thanks for playing. Have a good day!' end main <file_sep>/lesson_2/mortgage_calculator.rb def prompt(message) puts "=> #{message}" end def greet prompt "Welcome to Mortgage Calculator v0.1! What's your name?" name = '' loop do name = gets.chomp break unless name.empty? prompt 'Please enter a valid name' end prompt "Hi, #{name.downcase.capitalize}" end def valid_int?(number) number.to_i.to_s == number end def valid_number?(number) valid_int?(number) || number.to_f.to_s == number end def format_number(num) if num.include?('.') num.to_f else num.to_i end end def fmt_currency(num) "$#{format('%.2f', num)}" end def loan_amount_input prompt "What's the loan amount?" amount = 0 loop do amount = gets.chomp break if valid_number?(amount) prompt 'Please enter a valid loan amount.' end format_number(amount) end def annual_rate_input prompt "What's the annual rate of interest (APR)?" rate = 0 loop do rate = gets.chomp break if valid_number?(rate) prompt 'Please enter a valid rate of interest. Eg for 5% APR enter `5`' end format_number(rate) / 100.0 end def duration_input prompt "What's the loan duration in months?" duration = 0 loop do duration = gets.chomp break if valid_int?(duration) prompt 'Please enter a valid duration. Eg for 5 years enter `60`' end format_number(duration) end def inputs loan_amount = loan_amount_input annual_rate = annual_rate_input duration_in_months = duration_input [loan_amount, annual_rate, duration_in_months] end def calculate(amount, rate, duration) monthly_rate = rate / 12.0 amount * (monthly_rate / (1 - (1 + monthly_rate)**-duration)) end def main greet loan_amount, annual_rate, duration_in_months = inputs monthly_payment = calculate(loan_amount, annual_rate, duration_in_months) prompt "For a loan amount of #{fmt_currency(loan_amount)}, for #{duration_in_months} months, at #{format('%.2f', annual_rate * 100)}% annual interest, the amount to pay each month is #{fmt_currency(monthly_payment)}" end main <file_sep>/lesson_2/calculator_refactor.rb require 'yaml' MESSAGES = YAML.load_file('calculator_messages.yml') OP_VERB = { "1" => "op_add", "2" => "op_sub", "3" => "op_mul", "4" => "op_div" } def prompt(message) if MESSAGES.has_key? message puts "=> #{MESSAGES[message]}" else puts "=> #{message}" end end def valid_number?(num) if num.include? '.' num.to_f.to_s == num else num.to_i.to_s == num end end def format_number(num) if num.include? '.' num.to_f else num.to_i end end def get_number_input(message) loop do prompt message input = gets.chomp if valid_number?(input) break format_number(input) else prompt "number_error" end end end def get_op_input prompt "operator_prompt" loop do input = gets.chomp if %w(1 2 3 4).include?(input) break input else prompt "operator_error" end end end def calculate loop do number1 = get_number_input("number1_prompt") number2 = get_number_input("number2_prompt") operator = get_op_input prompt "#{OP_VERB[operator]} #{MESSAGES["op_message"]}" result = case operator when '1' then number1 + number2 when '2' then number1 - number2 when '3' then number1 * number2 when '4' then number1.to_f / number2 end prompt "#{MESSAGES["result"]} #{result}" prompt "again_prompt" answer = gets.chomp break unless answer.downcase.start_with?('y') end end def get_name loop do name = gets.chomp if name.empty? prompt "name_error" else break name.downcase.capitalize end end end def greet prompt "welcome" name = get_name prompt "#{MESSAGES["hi"]} #{name}!" end def main greet calculate prompt "bye" end main <file_sep>/lesson_2/rock_paper_scissors_bonus.rb require 'set' MAX_WINS = 5 VALID_CHOICES = %w[rock paper scissors lizard spock] WINNING_CHOICES = [ { player1: 'scissors', player2: 'paper' }, { player1: 'paper', player2: 'rock' }, { player1: 'rock', player2: 'lizard' }, { player1: 'lizard', player2: 'spock' }, { player1: 'spock', player2: 'scissors' }, { player1: 'scissors', player2: 'lizard' }, { player1: 'lizard', player2: 'paper' }, { player1: 'paper', player2: 'spock' }, { player1: 'spock', player2: 'rock' }, { player1: 'rock', player2: 'scissors' } ] WINNING_MESSAGE = { Set['scissors', 'paper'] => 'Scissors cut Paper', Set['paper', 'rock'] => 'Paper covers Rock', Set['rock', 'lizard'] => 'Rock crushes Lizard', Set['lizard', 'spock'] => 'Lizard poisons Spock', Set['spock', 'scissors'] => 'Spock smashes Scissors', Set['scissors', 'lizard'] => 'Scissors decapitate Lizard', Set['lizard', 'paper'] => 'Lizard eats Paper', Set['paper', 'spock'] => 'Paper disproves Spock', Set['spock', 'rock'] => 'Spock vaporizes Rock', Set['rock', 'scissors'] => 'Rock crushes Scissors' } INITIAL_SCORE = { user: 0, computer: 0 } def prompt(message) puts "=> #{message}" end def valid_choice?(choice) VALID_CHOICES.include?(choice) end def user_choice loop do prompt "Enter your choice (#{VALID_CHOICES.join(', ')})" choice = gets.chomp # Try to find a matching choice if user # entered 1 or 2 letter choice if choice.length <= 2 choice = VALID_CHOICES.find { |word| word.start_with?(choice) } end break choice if valid_choice?(choice) prompt "That's not a valid choice" end end def computer_choice VALID_CHOICES.sample end def win?(player1, player2) WINNING_CHOICES.include?(player1: player1, player2: player2) end def winning_message(player1, player2) WINNING_MESSAGE.fetch(Set[player1, player2], "") end # Returns 1 if player 1 wins, 0 if tie # and -1 if player 2 wins def result(player1, player2) if player1 == player2 0 elsif win?(player1, player2) 1 else -1 end end def result_message(result) case result when 0 then "It's a tie." when 1 then "You won!" when -1 then "Computer won." end end def display_result(winning_msg, result_msg) prompt winning_msg prompt result_msg end def quit? prompt 'Do you want to play again?' answer = gets.chomp !answer.downcase.start_with?('y') end def clear_screen system('clear') || system('cls') end def game_over?(score) score.values.max >= MAX_WINS end def update_score(score, result) updated_score = score.dup if result == -1 updated_score[:computer] += 1 elsif result == 1 updated_score[:user] += 1 end updated_score end def display_score(score) prompt "Score: User #{score[:user]} Computer #{score[:computer]}" end def display_grand_winner(score) if score[:user] > score[:computer] prompt "You are the GRAND WINNER!!!" else prompt "Computer is the GRAND WINNER!!!" end end def turn_choices choice = user_choice comp_choice = computer_choice [choice, comp_choice] end def play_game(score) loop do choice, comp_choice = turn_choices prompt "You chose #{choice}, computer chose #{comp_choice}" computed_result = result(choice, comp_choice) winning_msg = winning_message(choice, comp_choice) result_msg = result_message(computed_result) score = update_score(score, computed_result) display_result(winning_msg, result_msg) display_score(score) if game_over?(score) then break score elsif quit? then break false end clear_screen end end prompt 'Welcome to Rock, Paper, Scissors, Lizard, Spock!' updated_score = play_game(INITIAL_SCORE) display_grand_winner(updated_score) if updated_score prompt 'Thanks for playing. Have a good day!'
a10f31a1e3bcf3e0f3bbf5d57ab70ec818316582
[ "Ruby" ]
6
Ruby
royshouvik/rb101-programming-foundations
78552bcb2006166fd4da20896f01b10954aaa7bb
2bd59fb3e83cdae372760d8bc1a4d0580f409fbd
refs/heads/master
<file_sep># tig-stack-docker Really simple docker-compose setup with Telegraf, InfluxDB and Grafana which can be used to monitor a Docker host and the running containers. All images are based on the official images. I just added some basic configuration. ## Requirements * docker * docker-compose ## How to use Clone this repo and use `docker-compose up` to build the images and start the stack. Grafana will be available on port 3000 when the stack is up and running. You can login using `admin` as username and password. <file_sep>FROM grafana/grafana:latest MAINTAINER <NAME> <<EMAIL>> RUN apt-get update &&\ apt-get -y --no-install-recommends install netcat curl VOLUME ["/var/lib/grafana", "/var/lib/grafana/plugins", "/var/log/grafana", "/etc/grafana"] EXPOSE 3000 # Copy initial scripts COPY ./entrypoint.sh /entrypoint.sh COPY ./create-entities.sh /tmp/create-entities.sh # Copy dahsboards and datasources COPY conf/influxdb-datasource.json /tmp/influxdb-datasource.json COPY conf/containers-dashboard.json /tmp/containers-dashboard.json COPY conf/production-dashboard.json /tmp/production-dashboard.json RUN chmod a+x /entrypoint.sh /tmp/create-entities.sh ENTRYPOINT ["/entrypoint.sh"] <file_sep>FROM influxdb:alpine MAINTAINER <NAME> <<EMAIL>> ENV INFLUXDB_USER=${INFLUXDB_USER:-admin} ENV INFLUXDB_PASSWORD=${INFLUXDB_PASSWORD:-<PASSWORD>} ENV INFLUXDB_SUPPORT=${INFLUXDB_SUPPORT:-guest} ENV INFLUXDB_SUPPORT_PASS=${INFLUXDB_SUPPORT_PASS:-readonly} ADD /config/config.toml /etc/influxdb/influxdb.toml RUN \ apk add --update curl bash && \ rm -rf /var/cache/apk/* /tmp/* /var/tmp/* COPY entrypoint.sh /entrypoint.sh RUN chmod 0755 /entrypoint.sh # Expose the admin port EXPOSE 8083 # Expose the ssl http api port EXPOSE 8084 # Expose the http api port EXPOSE 8086 # raft protocol port used by the cluster #EXPOSE 8090 # protobuf protocol port used for replication #EXPOSE 8099 # volume used for storing database logs and data VOLUME ["/data"] # volume used for storing debug logs VOLUME ["/logs"] ENTRYPOINT ["/entrypoint.sh"] CMD ["influxd", "-config", "/etc/influxdb/influxdb.toml"] <file_sep>#!/bin/bash # create predefined database with metrics name export DB_NAME=${DB_NAME:-metrics} sleep 12 && curl -s -G http://localhost:8086/query --data-urlencode "q=CREATE USER "$INFLUXDB_USER" WITH PASSWORD '$<PASSWORD>' WITH ALL PRIVILEGES" && curl -s -G http://localhost:8086/query --data-urlencode "u=$INFLUXDB_USER" --data-urlencode "p=$INFLUXDB_PASSWORD" --data-urlencode "q=CREATE DATABASE $DB_NAME" && curl -s -G http://localhost:8086/query --data-urlencode "u=$INFLUXDB_USER" --data-urlencode "p=$INFLUXDB_PASSWORD" --data-urlencode "q=CREATE USER "$INFLUXDB_SUPPORT" WITH PASSWORD '$<PASSWORD>'" && curl -s -G http://localhost:8086/query --data-urlencode "u=$INFLUXDB_USER" --data-urlencode "p=$INFLUXDB_PASSWORD" --data-urlencode "q=GRANT READ ON $DB_NAME TO $INFLUXDB_SUPPORT" & exec "$@" <file_sep>#!/bin/bash # Influx URL do not need for Docker compose --> using Docker service variables instead #export INFLUX_URL=${INFLUX_URL:-172.17.0.2:8086} # Credentials and DB export INFLUX_DB=${INFLUX_DB:-metrics} export INFLUX_USER=${INFLUX_USER:-admin} export INFLUX_PASSWORD=${INFLUX_PASSWORD:-<PASSWORD>} sed -i -e "s/_INFLUX_/$INFLUXDB_PORT_8086_TCP_ADDR:$INFLUXDB_PORT_8086_TCP_PORT/g" -e "s/_INFLUXDB_/$INFLUX_DB/g" -e "s/_INFLUXUSER_/$INFLUX_USER/g" -e "s/_INFLUXPASS_/$INFLUX_PASSWORD/g" "${TELEGRAF_CONFIG}" exec "$@" <file_sep>FROM telegraf:alpine MAINTAINER <NAME> <<EMAIL>> ENV TELEGRAF_CONFIG /etc/telegraf/telegraf.conf RUN apk add --update bash sed\ && rm -rf /var/cache/apk/* /tmp/* /var/tmp/* ADD /config/telegraf.conf /etc/telegraf/ COPY entrypoint.sh /entrypoint.sh RUN chmod 0755 /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] CMD ["telegraf"] <file_sep>#!/bin/bash # Grafana variables export HOST=localhost export PORT=3000 export CREDENTIALS=admin:admin while ! echo "quit" | nc $HOST 3000 | grep HTTP do echo "Grafana is not started yet - `date`" sleep 3 done sed -i -e "s/_INFLUX_/$INFLUXDB_PORT_8086_TCP_ADDR:$INFLUXDB_PORT_8086_TCP_PORT/g" "/tmp/influxdb-datasource.json" # add datasources to grafana for item in $(ls /tmp/*-datasource.json); do curl -k -u $CREDENTIALS -H 'content-type: application/json' http://$HOST:$PORT/api/datasources -d@$item; echo "Datasource imported: $item" sleep 2 done # add dashboards for item in $(ls /tmp/*-dashboard.json); do curl -k -u $CREDENTIALS -H 'content-type: application/json' http://$HOST:$PORT/api/dashboards/db -d@$item; echo "Dashboard imported: $item" sleep 2 done
87544819c3a83f067f23691116732d809bc38da5
[ "Markdown", "Dockerfile", "Shell" ]
7
Markdown
viveleroy/tig-stack-docker
815bed6e880dbb678ace97615853d46324e814f4
9212f3d9a6e9018bd94af10cab3a035221480aa1
refs/heads/master
<file_sep># riak-for-travis This repo builds standalone Riak binary tarballs from source for use in Travis container builds and anywhere else the usual Debian packages may be problematic. After a particular version of Riak is built, version-specific config files (from `config/riak-<version>/`) are copied over the default configs and the whole lot is bundled up into a tarball. The tarballs are named for the Riak version they contain (`riak-1.4.12.tar.bz2`, for example) but the directory they extract to is simply `riak`. If multiple versions are needed on the same machine, make sure to move or rename them. <file_sep>#!/bin/bash -e RIAK_VERSION=$1; shift ERLANG_VERSION=$1; shift URL_BASE="http://s3.amazonaws.com/downloads.basho.com/riak" SHORT_VERSION="${RIAK_VERSION%.*}" wget $URL_BASE/$SHORT_VERSION/$RIAK_VERSION/riak-$RIAK_VERSION.tar.gz tar zxvf riak-$RIAK_VERSION.tar.gz cd riak-$RIAK_VERSION . ~/otp/$ERLANG_VERSION/activate make rel
10e7925b7fdbd18eebbf883bbea53099b5cee6d8
[ "Markdown", "Shell" ]
2
Markdown
praekelt/riak-for-travis
22554a8bf97b577a897899fbc75558cfcac6c175
f993f61b9ab5e80b407f38f9eaf187381ebad22b
refs/heads/master
<file_sep>import path from 'path' import test from 'ava' import sao from 'sao' const template = path.join(__dirname, '..') test('defaults', async t => { const stream = await sao.mockPrompt(template, { // To make local and CI generate same result // We need to use fake data for these fields author: 'fake-name', gitUser: 'fake-name', email: 'fake-email', description: 'lol' }) t.snapshot(stream.meta.merged, 'template data') t.snapshot(stream.fileContents('README.md'), 'readme') t.snapshot(stream.fileContents('package.json'), 'package.json') t.snapshot(stream.fileContents('circle.yml'), 'circle.yml') t.snapshot(stream.fileList, 'files') }) <file_sep># create-react-component-with-no-config [![NPM version](https://img.shields.io/npm/v/create-react-component-with-no-config.svg?style=flat)](https://npmjs.com/package/create-react-component-with-no-config) [![NPM downloads](https://img.shields.io/npm/dm/create-react-component-with-no-config.svg?style=flat)](https://npmjs.com/package/create-react-component-with-no-config) [![CircleCI](https://circleci.com/gh/luyilin/create-react-component-with-no-config/tree/master.svg?style=shield)](https://circleci.com/gh/luyilin/create-react-component-with-no-config/tree/master) Create React component with no configurations. Inspired by the awesome [vue-land/create-vue-component](https://github.com/vue-land/create-vue-component), now you can create a react component just like it! ## Install ```bash yarn global add create-react-component-with-no-config ``` ## Usage ```bash create-react-component-with-no-config react-xxx # or create-react-component react-xxx # or type less crc react-xxx # you can also create component in place mkdir react-xxx && cd react-xxx crc ``` The folder struture of generated project (no config files!): ![structure](https://wx3.sinaimg.cn/mw690/a2117cdbly1fnxfc4mh6mj20jq0cddgw.jpg) ## Documentation ### folder structure - `src/index.jsx`: Your fancy component - `example/index.jsx`: Entry file of your demo ### npm scripts - `yarn example`: Run the demo for your component (with [Poi](https://poi.js.org)) - `yarn example:build`: Build the demo for your component (with [Poi](https://poi.js.org)) - `yarn build`: Build your component (with [Bili](https://github.com/egoist/bili)) - `yarn test`: Lint and test your component (with [Jest](https://github.com/facebook/jest)) - `yarn lint`: Lint only. ### badges The generated `README.md` in your project contains the badges of `npm version`, `npm downloads` and `circleci status`. ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D ## Author [MIT](./LICENSE) License <br> > [minemine.cc](https://minemine.cc) · GitHub [@luyilin](https://github.com/luyilin) · Twitter [@luyilin12](https://twitter.com/luyilin12) <file_sep># Snapshot report for `test/test.js` The actual snapshot is saved in `test.js.snap`. Generated by [AVA](https://ava.li). ## defaults > template data { _: { folderName: 'output', folderPath: '/fake-path/output', isNewFolder: true, pm: 'yarn', }, author: 'fake-name', componentName: 'HelloWorld', description: 'lol', email: 'fake-email', gitUser: 'fake-name', name: 'output', pascalCasedComponentName: 'HelloWorld', website: 'https://github.com/fake-name', } > readme `# output␊ ␊ [![NPM version](https://img.shields.io/npm/v/output.svg?style=flat)](https://npmjs.com/package/output) [![NPM downloads](https://img.shields.io/npm/dm/output.svg?style=flat)](https://npmjs.com/package/output) [![CircleCI](https://circleci.com/gh/fake-name/output/tree/master.svg?style=shield)](https://circleci.com/gh/fake-name/output/tree/master)␊ ␊ lol␊ ␊ ## Install␊ ␊ ```bash␊ yarn add output --save␊ ```␊ ␊ CDN: [UNPKG](https://unpkg.com/output/) | [jsDelivr](https://cdn.jsdelivr.net/npm/output/) (available as `window.HelloWorld`)␊ ␊ ## Usage␊ ␊ ```␊ import HelloWorld from 'output'␊ ␊ ReactDOM.render(␊ <HelloWorld></HelloWorld>␊ , mountNode)␊ ```␊ ␊ ## License␊ ␊ MIT &copy; [fake-name](https://github.com/fake-name)␊ ` > package.json `{␊ "name": "output",␊ "version": "0.0.0",␊ "description": "lol",␊ "repository": {␊ "url": "fake-name/output",␊ "type": "git"␊ },␊ "main": "dist/output.cjs.js",␊ "files": ["dist"],␊ "scripts": {␊ "prepublishOnly": "npm test && npm run build",␊ "lint": "eslint . --ext .js --ext .jsx",␊ "test": "npm run lint && jest",␊ "build": "bili",␊ "example": "poi --jsx react",␊ "build:example": "poi build --jsx react"␊ },␊ "author": {␊ "name": "fake-name",␊ "email": "fake-email"␊ },␊ "license": "MIT",␊ "poi": {␊ "entry": "example/index.jsx",␊ "dist": "example/dist",␊ "homepage": "./"␊ },␊ "bili": {␊ "format": [␊ "cjs",␊ "umd"␊ ]␊ },␊ "eslintConfig": {␊ "parser": "babel-eslint",␊ "extends": [␊ "plugin:react/recommended"␊ ]␊ },␊ "dependencies": {␊ "react": "^16.2.0",␊ "react-dom": "^16.2.0",␊ "prop-types": "^15.6.0"␊ },␊ "devDependencies": {␊ "poi": "^9.3.10",␊ "bili": "^1.3.3",␊ "eslint": "^4.14.0",␊ "jest": "^22.1.4",␊ "enzyme": "^3.3.0",␊ "enzyme-adapter-react-16": "^1.1.1",␊ "babel-jest": "^22.1.0",␊ "babel-preset-env": "^1.6.1",␊ "babel-preset-react": "^6.24.1",␊ "babel-eslint": "^8.2.1",␊ "eslint-plugin-react": "^7.6.0",␊ "babel-plugin-transform-class-properties": "^6.24.1"␊ }␊ }␊ ` > circle.yml `version: 2␊ jobs:␊ build:␊ working_directory: ~/repo␊ docker:␊ - image: circleci/node:latest␊ branches:␊ ignore:␊ - gh-pages # list of branches to ignore␊ - /release\\/.*/ # or ignore regexes␊ steps:␊ - checkout␊ - restore_cache:␊ key: dependency-cache-{{ checksum "yarn.lock" }}␊ - run:␊ name: install dependences␊ command: yarn install␊ - save_cache:␊ key: dependency-cache-{{ checksum "yarn.lock" }}␊ paths:␊ - ./node_modules␊ - run:␊ name: test␊ command: yarn run test␊ ` > files [ '.babelrc', '.editorconfig', '.gitignore', 'README.md', 'circle.yml', 'example/index.js', 'package.json', 'src/index.jsx', 'src/index.test.js', ] <file_sep>import React from 'react' import { configure, render } from 'enzyme' import Adapter from 'enzyme-adapter-react-16' import <%= pascalCasedComponentName %> from './' configure({ adapter: new Adapter() }) test('it works', () => { expect(render(<<%= pascalCasedComponentName %> />).text()).toEqual('Hello react') }) <file_sep>const superb = require('superb') const pascalCase = require('pascal-case') module.exports = { prompts: { name: { message: 'Type the package name', default: ':folderName:' }, description: { message: 'Describe this component', default() { return `My ${superb()} React component.` } }, componentName: { message: 'Type the component name in pascal-case', default: 'HelloWorld' }, author: { message: 'Type your name', default: ':gitUser:', store: true }, gitUser: { message: 'Type your GitHub username', default: ':gitUser:', store: true }, email: { message: 'Type your email address', default: ':gitEmail:', store: true }, website: { message: 'Type the url of your personal website', default({ gitUser }) { return `https://github.com/${gitUser}` }, store: true } }, data({ componentName }) { return { pascalCasedComponentName: pascalCase(componentName) } }, move: { gitignore: '.gitignore', // @see https://github.com/vue-land/create-vue-component/issues/1 '_package.json': 'package.json', editorconfig: '.editorconfig' }, post({ yarnInstall, gitInit, chalk, pm, isNewFolder, folderName }) { gitInit() yarnInstall() const cd = () => { if (isNewFolder) { console.log(` ${chalk.cyan('cd')} ${folderName}`) } } console.log() console.log(chalk.bold(` To run demo:\n`)) cd() console.log(` ${chalk.cyan(pm)} run example\n`) console.log(chalk.bold(` To build the component:\n`)) cd() console.log(` ${chalk.cyan(pm)} run build`) console.log() } } <file_sep>import React from 'react' import { render } from 'react-dom' import HelloWorld from '../src/index' const App = () => <HelloWorld></HelloWorld> render(<App />, document.getElementById('app')) <file_sep>#!/usr/bin/env node const path = require('path') const cac = require('cac') const sao = require('sao') const update = require('update-notifier') const pkg = require('./package') const cli = cac() cli.command('*', 'Generate a new project', input => { const folderName = input[0] || '.' const targetPath = path.resolve(folderName) console.log(`> Generating React component in ${targetPath}`) const templatePath = __dirname return sao({ template: templatePath, targetPath }).catch(err => { process.exitCode = 1 if (err.name === 'SAOError') { sao.log.error(err.message) } else { console.error(err.stack) } }) }) cli.parse() update({ pkg }).notify() <file_sep># <%= name %> [![NPM version](https://img.shields.io/npm/v/<%= name %>.svg?style=flat)](https://npmjs.com/package/<%= name %>) [![NPM downloads](https://img.shields.io/npm/dm/<%= name %>.svg?style=flat)](https://npmjs.com/package/<%= name %>) [![CircleCI](https://circleci.com/gh/<%= gitUser %>/<%= name %>/tree/master.svg?style=shield)](https://circleci.com/gh/<%= gitUser %>/<%= name %>/tree/master) <%- description %> ## Install ```bash yarn add <%= name %> --save ``` CDN: [UNPKG](https://unpkg.com/<%= name %>/) | [jsDelivr](https://cdn.jsdelivr.net/npm/<%= name %>/) (available as `window.<%= pascalCasedComponentName %>`) ## Usage ``` import <%= pascalCasedComponentName %> from '<%= name %>' ReactDOM.render( <<%= componentName %>></<%= componentName %>> , mountNode) ``` ## License MIT &copy; [<%= author %>](<%= website %>)
4f356164d7f8b5d10e0df1fbba0e5f5f80cda8ca
[ "JavaScript", "Markdown" ]
8
JavaScript
luyilin/create-react-component-with-no-config
b453ed7691c4c940e5581c8440fc1f6f5b98e0f7
fa9cb1a3e59046c05ba9ba3497efa26ec912823d
refs/heads/master
<repo_name>JPDvlpr/Park-It<file_sep>/mels/js/park-it.js // alert("hello!"); $(init); var storage; function init(){ //Third parameter has to with event bubbling and //capturing; use false for backward compatibility document.addEventListener("deviceready", onDeviceReady, false); storage = windo.localStorage; } function onDeviceReady() { //Load the correct stylesheet, depending on device var node = document.createElement('link'); node.setAttribute('rel', 'stylesheet'); node.setAttribute('type', 'text/css'); if (cordova.platformif == 'ios'){ $('head').append('<link rel="stylesheet" href="css/park-it-ios.css" type="text/css" />'); //prevents status bar from overlaying web view window.StatusBar.overrlaysWebView(false); window.StatusBar.styleDefault(); } else { $('head').append('<link rel="stylesheet" href="css/park-it-android.css" type="text/css" />'); //prevents status bar from overlaying web view window.StatusBar.backgroundColor("#1565C0"); } //What is happening here? $('head').appendChild(node); } function initMap() { var grc = {lat: 47.313582, lng: -122.1800072}; var tokyo = {lat: 35.6895, lng: 139.6917}; var mapDiv = new google.maps.Map(document.getElementById('map'),{ zoom: 6, center: grc }); var marker = new google.maps.Marker({ position: grc, map: mapDiv }); // alert("Hello!"); } $('#park').click(function () { alert("Set parking location"); } ); $('#retrieve').click(function () { alert("Get parking location"); } ); $('#gotIt').click(function () { $('#instructions').hide(); } );<file_sep>/parkItCordova/www/www/js/park-it.js // alert("hello!"); $(init); var storage; function init(){ //Third parameter has to with event bubbling and //capturing; use false for backward compatibility document.addEventListener("deviceready", onDeviceReady, false); storage = window.localStorage; } function onDeviceReady() { //Load the correct stylesheet, depending on device // var node = document.createElement('link'); // node.setAttribute('rel', 'stylesheet'); // node.setAttribute('type', 'text/css'); if (cordova.platformif == 'ios'){ $('head').append('<link rel="stylesheet" href="css/park-it-ios.css" type="text/css" />'); //prevents status bar from overlaying web view window.StatusBar.overrlaysWebView(false); window.StatusBar.styleDefault(); } else { $('head').append('<link rel="stylesheet" href="css/park-it-android.css" type="text/css" />'); //prevents status bar from overlaying web view window.StatusBar.backgroundColor("#1565C0"); } // //What is happening here? // $('head').appendChild(node); } function initMap() { var grc = {lat: 47.313582, lng: -122.1800072}; var tokyo = {lat: 35.6895, lng: 139.6917}; var mapDiv = new google.maps.Map(document.getElementById('map'),{ zoom: 6, center: grc }); var marker = new google.maps.Marker({ position: grc, map: mapDiv }); // alert("Hello!"); } function setParkingLocation(){ // alert("Trying to get location - in setParking location"); //got this navigator.geolocation.getCurrentPosition(setParkingLocationSuccess, setParkingLocationError, {enableHighAccuracy:true}); } function setParkingLocationSuccess(position){ // alert("Had success");//got this latitude = position.coords.latitude; // alert("Grabbed latitude"); //got this storage.setItem("parkedLatitude", latitude); // alert("Stored latitude:" + latitude); //worked // alert("Grabbed longitude"); // got this longitude = position.coords.longitude; // alert("Stored latitude"); // got this storage.setItem("parkedLongitude", longitude); // alert("Grabbed position"); //got this //Display an alert that shows the latitude and longitude navigator.notification.alert("Parking Location Saved. (Lat:" + storage.getItem("parkedLatitude") +", Long: " + storage.getItem("parkedLongitude") + ")"); //worked showParkingLocation(); } function setParkingLocationError(err) { alert("failed"); navigator.notification.alert("Error Code: " + error.code + "\nError Message: " + error.message); } function showParkingLocation(){ navigator.notification.alert("You are parked at Lat:" + storage.getItem("parkedLatitude") +", Long: " + storage.getItem("parkedLongitude")); //worked $('#instructions').hide(); $('#directions').hide(); } $('#park').click(function () { alert("Set parking location"); setParkingLocation(); } ); $('#retrieve').click(function () { alert("Get parking location"); } ); $('#gotIt').click(function () { $('#instructions').hide(); } );
08391a9bcc984687d4fe90f0cf42df7efdd5739c
[ "JavaScript" ]
2
JavaScript
JPDvlpr/Park-It
eed6f6b2f9990a81eff7c98aad181e2034e4c811
b33d2c920e2b17ab18f74a90dd88a9e192b0ff0c